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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
343dd1fb4f2af6c62a656a157c21cf03edcb7764 | [
"self.object = self.get_object()\nif not self.object.published and (not request.user.is_authenticated):\n raise Http404()\nelse:\n context = self.get_context_data(object=self.object)\n return self.render_to_response(context)",
"context = super().get_context_data(**kwargs)\nif self.object.responsive_banne... | <|body_start_0|>
self.object = self.get_object()
if not self.object.published and (not request.user.is_authenticated):
raise Http404()
else:
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
<|end_body_0|>
<|body_star... | Returns a single post. | PostDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostDetailView:
"""Returns a single post."""
def get(self, request, *args, **kwargs):
"""Returns a blog post."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Add banner sourceset and related posts to context data."""
<|body_1|>
def create_bann... | stack_v2_sparse_classes_75kplus_train_008900 | 3,911 | no_license | [
{
"docstring": "Returns a blog post.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Add banner sourceset and related posts to context data.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_027121 | Implement the Python class `PostDetailView` described below.
Class description:
Returns a single post.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a blog post.
- def get_context_data(self, **kwargs): Add banner sourceset and related posts to context data.
- def create_banner_s... | Implement the Python class `PostDetailView` described below.
Class description:
Returns a single post.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a blog post.
- def get_context_data(self, **kwargs): Add banner sourceset and related posts to context data.
- def create_banner_s... | 7a41c1c7623aca620555470e0c33d5c12ae52db0 | <|skeleton|>
class PostDetailView:
"""Returns a single post."""
def get(self, request, *args, **kwargs):
"""Returns a blog post."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Add banner sourceset and related posts to context data."""
<|body_1|>
def create_bann... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostDetailView:
"""Returns a single post."""
def get(self, request, *args, **kwargs):
"""Returns a blog post."""
self.object = self.get_object()
if not self.object.published and (not request.user.is_authenticated):
raise Http404()
else:
context = se... | the_stack_v2_python_sparse | site/blog/views.py | williamaurreav23/portfolio-snapshot | train | 0 |
9b58ef2b28761f7d76595ec670c015288dcf0c35 | [
"ans = []\nboard = [['.'] * n for _ in range(n)]\nself.fill_row(ans, board, [], n, 0)\nreturn ans",
"if row == n:\n ans.append([''.join(i) for i in board])\n return\nfor col in range(n):\n available = True\n for position in positions:\n if row == position[0] or col == position[1] or abs(row - p... | <|body_start_0|>
ans = []
board = [['.'] * n for _ in range(n)]
self.fill_row(ans, board, [], n, 0)
return ans
<|end_body_0|>
<|body_start_1|>
if row == n:
ans.append([''.join(i) for i in board])
return
for col in range(n):
available =... | 20190818 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""20190818"""
def solveNQueens(self, n: int) -> List[List[str]]:
"""暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了"""
<|body_0|>
def fill_row(self, ans: List[List[str]], board: List[List[str]], positions: List[tuple], n: int, row: int):
"""填入行""... | stack_v2_sparse_classes_75kplus_train_008901 | 1,601 | no_license | [
{
"docstring": "暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了",
"name": "solveNQueens",
"signature": "def solveNQueens(self, n: int) -> List[List[str]]"
},
{
"docstring": "填入行",
"name": "fill_row",
"signature": "def fill_row(self, ans: List[List[str]], board: List[List[str]], pos... | 2 | stack_v2_sparse_classes_30k_train_037069 | Implement the Python class `Solution` described below.
Class description:
20190818
Method signatures and docstrings:
- def solveNQueens(self, n: int) -> List[List[str]]: 暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了
- def fill_row(self, ans: List[List[str]], board: List[List[str]], positions: List[tuple], n: ... | Implement the Python class `Solution` described below.
Class description:
20190818
Method signatures and docstrings:
- def solveNQueens(self, n: int) -> List[List[str]]: 暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了
- def fill_row(self, ans: List[List[str]], board: List[List[str]], positions: List[tuple], n: ... | efea806d49f07d78e3db0390696778d4a7fc6c28 | <|skeleton|>
class Solution:
"""20190818"""
def solveNQueens(self, n: int) -> List[List[str]]:
"""暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了"""
<|body_0|>
def fill_row(self, ans: List[List[str]], board: List[List[str]], positions: List[tuple], n: int, row: int):
"""填入行""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""20190818"""
def solveNQueens(self, n: int) -> List[List[str]]:
"""暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了"""
ans = []
board = [['.'] * n for _ in range(n)]
self.fill_row(ans, board, [], n, 0)
return ans
def fill_row(self, ans: List[L... | the_stack_v2_python_sparse | ToolsX/leetcode/0051/0051.py | JunLei-MI/PythonX | train | 0 |
8ff1c1a4a2c37f981fe041be209f60fc5f7e98bc | [
"max_profit = 0\nfor i in range(1, len(prices)):\n max_profit += max(0, prices[i] - prices[i - 1])\nreturn max_profit",
"max_profit = 0\nfor k in range(1, len(prices)):\n max_profit = max(max_profit, prices[k] - prices[k - 1] + max_profit)\nreturn max_profit"
] | <|body_start_0|>
max_profit = 0
for i in range(1, len(prices)):
max_profit += max(0, prices[i] - prices[i - 1])
return max_profit
<|end_body_0|>
<|body_start_1|>
max_profit = 0
for k in range(1, len(prices)):
max_profit = max(max_profit, prices[k] - price... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
"""1-dimensional DP. dp[i] is the maximum profit at day i"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
max_profit = 0
... | stack_v2_sparse_classes_75kplus_train_008902 | 2,144 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": "1-dimensional DP. dp[i] is the maximum profit at day i",
"name": "maxProfit2",
"signature": "def maxProfit2(self, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): 1-dimensional DP. dp[i] is the maximum profit at day i | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): 1-dimensional DP. dp[i] is the maximum profit at day i
<|skeleton|>
class Soluti... | a5b02044ef39154b6a8d32eb57682f447e1632ba | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
"""1-dimensional DP. dp[i] is the maximum profit at day i"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
max_profit = 0
for i in range(1, len(prices)):
max_profit += max(0, prices[i] - prices[i - 1])
return max_profit
def maxProfit2(self, prices):
"""1-dimensional DP. dp[i] is... | the_stack_v2_python_sparse | algo/dp/best_time_to_buy_and_sell_stock_II.py | xys234/coding-problems | train | 0 | |
6100f1a09996674b67a958a7026ada368ae699fb | [
"nn.Module.__init__(self)\nself.eta = eta\nself.eps = eps",
"dist, _ = torch.min(torch.norm(c.unsqueeze(0) - input.unsqueeze(1), p=2, dim=2), dim=1)\nlosses = torch.where(semi_target == 0, dist ** 2, self.eta * (dist ** 2 + self.eps) ** semi_target.float())\nloss = torch.mean(losses)\nreturn loss"
] | <|body_start_0|>
nn.Module.__init__(self)
self.eta = eta
self.eps = eps
<|end_body_0|>
<|body_start_1|>
dist, _ = torch.min(torch.norm(c.unsqueeze(0) - input.unsqueeze(1), p=2, dim=2), dim=1)
losses = torch.where(semi_target == 0, dist ** 2, self.eta * (dist ** 2 + self.eps) ** ... | Implementation of the DMSAD loss inspired by Ghafoori et al. (2020) and Ruff et al. (2020) | DMSADLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DMSADLoss:
"""Implementation of the DMSAD loss inspired by Ghafoori et al. (2020) and Ruff et al. (2020)"""
def __init__(self, eta, eps=1e-06):
"""Constructor of the DMSAD loss. ---------- INPUT |---- eta (float) control the importance given to known or unknonw | samples. 1.0 gives e... | stack_v2_sparse_classes_75kplus_train_008903 | 18,386 | permissive | [
{
"docstring": "Constructor of the DMSAD loss. ---------- INPUT |---- eta (float) control the importance given to known or unknonw | samples. 1.0 gives equal weights, <1.0 gives more weight | to the unknown samples, >1.0 gives more weight to the | known samples. |---- eps (float) epsilon to ensure numerical sta... | 2 | stack_v2_sparse_classes_30k_train_052002 | Implement the Python class `DMSADLoss` described below.
Class description:
Implementation of the DMSAD loss inspired by Ghafoori et al. (2020) and Ruff et al. (2020)
Method signatures and docstrings:
- def __init__(self, eta, eps=1e-06): Constructor of the DMSAD loss. ---------- INPUT |---- eta (float) control the im... | Implement the Python class `DMSADLoss` described below.
Class description:
Implementation of the DMSAD loss inspired by Ghafoori et al. (2020) and Ruff et al. (2020)
Method signatures and docstrings:
- def __init__(self, eta, eps=1e-06): Constructor of the DMSAD loss. ---------- INPUT |---- eta (float) control the im... | 850b6195d6290a50eee865b4d5a66f5db5260e8f | <|skeleton|>
class DMSADLoss:
"""Implementation of the DMSAD loss inspired by Ghafoori et al. (2020) and Ruff et al. (2020)"""
def __init__(self, eta, eps=1e-06):
"""Constructor of the DMSAD loss. ---------- INPUT |---- eta (float) control the importance given to known or unknonw | samples. 1.0 gives e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DMSADLoss:
"""Implementation of the DMSAD loss inspired by Ghafoori et al. (2020) and Ruff et al. (2020)"""
def __init__(self, eta, eps=1e-06):
"""Constructor of the DMSAD loss. ---------- INPUT |---- eta (float) control the importance given to known or unknonw | samples. 1.0 gives equal weights,... | the_stack_v2_python_sparse | Code/src/models/optim/CustomLosses.py | antoine-spahr/X-ray-Anomaly-Detection | train | 3 |
1ff36e48d84621f3c8b25d4b227f240b837765f2 | [
"self.ai_settings = ai_settings\nself.reset_stats()\nself.game_active = False\nself.high_score = int(self.read_high_score_file())",
"self.ships_left = self.ai_settings.ship_limit\nself.score = 0\nself.level = 1",
"filename = 'high score.txt'\ntry:\n with open(filename) as file:\n return file.read()\ne... | <|body_start_0|>
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = False
self.high_score = int(self.read_high_score_file())
<|end_body_0|>
<|body_start_1|>
self.ships_left = self.ai_settings.ship_limit
self.score = 0
self.level = 1
<|end_body_1... | 跟踪游戏的统计信息 | GameStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, ai_settings):
"""初始化统计信息"""
<|body_0|>
def reset_stats(self):
"""初始化在游戏运行期间可能变化的统计信息"""
<|body_1|>
def read_high_score_file(self):
"""读取历史最高分"""
<|body_2|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_008904 | 782 | no_license | [
{
"docstring": "初始化统计信息",
"name": "__init__",
"signature": "def __init__(self, ai_settings)"
},
{
"docstring": "初始化在游戏运行期间可能变化的统计信息",
"name": "reset_stats",
"signature": "def reset_stats(self)"
},
{
"docstring": "读取历史最高分",
"name": "read_high_score_file",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_val_001501 | Implement the Python class `GameStats` described below.
Class description:
跟踪游戏的统计信息
Method signatures and docstrings:
- def __init__(self, ai_settings): 初始化统计信息
- def reset_stats(self): 初始化在游戏运行期间可能变化的统计信息
- def read_high_score_file(self): 读取历史最高分 | Implement the Python class `GameStats` described below.
Class description:
跟踪游戏的统计信息
Method signatures and docstrings:
- def __init__(self, ai_settings): 初始化统计信息
- def reset_stats(self): 初始化在游戏运行期间可能变化的统计信息
- def read_high_score_file(self): 读取历史最高分
<|skeleton|>
class GameStats:
"""跟踪游戏的统计信息"""
def __init__(... | 0bf5ce19d4282dcc615ae4e939893c1017fab1fd | <|skeleton|>
class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, ai_settings):
"""初始化统计信息"""
<|body_0|>
def reset_stats(self):
"""初始化在游戏运行期间可能变化的统计信息"""
<|body_1|>
def read_high_score_file(self):
"""读取历史最高分"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, ai_settings):
"""初始化统计信息"""
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = False
self.high_score = int(self.read_high_score_file())
def reset_stats(self):
"""初始化在游戏运行期间可能变化的统计信息"""
... | the_stack_v2_python_sparse | alien_invasion/game_stats.py | 957739315/little-items | train | 0 |
30fe53adae56c4b85722c60f173b3a2d20c48624 | [
"decl = suncxx.arguments()\nself.assertEqual(decl['PKGCHK']['help'], 'On Solaris systems, the package-checking program')\nself.assertEqual(decl['PKGCHK']['metavar'], 'PROG')\nself.assertEqual(decl['PKGINFO']['help'], 'On Solaris systems, the package information program')\nself.assertEqual(decl['PKGINFO']['metavar']... | <|body_start_0|>
decl = suncxx.arguments()
self.assertEqual(decl['PKGCHK']['help'], 'On Solaris systems, the package-checking program')
self.assertEqual(decl['PKGCHK']['metavar'], 'PROG')
self.assertEqual(decl['PKGINFO']['help'], 'On Solaris systems, the package information program')
... | Test SConsArguments.suncxx | Test_suncxx | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_suncxx:
"""Test SConsArguments.suncxx"""
def test_arguments1(self):
"""Test SConsArguments.suncxx.arguments()"""
<|body_0|>
def test_arguments__groups_1(self):
"""Test SConsArguments.suncxx.arguments() with groups (exclude, include)"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_008905 | 3,274 | permissive | [
{
"docstring": "Test SConsArguments.suncxx.arguments()",
"name": "test_arguments1",
"signature": "def test_arguments1(self)"
},
{
"docstring": "Test SConsArguments.suncxx.arguments() with groups (exclude, include)",
"name": "test_arguments__groups_1",
"signature": "def test_arguments__gr... | 3 | stack_v2_sparse_classes_30k_train_043140 | Implement the Python class `Test_suncxx` described below.
Class description:
Test SConsArguments.suncxx
Method signatures and docstrings:
- def test_arguments1(self): Test SConsArguments.suncxx.arguments()
- def test_arguments__groups_1(self): Test SConsArguments.suncxx.arguments() with groups (exclude, include)
- de... | Implement the Python class `Test_suncxx` described below.
Class description:
Test SConsArguments.suncxx
Method signatures and docstrings:
- def test_arguments1(self): Test SConsArguments.suncxx.arguments()
- def test_arguments__groups_1(self): Test SConsArguments.suncxx.arguments() with groups (exclude, include)
- de... | f4b783fc79fe3fc16e8d0f58308099a67752d299 | <|skeleton|>
class Test_suncxx:
"""Test SConsArguments.suncxx"""
def test_arguments1(self):
"""Test SConsArguments.suncxx.arguments()"""
<|body_0|>
def test_arguments__groups_1(self):
"""Test SConsArguments.suncxx.arguments() with groups (exclude, include)"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_suncxx:
"""Test SConsArguments.suncxx"""
def test_arguments1(self):
"""Test SConsArguments.suncxx.arguments()"""
decl = suncxx.arguments()
self.assertEqual(decl['PKGCHK']['help'], 'On Solaris systems, the package-checking program')
self.assertEqual(decl['PKGCHK']['met... | the_stack_v2_python_sparse | unit_tests/SConsArgumentsT/suncxxTests.py | mcqueen256/scons-arguments | train | 0 |
58fbe93a10bcc00e2ad447d3b43ca662c1492758 | [
"count = 0\nresult = 0\n\ndef dfs(node):\n nonlocal count, result\n if node.left:\n dfs(node.left)\n if count >= k:\n return\n count += 1\n result = node.val\n if node.right:\n dfs(node.right)\ndfs(root)\nreturn result",
"def helper(node, stack):\n while node:\n st... | <|body_start_0|>
count = 0
result = 0
def dfs(node):
nonlocal count, result
if node.left:
dfs(node.left)
if count >= k:
return
count += 1
result = node.val
if node.right:
dfs(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)"""
<|body_0|>
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Iterative Inorder-Traversal, Time: O(H+k), Space: O(H)"""
<|body_1... | stack_v2_sparse_classes_75kplus_train_008906 | 1,262 | no_license | [
{
"docstring": "Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)",
"name": "kthSmallest",
"signature": "def kthSmallest(self, root: TreeNode, k: int) -> int"
},
{
"docstring": "Iterative Inorder-Traversal, Time: O(H+k), Space: O(H)",
"name": "kthSmallest",
"signature": "def kthSmal... | 2 | stack_v2_sparse_classes_30k_train_024643 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root: TreeNode, k: int) -> int: Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)
- def kthSmallest(self, root: TreeNode, k: int) -> int: Iterative Ino... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root: TreeNode, k: int) -> int: Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)
- def kthSmallest(self, root: TreeNode, k: int) -> int: Iterative Ino... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)"""
<|body_0|>
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Iterative Inorder-Traversal, Time: O(H+k), Space: O(H)"""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)"""
count = 0
result = 0
def dfs(node):
nonlocal count, result
if node.left:
dfs(node.left)
if count >= ... | the_stack_v2_python_sparse | python/230-Kth Smallest Element in a BST.py | cwza/leetcode | train | 0 | |
7c6f75cf2cd5cfabdafa94af78cec7b86a2525f9 | [
"print('PIC CUTTING!!...')\nself.pic_path = pic_path\nself.save_dir = save_dir\nself.cut_size = cut_size\nself.H = H\nself.W = W\nself.img = cv.imread(self.pic_path)\nprint(self.img.shape)\nif self.H == None or self.W == None:\n raise ValueError('H,W should be int not None!!')",
"for j in range(self.W):\n d... | <|body_start_0|>
print('PIC CUTTING!!...')
self.pic_path = pic_path
self.save_dir = save_dir
self.cut_size = cut_size
self.H = H
self.W = W
self.img = cv.imread(self.pic_path)
print(self.img.shape)
if self.H == None or self.W == None:
r... | PICCUT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PICCUT:
def __init__(self, pic_path: os.path, save_dir: os.path, cut_size=256, H=None, W=None):
"""图像多线程切割类 :param pic_path: 图像路径 :param save_dir: 保存路径 :param cut_size: 剪裁大小"""
<|body_0|>
def pic_cut_(self, h, flag):
"""单线程切割函数 :param h: 行号 :param flag: 编号 :return: N... | stack_v2_sparse_classes_75kplus_train_008907 | 7,655 | no_license | [
{
"docstring": "图像多线程切割类 :param pic_path: 图像路径 :param save_dir: 保存路径 :param cut_size: 剪裁大小",
"name": "__init__",
"signature": "def __init__(self, pic_path: os.path, save_dir: os.path, cut_size=256, H=None, W=None)"
},
{
"docstring": "单线程切割函数 :param h: 行号 :param flag: 编号 :return: NULL",
"name... | 3 | stack_v2_sparse_classes_30k_train_038496 | Implement the Python class `PICCUT` described below.
Class description:
Implement the PICCUT class.
Method signatures and docstrings:
- def __init__(self, pic_path: os.path, save_dir: os.path, cut_size=256, H=None, W=None): 图像多线程切割类 :param pic_path: 图像路径 :param save_dir: 保存路径 :param cut_size: 剪裁大小
- def pic_cut_(self... | Implement the Python class `PICCUT` described below.
Class description:
Implement the PICCUT class.
Method signatures and docstrings:
- def __init__(self, pic_path: os.path, save_dir: os.path, cut_size=256, H=None, W=None): 图像多线程切割类 :param pic_path: 图像路径 :param save_dir: 保存路径 :param cut_size: 剪裁大小
- def pic_cut_(self... | a0f45c2fd8f7a275dcb20da9a1e1fa02edade5fc | <|skeleton|>
class PICCUT:
def __init__(self, pic_path: os.path, save_dir: os.path, cut_size=256, H=None, W=None):
"""图像多线程切割类 :param pic_path: 图像路径 :param save_dir: 保存路径 :param cut_size: 剪裁大小"""
<|body_0|>
def pic_cut_(self, h, flag):
"""单线程切割函数 :param h: 行号 :param flag: 编号 :return: N... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PICCUT:
def __init__(self, pic_path: os.path, save_dir: os.path, cut_size=256, H=None, W=None):
"""图像多线程切割类 :param pic_path: 图像路径 :param save_dir: 保存路径 :param cut_size: 剪裁大小"""
print('PIC CUTTING!!...')
self.pic_path = pic_path
self.save_dir = save_dir
self.cut_size = c... | the_stack_v2_python_sparse | GLACIERSPLIT/pic_/PicCutThread.py | qxcnwu/glacier | train | 1 | |
9ac8da229d3ff208dc41fb10573b94dd366e0b63 | [
"self.__message = message or 'Deprecated method'\nself.__logger = logger or None\nself.__already_logged = False",
"if not self.__already_logged:\n stack = '\\n\\t'.join(traceback.format_stack())\n logging.getLogger(self.__logger).warning('%s: %s\\n%s', method_name, self.__message, stack)\n self.__already... | <|body_start_0|>
self.__message = message or 'Deprecated method'
self.__logger = logger or None
self.__already_logged = False
<|end_body_0|>
<|body_start_1|>
if not self.__already_logged:
stack = '\n\t'.join(traceback.format_stack())
logging.getLogger(self.__logg... | Prints a warning when using the decorated method | Deprecated | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Deprecated:
"""Prints a warning when using the decorated method"""
def __init__(self, message=None, logger=None):
"""Sets the deprecation message, e.g. to indicate which method to call instead. If a logger is given, its 'warning' method will be called to print the message; else the s... | stack_v2_sparse_classes_75kplus_train_008908 | 20,075 | permissive | [
{
"docstring": "Sets the deprecation message, e.g. to indicate which method to call instead. If a logger is given, its 'warning' method will be called to print the message; else the standard 'print' method will be used. :param message: Message to be printed :param logger: The name of the logger to use, or None.... | 3 | stack_v2_sparse_classes_30k_train_043322 | Implement the Python class `Deprecated` described below.
Class description:
Prints a warning when using the decorated method
Method signatures and docstrings:
- def __init__(self, message=None, logger=None): Sets the deprecation message, e.g. to indicate which method to call instead. If a logger is given, its 'warnin... | Implement the Python class `Deprecated` described below.
Class description:
Prints a warning when using the decorated method
Method signatures and docstrings:
- def __init__(self, message=None, logger=None): Sets the deprecation message, e.g. to indicate which method to call instead. If a logger is given, its 'warnin... | 1d0add361ca219da8fdf72bb9ba8cb0ade01ad2f | <|skeleton|>
class Deprecated:
"""Prints a warning when using the decorated method"""
def __init__(self, message=None, logger=None):
"""Sets the deprecation message, e.g. to indicate which method to call instead. If a logger is given, its 'warning' method will be called to print the message; else the s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Deprecated:
"""Prints a warning when using the decorated method"""
def __init__(self, message=None, logger=None):
"""Sets the deprecation message, e.g. to indicate which method to call instead. If a logger is given, its 'warning' method will be called to print the message; else the standard 'prin... | the_stack_v2_python_sparse | pelix/utilities.py | tcalmant/ipopo | train | 67 |
1f339091d4d17b82737552178a4e467d0bbda83a | [
"self.A = [[0.9583615, 0.0001809, 0.0414576], [0.0117296, 0.7786373, 0.2096332], [0.042159, 0.2244591, 0.7333819]]\nself.C = [[0.1217175, 0.1197142, 0.1388058, 0.1273634, 0.1863004], [0, 0, 0, 0, 0.4107128], [0.0702153, 0.0574256, 0.0518409, 0.0491597, -0.3574271]]\nself.R = [{'mean': 1.2427012, 'std_dev': 2.248914... | <|body_start_0|>
self.A = [[0.9583615, 0.0001809, 0.0414576], [0.0117296, 0.7786373, 0.2096332], [0.042159, 0.2244591, 0.7333819]]
self.C = [[0.1217175, 0.1197142, 0.1388058, 0.1273634, 0.1863004], [0, 0, 0, 0, 0.4107128], [0.0702153, 0.0574256, 0.0518409, 0.0491597, -0.3574271]]
self.R = [{'mea... | Wake up periodically and Scale the cluster with an ARHMM Reserve Policy This scaler uses an ARHMM reserve policy to request and release server resources from the cluster. | ARHMMReservePolicy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ARHMMReservePolicy:
"""Wake up periodically and Scale the cluster with an ARHMM Reserve Policy This scaler uses an ARHMM reserve policy to request and release server resources from the cluster."""
def __init__(self, sim, scale_rate, startup_delay_func, shutdown_delay, five_minute_counts_file... | stack_v2_sparse_classes_75kplus_train_008909 | 14,183 | no_license | [
{
"docstring": "Initializes a ARHMMReservePolicy object parameters: sim -- The Simulation containing a cluster cluster object this scale function is managing scale_rate -- The interarrival time between scale events in seconds startup_delay_func -- A callable that returns the time a server spends in the booting ... | 3 | null | Implement the Python class `ARHMMReservePolicy` described below.
Class description:
Wake up periodically and Scale the cluster with an ARHMM Reserve Policy This scaler uses an ARHMM reserve policy to request and release server resources from the cluster.
Method signatures and docstrings:
- def __init__(self, sim, sca... | Implement the Python class `ARHMMReservePolicy` described below.
Class description:
Wake up periodically and Scale the cluster with an ARHMM Reserve Policy This scaler uses an ARHMM reserve policy to request and release server resources from the cluster.
Method signatures and docstrings:
- def __init__(self, sim, sca... | 30dc0702f6189307ff776525a2f3006ec471de47 | <|skeleton|>
class ARHMMReservePolicy:
"""Wake up periodically and Scale the cluster with an ARHMM Reserve Policy This scaler uses an ARHMM reserve policy to request and release server resources from the cluster."""
def __init__(self, sim, scale_rate, startup_delay_func, shutdown_delay, five_minute_counts_file... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ARHMMReservePolicy:
"""Wake up periodically and Scale the cluster with an ARHMM Reserve Policy This scaler uses an ARHMM reserve policy to request and release server resources from the cluster."""
def __init__(self, sim, scale_rate, startup_delay_func, shutdown_delay, five_minute_counts_file):
""... | the_stack_v2_python_sparse | appsim/scaler/reserve_policy.py | bmbouter/vcl_simulation | train | 0 |
1d6fa9658b768dfc4379d1a8165669ff19b24561 | [
"if self.student_id:\n self.roll_no = self.student_id.roll_no\n self.classes = self.student_id.standard_id\n self.student_code = self.student_id.student_code",
"rec = self.env['student.student'].search([])\nfor x in rec:\n if self.student_code == x.student_code:\n self.campus = x.school_id.id\n... | <|body_start_0|>
if self.student_id:
self.roll_no = self.student_id.roll_no
self.classes = self.student_id.standard_id
self.student_code = self.student_id.student_code
<|end_body_0|>
<|body_start_1|>
rec = self.env['student.student'].search([])
for x in rec:
... | Defining a Teacher information | SchoolWarning | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchoolWarning:
"""Defining a Teacher information"""
def onchange_student(self):
"""Method to get standard and roll no of student selected"""
<|body_0|>
def onchange_student33(self):
"""Method to get standard and roll no of student selected"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_008910 | 3,205 | no_license | [
{
"docstring": "Method to get standard and roll no of student selected",
"name": "onchange_student",
"signature": "def onchange_student(self)"
},
{
"docstring": "Method to get standard and roll no of student selected",
"name": "onchange_student33",
"signature": "def onchange_student33(se... | 3 | null | Implement the Python class `SchoolWarning` described below.
Class description:
Defining a Teacher information
Method signatures and docstrings:
- def onchange_student(self): Method to get standard and roll no of student selected
- def onchange_student33(self): Method to get standard and roll no of student selected
- ... | Implement the Python class `SchoolWarning` described below.
Class description:
Defining a Teacher information
Method signatures and docstrings:
- def onchange_student(self): Method to get standard and roll no of student selected
- def onchange_student33(self): Method to get standard and roll no of student selected
- ... | 043857268cccf78e96bcd236245f24c172d0dde8 | <|skeleton|>
class SchoolWarning:
"""Defining a Teacher information"""
def onchange_student(self):
"""Method to get standard and roll no of student selected"""
<|body_0|>
def onchange_student33(self):
"""Method to get standard and roll no of student selected"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SchoolWarning:
"""Defining a Teacher information"""
def onchange_student(self):
"""Method to get standard and roll no of student selected"""
if self.student_id:
self.roll_no = self.student_id.roll_no
self.classes = self.student_id.standard_id
self.stude... | the_stack_v2_python_sparse | meli_mis/addons/school/models/warning.py | ponnamsandy/karimi | train | 0 |
379fe69a1a0a2779bc0b63ae85f11728488c294a | [
"if internal:\n return cls.INTERNAL_MAP_LOCATION % (buildroot, suffix)\nreturn cls.EXTERNAL_MAP_LOCATION % (buildroot, suffix)",
"configs = cls(by_compat_id=collections.defaultdict(set), by_arch_useflags=collections.defaultdict(set))\nfor key in keys:\n compat_id = compat_ids[key]\n configs.by_compat_id[... | <|body_start_0|>
if internal:
return cls.INTERNAL_MAP_LOCATION % (buildroot, suffix)
return cls.EXTERNAL_MAP_LOCATION % (buildroot, suffix)
<|end_body_0|>
<|body_start_1|>
configs = cls(by_compat_id=collections.defaultdict(set), by_arch_useflags=collections.defaultdict(set))
... | A tuple of dicts describing our Chrome PFQs. Members: by_compat_id: A dict mapping CompatIds to sets of BoardKey objects. by_arch_useflags: A dict mapping (arch, useflags) tuples to sets of BoardKey objects. | PrebuiltMapping | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrebuiltMapping:
"""A tuple of dicts describing our Chrome PFQs. Members: by_compat_id: A dict mapping CompatIds to sets of BoardKey objects. by_arch_useflags: A dict mapping (arch, useflags) tuples to sets of BoardKey objects."""
def GetFilename(cls, buildroot, suffix, internal=True):
... | stack_v2_sparse_classes_75kplus_train_008911 | 10,665 | permissive | [
{
"docstring": "Get the filename where we should store our JSON dump. Args: buildroot: The root of the source tree. suffix: The base filename used for the dump (e.g. \"chrome\"). internal: If true, use the internal binhost location. Otherwise, use the public one.",
"name": "GetFilename",
"signature": "d... | 5 | stack_v2_sparse_classes_30k_train_008767 | Implement the Python class `PrebuiltMapping` described below.
Class description:
A tuple of dicts describing our Chrome PFQs. Members: by_compat_id: A dict mapping CompatIds to sets of BoardKey objects. by_arch_useflags: A dict mapping (arch, useflags) tuples to sets of BoardKey objects.
Method signatures and docstri... | Implement the Python class `PrebuiltMapping` described below.
Class description:
A tuple of dicts describing our Chrome PFQs. Members: by_compat_id: A dict mapping CompatIds to sets of BoardKey objects. by_arch_useflags: A dict mapping (arch, useflags) tuples to sets of BoardKey objects.
Method signatures and docstri... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class PrebuiltMapping:
"""A tuple of dicts describing our Chrome PFQs. Members: by_compat_id: A dict mapping CompatIds to sets of BoardKey objects. by_arch_useflags: A dict mapping (arch, useflags) tuples to sets of BoardKey objects."""
def GetFilename(cls, buildroot, suffix, internal=True):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrebuiltMapping:
"""A tuple of dicts describing our Chrome PFQs. Members: by_compat_id: A dict mapping CompatIds to sets of BoardKey objects. by_arch_useflags: A dict mapping (arch, useflags) tuples to sets of BoardKey objects."""
def GetFilename(cls, buildroot, suffix, internal=True):
"""Get the... | the_stack_v2_python_sparse | third_party/chromite/cbuildbot/binhost.py | metux/chromium-suckless | train | 5 |
be0dc0d021f0a1fa68a02bf2c5ea3511fd69901c | [
"if n <= 0:\n return 0\nif n == 1:\n return 1\nreturn self.Feibonacci1(n - 1) + self.Feibonacci1(n - 2)",
"res = [0, 1]\nif n < 2:\n return res[n]\nfib1 = 1\nfib2 = 0\nfib_n = 0\nfor i in range(2, n + 1):\n fib_n = fib1 + fib2\n fib2 = fib1\n fib1 = fib_n\nreturn fib_n",
"res = [0, 1, 2]\nif n... | <|body_start_0|>
if n <= 0:
return 0
if n == 1:
return 1
return self.Feibonacci1(n - 1) + self.Feibonacci1(n - 2)
<|end_body_0|>
<|body_start_1|>
res = [0, 1]
if n < 2:
return res[n]
fib1 = 1
fib2 = 0
fib_n = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def Feibonacci1(self, n):
"""递归思想"""
<|body_0|>
def Feibonacci2(self, n):
"""自下而上,循环的思想"""
<|body_1|>
def jumpFloor1(self, n):
"""青蛙跳台阶, 每次可以跳1级或2级"""
<|body_2|>
def jumpFloor2(self, n):
"""青蛙跳台阶,每次可以跳1级、2级...n级。"""... | stack_v2_sparse_classes_75kplus_train_008912 | 1,529 | no_license | [
{
"docstring": "递归思想",
"name": "Feibonacci1",
"signature": "def Feibonacci1(self, n)"
},
{
"docstring": "自下而上,循环的思想",
"name": "Feibonacci2",
"signature": "def Feibonacci2(self, n)"
},
{
"docstring": "青蛙跳台阶, 每次可以跳1级或2级",
"name": "jumpFloor1",
"signature": "def jumpFloor1(s... | 4 | stack_v2_sparse_classes_30k_test_000839 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Feibonacci1(self, n): 递归思想
- def Feibonacci2(self, n): 自下而上,循环的思想
- def jumpFloor1(self, n): 青蛙跳台阶, 每次可以跳1级或2级
- def jumpFloor2(self, n): 青蛙跳台阶,每次可以跳1级、2级...n级。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Feibonacci1(self, n): 递归思想
- def Feibonacci2(self, n): 自下而上,循环的思想
- def jumpFloor1(self, n): 青蛙跳台阶, 每次可以跳1级或2级
- def jumpFloor2(self, n): 青蛙跳台阶,每次可以跳1级、2级...n级。
<|skeleton|>... | 14fb97af36c5fb1d69439585adb0db0ce9eae45d | <|skeleton|>
class Solution:
def Feibonacci1(self, n):
"""递归思想"""
<|body_0|>
def Feibonacci2(self, n):
"""自下而上,循环的思想"""
<|body_1|>
def jumpFloor1(self, n):
"""青蛙跳台阶, 每次可以跳1级或2级"""
<|body_2|>
def jumpFloor2(self, n):
"""青蛙跳台阶,每次可以跳1级、2级...n级。"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def Feibonacci1(self, n):
"""递归思想"""
if n <= 0:
return 0
if n == 1:
return 1
return self.Feibonacci1(n - 1) + self.Feibonacci1(n - 2)
def Feibonacci2(self, n):
"""自下而上,循环的思想"""
res = [0, 1]
if n < 2:
ret... | the_stack_v2_python_sparse | 斐波拉契数列.py | zhanvwei/targetoffer | train | 0 | |
3248b044a38f8f177a84c24d2eda205f09e9c038 | [
"diagnostic = SupplyTempAIRCx()\nif isinstance(diagnostic, SupplyTempAIRCx):\n assert True\nelse:\n assert False",
"diagnostic = SupplyTempAIRCx()\ndata_window = td(minutes=1)\ndiagnostic.set_class_values({}, 1, data_window, False, {}, 4.0, 4.0, {}, {}, 2, 3, {}, 5, 'test', 'test_c', [])\nassert diagnostic.... | <|body_start_0|>
diagnostic = SupplyTempAIRCx()
if isinstance(diagnostic, SupplyTempAIRCx):
assert True
else:
assert False
<|end_body_0|>
<|body_start_1|>
diagnostic = SupplyTempAIRCx()
data_window = td(minutes=1)
diagnostic.set_class_values({}, 1... | Contains all the tests for SupplyTempAIRCx Diagnostic | TestDiagnosticsSupplyTempAIRCx | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDiagnosticsSupplyTempAIRCx:
"""Contains all the tests for SupplyTempAIRCx Diagnostic"""
def test_temp_sensor_dx_creation(self):
"""test the creation of temp sensor diagnostic class"""
<|body_0|>
def test_temp_sensor_dx_set_class_values(self):
"""test the crea... | stack_v2_sparse_classes_75kplus_train_008913 | 14,928 | permissive | [
{
"docstring": "test the creation of temp sensor diagnostic class",
"name": "test_temp_sensor_dx_creation",
"signature": "def test_temp_sensor_dx_creation(self)"
},
{
"docstring": "test the creation of temp sensor diagnostic class",
"name": "test_temp_sensor_dx_set_class_values",
"signat... | 6 | stack_v2_sparse_classes_30k_train_008478 | Implement the Python class `TestDiagnosticsSupplyTempAIRCx` described below.
Class description:
Contains all the tests for SupplyTempAIRCx Diagnostic
Method signatures and docstrings:
- def test_temp_sensor_dx_creation(self): test the creation of temp sensor diagnostic class
- def test_temp_sensor_dx_set_class_values... | Implement the Python class `TestDiagnosticsSupplyTempAIRCx` described below.
Class description:
Contains all the tests for SupplyTempAIRCx Diagnostic
Method signatures and docstrings:
- def test_temp_sensor_dx_creation(self): test the creation of temp sensor diagnostic class
- def test_temp_sensor_dx_set_class_values... | 24d50729aef8d91036cc13b0f5c03be76f3237ed | <|skeleton|>
class TestDiagnosticsSupplyTempAIRCx:
"""Contains all the tests for SupplyTempAIRCx Diagnostic"""
def test_temp_sensor_dx_creation(self):
"""test the creation of temp sensor diagnostic class"""
<|body_0|>
def test_temp_sensor_dx_set_class_values(self):
"""test the crea... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDiagnosticsSupplyTempAIRCx:
"""Contains all the tests for SupplyTempAIRCx Diagnostic"""
def test_temp_sensor_dx_creation(self):
"""test the creation of temp sensor diagnostic class"""
diagnostic = SupplyTempAIRCx()
if isinstance(diagnostic, SupplyTempAIRCx):
assert... | the_stack_v2_python_sparse | EnergyEfficiency/AirsideRCxAgent/airside/test.py | shwethanidd/volttron-pnnl-applications-2 | train | 0 |
6878907f9fd3b3ae273e4c58d5ecb2091a4a5da0 | [
"if not self.queue:\n return '#'\nelse:\n return self.queue[0]",
"if char in self.d.keys():\n self.d[char] += 1\nelse:\n self.d[char] = 1\n self.queue.append(char)\nwhile self.queue and self.d[self.queue[0]] > 1:\n self.queue.pop(0)"
] | <|body_start_0|>
if not self.queue:
return '#'
else:
return self.queue[0]
<|end_body_0|>
<|body_start_1|>
if char in self.d.keys():
self.d[char] += 1
else:
self.d[char] = 1
self.queue.append(char)
while self.queue and s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstAppearingOnce(self):
""":rtype: str"""
<|body_0|>
def insert(self, char):
""":type char: str :rtype: void"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.queue:
return '#'
else:
return s... | stack_v2_sparse_classes_75kplus_train_008914 | 777 | no_license | [
{
"docstring": ":rtype: str",
"name": "firstAppearingOnce",
"signature": "def firstAppearingOnce(self)"
},
{
"docstring": ":type char: str :rtype: void",
"name": "insert",
"signature": "def insert(self, char)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039637 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstAppearingOnce(self): :rtype: str
- def insert(self, char): :type char: str :rtype: void | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstAppearingOnce(self): :rtype: str
- def insert(self, char): :type char: str :rtype: void
<|skeleton|>
class Solution:
def firstAppearingOnce(self):
""":rtyp... | 967b0fbb40ae491b552bc3365a481e66324cb6f2 | <|skeleton|>
class Solution:
def firstAppearingOnce(self):
""":rtype: str"""
<|body_0|>
def insert(self, char):
""":type char: str :rtype: void"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def firstAppearingOnce(self):
""":rtype: str"""
if not self.queue:
return '#'
else:
return self.queue[0]
def insert(self, char):
""":type char: str :rtype: void"""
if char in self.d.keys():
self.d[char] += 1
els... | the_stack_v2_python_sparse | jianzhi_offer/43_字符流中第一个只出现一次的字符.py | ryanatgz/data_structure_and_algorithm | train | 0 | |
500cad510c1774e236f51681a70eb769a038f9c1 | [
"for subkey in application_identifiers_key.GetSubkeys():\n name = subkey.name.lower()\n if len(name) == 38 and name[0] == '{' and (name[37] == '}'):\n description = self._GetValueFromKey(subkey, '')\n yield ApplicationIdentifier(name, description)",
"application_identifiers_key = registry.GetK... | <|body_start_0|>
for subkey in application_identifiers_key.GetSubkeys():
name = subkey.name.lower()
if len(name) == 38 and name[0] == '{' and (name[37] == '}'):
description = self._GetValueFromKey(subkey, '')
yield ApplicationIdentifier(name, description)
... | Windows application identifiers collector. | ApplicationIdentifiersCollector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationIdentifiersCollector:
"""Windows application identifiers collector."""
def _CollectApplicationIdentifiers(self, application_identifiers_key):
"""Collects Windows application identifiers (AppID). Args: application_identifiers_key (dfwinreg.WinRegistryKey): application ident... | stack_v2_sparse_classes_75kplus_train_008915 | 1,906 | permissive | [
{
"docstring": "Collects Windows application identifiers (AppID). Args: application_identifiers_key (dfwinreg.WinRegistryKey): application identifiers Windows Registry key. Yields: ApplicationIdentifier: an application identifier.",
"name": "_CollectApplicationIdentifiers",
"signature": "def _CollectApp... | 2 | stack_v2_sparse_classes_30k_train_052300 | Implement the Python class `ApplicationIdentifiersCollector` described below.
Class description:
Windows application identifiers collector.
Method signatures and docstrings:
- def _CollectApplicationIdentifiers(self, application_identifiers_key): Collects Windows application identifiers (AppID). Args: application_ide... | Implement the Python class `ApplicationIdentifiersCollector` described below.
Class description:
Windows application identifiers collector.
Method signatures and docstrings:
- def _CollectApplicationIdentifiers(self, application_identifiers_key): Collects Windows application identifiers (AppID). Args: application_ide... | d149aff1b8ff97e1cc8d7416fc583b964bad4ccd | <|skeleton|>
class ApplicationIdentifiersCollector:
"""Windows application identifiers collector."""
def _CollectApplicationIdentifiers(self, application_identifiers_key):
"""Collects Windows application identifiers (AppID). Args: application_identifiers_key (dfwinreg.WinRegistryKey): application ident... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApplicationIdentifiersCollector:
"""Windows application identifiers collector."""
def _CollectApplicationIdentifiers(self, application_identifiers_key):
"""Collects Windows application identifiers (AppID). Args: application_identifiers_key (dfwinreg.WinRegistryKey): application identifiers Window... | the_stack_v2_python_sparse | winregrc/application_identifiers.py | libyal/winreg-kb | train | 129 |
a3caa7498eda007356814f580720f7a3ae027914 | [
"choices_plist, error = subprocess.Popen(['/usr/sbin/installer', '-showChoicesXML', '-pkg', choices_pkg_path], stdout=subprocess.PIPE).communicate()\nif choices_plist:\n try:\n choices_list = plistlib.loads(choices_plist)\n except Exception as err:\n raise ProcessorError(f\"Unexpected error pars... | <|body_start_0|>
choices_plist, error = subprocess.Popen(['/usr/sbin/installer', '-showChoicesXML', '-pkg', choices_pkg_path], stdout=subprocess.PIPE).communicate()
if choices_plist:
try:
choices_list = plistlib.loads(choices_plist)
except Exception as err:
... | Generates a choices.xml file for use with an installer. A postinstall script is required to run the installer with the choices.xml | ChoicesXMLGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChoicesXMLGenerator:
"""Generates a choices.xml file for use with an installer. A postinstall script is required to run the installer with the choices.xml"""
def output_showchoicesxml(self, choices_pkg_path):
"""Invoke the installer showChoicesXML command and return the contents"""
... | stack_v2_sparse_classes_75kplus_train_008916 | 4,729 | permissive | [
{
"docstring": "Invoke the installer showChoicesXML command and return the contents",
"name": "output_showchoicesxml",
"signature": "def output_showchoicesxml(self, choices_pkg_path)"
},
{
"docstring": "Generates the python dictionary of choices. Desired choices are given the choice attribute '1... | 4 | stack_v2_sparse_classes_30k_train_048101 | Implement the Python class `ChoicesXMLGenerator` described below.
Class description:
Generates a choices.xml file for use with an installer. A postinstall script is required to run the installer with the choices.xml
Method signatures and docstrings:
- def output_showchoicesxml(self, choices_pkg_path): Invoke the inst... | Implement the Python class `ChoicesXMLGenerator` described below.
Class description:
Generates a choices.xml file for use with an installer. A postinstall script is required to run the installer with the choices.xml
Method signatures and docstrings:
- def output_showchoicesxml(self, choices_pkg_path): Invoke the inst... | 7c0a2eaf223822480ccd80a7ea3d163cc9b5b507 | <|skeleton|>
class ChoicesXMLGenerator:
"""Generates a choices.xml file for use with an installer. A postinstall script is required to run the installer with the choices.xml"""
def output_showchoicesxml(self, choices_pkg_path):
"""Invoke the installer showChoicesXML command and return the contents"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChoicesXMLGenerator:
"""Generates a choices.xml file for use with an installer. A postinstall script is required to run the installer with the choices.xml"""
def output_showchoicesxml(self, choices_pkg_path):
"""Invoke the installer showChoicesXML command and return the contents"""
choice... | the_stack_v2_python_sparse | CommonProcessors/ChoicesXMLGenerator.py | autopkg/grahampugh-recipes | train | 66 |
b70e73edb101e6303b655e31f58aa1ebc22cac70 | [
"super(Decoder, self).__init__(parameters)\nself.num_layers = num_layers\nself.layer_list = add_conv_block(self.Conv, self.BatchNorm, in_channels=anatomy_factors, out_channels=self.base_filters)\nfor _ in range(self.num_layers - 2):\n self.layer_list += add_conv_block(self.Conv, self.BatchNorm, in_channels=self.... | <|body_start_0|>
super(Decoder, self).__init__(parameters)
self.num_layers = num_layers
self.layer_list = add_conv_block(self.Conv, self.BatchNorm, in_channels=anatomy_factors, out_channels=self.base_filters)
for _ in range(self.num_layers - 2):
self.layer_list += add_conv_bl... | Decoder | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
def __init__(self, parameters, anatomy_factors, num_layers=5):
"""Decoder module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The number of anatomical factors to be considered. num_layers (int, optional): The number of laye... | stack_v2_sparse_classes_75kplus_train_008917 | 14,834 | permissive | [
{
"docstring": "Decoder module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The number of anatomical factors to be considered. num_layers (int, optional): The number of layers in the Decoder. Defaults to 5. Attributes: num_layers (int): The number of layer... | 6 | stack_v2_sparse_classes_30k_train_015347 | Implement the Python class `Decoder` described below.
Class description:
Implement the Decoder class.
Method signatures and docstrings:
- def __init__(self, parameters, anatomy_factors, num_layers=5): Decoder module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): T... | Implement the Python class `Decoder` described below.
Class description:
Implement the Decoder class.
Method signatures and docstrings:
- def __init__(self, parameters, anatomy_factors, num_layers=5): Decoder module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): T... | 72eb99f68205afd5f8d49a3bb6cfc08cfd467582 | <|skeleton|>
class Decoder:
def __init__(self, parameters, anatomy_factors, num_layers=5):
"""Decoder module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The number of anatomical factors to be considered. num_layers (int, optional): The number of laye... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decoder:
def __init__(self, parameters, anatomy_factors, num_layers=5):
"""Decoder module for SDNet. Args: parameters (dict): A dictionary containing model parameters. anatomy_factors (int): The number of anatomical factors to be considered. num_layers (int, optional): The number of layers in the Deco... | the_stack_v2_python_sparse | GANDLF/models/sdnet.py | mlcommons/GaNDLF | train | 45 | |
3771b62900dcf339cc07a3dfed1619b1f196a343 | [
"typ = type(x)\nif typ in [int, float, bool]:\n return typ\nif x == AbstractInt():\n return Type.Integer\nif x == AbstractFloat():\n return Type.Float\nif x == AbstractBool():\n return Type.Bool\nif isinstance(x, tuple):\n return tuple((Value.typeof(y) for y in x))\nif isinstance(x, AbstractTensor):\... | <|body_start_0|>
typ = type(x)
if typ in [int, float, bool]:
return typ
if x == AbstractInt():
return Type.Integer
if x == AbstractFloat():
return Type.Float
if x == AbstractBool():
return Type.Bool
if isinstance(x, tuple):
... | Value | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Value:
def typeof(x):
"""Returns the type of a value (in the abstract interpreter world). Used for dispatching function calls."""
<|body_0|>
def of_type(typ: Type):
"""Creates an abstract value of the given Type type. Uses assumed_vector_size for the shape of tensors... | stack_v2_sparse_classes_75kplus_train_008918 | 26,457 | permissive | [
{
"docstring": "Returns the type of a value (in the abstract interpreter world). Used for dispatching function calls.",
"name": "typeof",
"signature": "def typeof(x)"
},
{
"docstring": "Creates an abstract value of the given Type type. Uses assumed_vector_size for the shape of tensors.",
"na... | 3 | stack_v2_sparse_classes_30k_train_011271 | Implement the Python class `Value` described below.
Class description:
Implement the Value class.
Method signatures and docstrings:
- def typeof(x): Returns the type of a value (in the abstract interpreter world). Used for dispatching function calls.
- def of_type(typ: Type): Creates an abstract value of the given Ty... | Implement the Python class `Value` described below.
Class description:
Implement the Value class.
Method signatures and docstrings:
- def typeof(x): Returns the type of a value (in the abstract interpreter world). Used for dispatching function calls.
- def of_type(typ: Type): Creates an abstract value of the given Ty... | 8fa75e67c0db8f632b135379740051cd10ff31f2 | <|skeleton|>
class Value:
def typeof(x):
"""Returns the type of a value (in the abstract interpreter world). Used for dispatching function calls."""
<|body_0|>
def of_type(typ: Type):
"""Creates an abstract value of the given Type type. Uses assumed_vector_size for the shape of tensors... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Value:
def typeof(x):
"""Returns the type of a value (in the abstract interpreter world). Used for dispatching function calls."""
typ = type(x)
if typ in [int, float, bool]:
return typ
if x == AbstractInt():
return Type.Integer
if x == AbstractFl... | the_stack_v2_python_sparse | rlo/src/rlo/absint.py | tomjaguarpaw/knossos-ksc | train | 0 | |
3d69c6c6bb2cee1b2f5747930915f014e45d791e | [
"self.snake = deque([(0, 0)])\nself.snake_grid = {(0, 0): 1}\nself.height = height\nself.width = width\nself.food_index = 0\nself.food = food\nself.movement = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}",
"new_head = (self.snake[0] + self.movement[direction][0], self.snake[1] + self.movement[direction]... | <|body_start_0|>
self.snake = deque([(0, 0)])
self.snake_grid = {(0, 0): 1}
self.height = height
self.width = width
self.food_index = 0
self.food = food
self.movement = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}
<|end_body_0|>
<|body_start_1|>
... | W - Width, H - Height, N - no. of food items Time Complexity: - move method : O(1) - calculate bite itself: O(1) using dictionary - add and remove element from queue: O(1) Space Complexity: - O(W * H + N) - O(N) - food data structure - O(W * H) used by snake and snake grid. | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
"""W - Width, H - Height, N - no. of food items Time Complexity: - move method : O(1) - calculate bite itself: O(1) using dictionary - add and remove element from queue: O(1) Space Complexity: - O(W * H + N) - O(N) - food data structure - O(W * H) used by snake and snake grid."""
... | stack_v2_sparse_classes_75kplus_train_008919 | 2,715 | no_license | [
{
"docstring": "Initialize data structure here. :param width: - screen width. :param height: - screen height. :param food: - a list of food position. eg: food = [[1,1], [1,0]]",
"name": "__init__",
"signature": "def __init__(self, width: int, height: int, food: List[List[int]])"
},
{
"docstring"... | 2 | null | Implement the Python class `SnakeGame` described below.
Class description:
W - Width, H - Height, N - no. of food items Time Complexity: - move method : O(1) - calculate bite itself: O(1) using dictionary - add and remove element from queue: O(1) Space Complexity: - O(W * H + N) - O(N) - food data structure - O(W * H)... | Implement the Python class `SnakeGame` described below.
Class description:
W - Width, H - Height, N - no. of food items Time Complexity: - move method : O(1) - calculate bite itself: O(1) using dictionary - add and remove element from queue: O(1) Space Complexity: - O(W * H + N) - O(N) - food data structure - O(W * H)... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class SnakeGame:
"""W - Width, H - Height, N - no. of food items Time Complexity: - move method : O(1) - calculate bite itself: O(1) using dictionary - add and remove element from queue: O(1) Space Complexity: - O(W * H + N) - O(N) - food data structure - O(W * H) used by snake and snake grid."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeGame:
"""W - Width, H - Height, N - no. of food items Time Complexity: - move method : O(1) - calculate bite itself: O(1) using dictionary - add and remove element from queue: O(1) Space Complexity: - O(W * H + N) - O(N) - food data structure - O(W * H) used by snake and snake grid."""
def __init__(... | the_stack_v2_python_sparse | amazon/design/snake_game.py | Shiv2157k/leet_code | train | 1 |
02d546bb91ec79af39b01f4574e1316e7a71d790 | [
"super(MobileAttckMalware, self).__init__(**kwargs)\nself.mobile_attck_obj = mobile_attck_obj\nself.old_attack_id = self._set_attribute(kwargs, 'x_mitre_old_attack_id')\nself.platforms = self._set_list_items(kwargs, 'x_mitre_platforms')\nself.aliases = self._set_list_items(kwargs, 'x_mitre_aliases')\nself.version =... | <|body_start_0|>
super(MobileAttckMalware, self).__init__(**kwargs)
self.mobile_attck_obj = mobile_attck_obj
self.old_attack_id = self._set_attribute(kwargs, 'x_mitre_old_attack_id')
self.platforms = self._set_list_items(kwargs, 'x_mitre_platforms')
self.aliases = self._set_list_... | A child class of MobileAttckObject Creates objects which have been categorized as malware used in attacks Example: You can iterate over a `malwares` list and access specific properties and relationship properties. The following relationship properties are accessible: 1. actors 2. techniques 1. To iterate over an `malwa... | MobileAttckMalware | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MobileAttckMalware:
"""A child class of MobileAttckObject Creates objects which have been categorized as malware used in attacks Example: You can iterate over a `malwares` list and access specific properties and relationship properties. The following relationship properties are accessible: 1. act... | stack_v2_sparse_classes_75kplus_train_008920 | 4,277 | permissive | [
{
"docstring": "Creates an MobileAttckMalware object. The MobileAttckMalware object is based on malware which have been categorized as software used in attacks Arguments: mobile_attck_obj (json) -- Takes the raw MITRE Mobile ATT&CK Json object AttckObject (dict) -- Takes the MITRE Mobile ATT&CK Json object as a... | 3 | stack_v2_sparse_classes_30k_train_006285 | Implement the Python class `MobileAttckMalware` described below.
Class description:
A child class of MobileAttckObject Creates objects which have been categorized as malware used in attacks Example: You can iterate over a `malwares` list and access specific properties and relationship properties. The following relatio... | Implement the Python class `MobileAttckMalware` described below.
Class description:
A child class of MobileAttckObject Creates objects which have been categorized as malware used in attacks Example: You can iterate over a `malwares` list and access specific properties and relationship properties. The following relatio... | de5b80c653384ce0f1fb7b8ba077bb8890fa72fa | <|skeleton|>
class MobileAttckMalware:
"""A child class of MobileAttckObject Creates objects which have been categorized as malware used in attacks Example: You can iterate over a `malwares` list and access specific properties and relationship properties. The following relationship properties are accessible: 1. act... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MobileAttckMalware:
"""A child class of MobileAttckObject Creates objects which have been categorized as malware used in attacks Example: You can iterate over a `malwares` list and access specific properties and relationship properties. The following relationship properties are accessible: 1. actors 2. techni... | the_stack_v2_python_sparse | pyattck/mobile/malware.py | Neo23x0/pyattck | train | 7 |
f8f1f5b53b5da617646d4f62eea453425e0d9f6c | [
"for key in data.keys():\n if key == k:\n data[key] = v\n elif type(data[key]) is dict:\n Json._replace_value(data[key], k, v)",
"assert File.exists(file_path), 'Failed to find file: ' + file_path\nwith open(file_path) as json_file:\n data = json.load(json_file)\nreturn data",
"with open(... | <|body_start_0|>
for key in data.keys():
if key == k:
data[key] = v
elif type(data[key]) is dict:
Json._replace_value(data[key], k, v)
<|end_body_0|>
<|body_start_1|>
assert File.exists(file_path), 'Failed to find file: ' + file_path
with ... | Json | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Json:
def _replace_value(data, k, v):
"""Replace value of key inside json object. :param data: json object. :param k: key. :param v: value."""
<|body_0|>
def read(file_path):
"""Read content of json file. :param file_path: Path to file. :return: Content of file as js... | stack_v2_sparse_classes_75kplus_train_008921 | 1,357 | no_license | [
{
"docstring": "Replace value of key inside json object. :param data: json object. :param k: key. :param v: value.",
"name": "_replace_value",
"signature": "def _replace_value(data, k, v)"
},
{
"docstring": "Read content of json file. :param file_path: Path to file. :return: Content of file as j... | 3 | stack_v2_sparse_classes_30k_train_003484 | Implement the Python class `Json` described below.
Class description:
Implement the Json class.
Method signatures and docstrings:
- def _replace_value(data, k, v): Replace value of key inside json object. :param data: json object. :param k: key. :param v: value.
- def read(file_path): Read content of json file. :para... | Implement the Python class `Json` described below.
Class description:
Implement the Json class.
Method signatures and docstrings:
- def _replace_value(data, k, v): Replace value of key inside json object. :param data: json object. :param k: key. :param v: value.
- def read(file_path): Read content of json file. :para... | b173dc78de9f45a383bf74c2175f24e7fbae02c9 | <|skeleton|>
class Json:
def _replace_value(data, k, v):
"""Replace value of key inside json object. :param data: json object. :param k: key. :param v: value."""
<|body_0|>
def read(file_path):
"""Read content of json file. :param file_path: Path to file. :return: Content of file as js... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Json:
def _replace_value(data, k, v):
"""Replace value of key inside json object. :param data: json object. :param k: key. :param v: value."""
for key in data.keys():
if key == k:
data[key] = v
elif type(data[key]) is dict:
Json._replace_... | the_stack_v2_python_sparse | core/json/json_utils.py | niravgohil/nativescript-cli-tests | train | 0 | |
5b70b3de40be63713dbc4de1ffa2abaac9c729c4 | [
"user = Account.find_account_by_user(request.user)\nturn_to_date = lambda x: x and datetime.strptime(x, '%Y%m%d') or date.today()\nstart_date = turn_to_date(request.GET.get('start', None))\nend_date = turn_to_date(request.GET.get('end', None))\nplans = []\ncalendars = Calendar.objects.select_related('plan').select_... | <|body_start_0|>
user = Account.find_account_by_user(request.user)
turn_to_date = lambda x: x and datetime.strptime(x, '%Y%m%d') or date.today()
start_date = turn_to_date(request.GET.get('start', None))
end_date = turn_to_date(request.GET.get('end', None))
plans = []
cale... | CalendarList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalendarList:
def get(self, request, format=None):
"""get my calendar"""
<|body_0|>
def post(self, request, format=None):
"""join plan same date & user will use the last one { "plan": 2, "joined_date": "2015-01-01" }"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_008922 | 10,839 | no_license | [
{
"docstring": "get my calendar",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "join plan same date & user will use the last one { \"plan\": 2, \"joined_date\": \"2015-01-01\" }",
"name": "post",
"signature": "def post(self, request, format=None)"
... | 2 | null | Implement the Python class `CalendarList` described below.
Class description:
Implement the CalendarList class.
Method signatures and docstrings:
- def get(self, request, format=None): get my calendar
- def post(self, request, format=None): join plan same date & user will use the last one { "plan": 2, "joined_date": ... | Implement the Python class `CalendarList` described below.
Class description:
Implement the CalendarList class.
Method signatures and docstrings:
- def get(self, request, format=None): get my calendar
- def post(self, request, format=None): join plan same date & user will use the last one { "plan": 2, "joined_date": ... | 4a74585dd1b607c4c1f730c1e41583c482d7f150 | <|skeleton|>
class CalendarList:
def get(self, request, format=None):
"""get my calendar"""
<|body_0|>
def post(self, request, format=None):
"""join plan same date & user will use the last one { "plan": 2, "joined_date": "2015-01-01" }"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CalendarList:
def get(self, request, format=None):
"""get my calendar"""
user = Account.find_account_by_user(request.user)
turn_to_date = lambda x: x and datetime.strptime(x, '%Y%m%d') or date.today()
start_date = turn_to_date(request.GET.get('start', None))
end_date = ... | the_stack_v2_python_sparse | fitrecipe/plan/views.py | tiant167/fitRecipe | train | 0 | |
ee1a330afe826f6cd60332bd5b8e37a3da6f3f54 | [
"if len(matrix) == 0 or len(matrix[0]) == 0:\n return 0\nmaxSide = 0\nrows, columns = (len(matrix), len(matrix[0]))\nfor i in range(rows):\n for j in range(columns):\n if matrix[i][j] == '1':\n maxSide = max(maxSide, 1)\n currentMaxsize = min(rows - i, columns - j)\n fo... | <|body_start_0|>
if len(matrix) == 0 or len(matrix[0]) == 0:
return 0
maxSide = 0
rows, columns = (len(matrix), len(matrix[0]))
for i in range(rows):
for j in range(columns):
if matrix[i][j] == '1':
maxSide = max(maxSide, 1)
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(matrix) == 0 o... | stack_v2_sparse_classes_75kplus_train_008923 | 2,127 | permissive | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquare",
"signature": "def maximalSquare(self, matrix)"
},
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquare",
"signature": "def maximalSquare(self, matrix)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017289 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int
- def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int
- def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int
<|skeleton|>
class Soluti... | d2b8a1dfe986d71d02d2568b55bad6e5b1c81492 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
if len(matrix) == 0 or len(matrix[0]) == 0:
return 0
maxSide = 0
rows, columns = (len(matrix), len(matrix[0]))
for i in range(rows):
for j in range(columns... | the_stack_v2_python_sparse | Middle/Que221最大正方形.py | HuangZengPei/LeetCode | train | 2 | |
7db4cd8e46545ac5906e9f2b318893c98c9bf7b8 | [
"res = []\nfor i in range(len(nums) + 1):\n res.extend([list(x) for x in itertools.combinations(nums, i)])\nreturn res",
"res = [[]]\nfor i in nums:\n res += [x + [i] for x in res]\nreturn res",
"def backtrack(first=0, cur=[]):\n if len(cur) == k:\n output.append(cur[:])\n return\n for... | <|body_start_0|>
res = []
for i in range(len(nums) + 1):
res.extend([list(x) for x in itertools.combinations(nums, i)])
return res
<|end_body_0|>
<|body_start_1|>
res = [[]]
for i in nums:
res += [x + [i] for x in res]
return res
<|end_body_1|>
<... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
"""Purpose: Given an int array of unique items, returns all possible subsets. Note: This is equivalent to the power set."""
<|body_0|>
def subsets2(self, nums: List[int]) -> List[List[int]]:
"""Cascadin... | stack_v2_sparse_classes_75kplus_train_008924 | 1,242 | no_license | [
{
"docstring": "Purpose: Given an int array of unique items, returns all possible subsets. Note: This is equivalent to the power set.",
"name": "subsets",
"signature": "def subsets(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "Cascading solution: Starting from an empty subset in ... | 3 | stack_v2_sparse_classes_30k_train_041501 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets(self, nums: List[int]) -> List[List[int]]: Purpose: Given an int array of unique items, returns all possible subsets. Note: This is equivalent to the power set.
- def... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets(self, nums: List[int]) -> List[List[int]]: Purpose: Given an int array of unique items, returns all possible subsets. Note: This is equivalent to the power set.
- def... | 95a86cbbca28d0c0f6d72d28a2f1cb5a86327934 | <|skeleton|>
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
"""Purpose: Given an int array of unique items, returns all possible subsets. Note: This is equivalent to the power set."""
<|body_0|>
def subsets2(self, nums: List[int]) -> List[List[int]]:
"""Cascadin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
"""Purpose: Given an int array of unique items, returns all possible subsets. Note: This is equivalent to the power set."""
res = []
for i in range(len(nums) + 1):
res.extend([list(x) for x in itertools.combin... | the_stack_v2_python_sparse | subsets.py | tashakim/puzzles_python | train | 8 | |
1bb8ac199deb2b7481de02ae587ffb3f4e198025 | [
"try:\n super().__init__()\n Assertor.assert_data_types([number], [str])\n self.number = number\n LOGGER.success(\"created '{}', with id: [{}]\".format(self.__class__.__name__, self.id_str))\nexcept Exception as phone_exception:\n LOGGER.exception(phone_exception)\n raise phone_exception",
"try:... | <|body_start_0|>
try:
super().__init__()
Assertor.assert_data_types([number], [str])
self.number = number
LOGGER.success("created '{}', with id: [{}]".format(self.__class__.__name__, self.id_str))
except Exception as phone_exception:
LOGGER.exc... | logic to validate a phone number | Phone | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Phone:
"""logic to validate a phone number"""
def __init__(self, number: str):
"""Constructor / Instantiate the class Parameters ---------- number : str phone number to be validated"""
<|body_0|>
def format_number(self):
"""formatting of phone number according to... | stack_v2_sparse_classes_75kplus_train_008925 | 2,474 | permissive | [
{
"docstring": "Constructor / Instantiate the class Parameters ---------- number : str phone number to be validated",
"name": "__init__",
"signature": "def __init__(self, number: str)"
},
{
"docstring": "formatting of phone number according to norwegian standard Returns ------- out : str formatt... | 3 | stack_v2_sparse_classes_30k_train_045839 | Implement the Python class `Phone` described below.
Class description:
logic to validate a phone number
Method signatures and docstrings:
- def __init__(self, number: str): Constructor / Instantiate the class Parameters ---------- number : str phone number to be validated
- def format_number(self): formatting of phon... | Implement the Python class `Phone` described below.
Class description:
logic to validate a phone number
Method signatures and docstrings:
- def __init__(self, number: str): Constructor / Instantiate the class Parameters ---------- number : str phone number to be validated
- def format_number(self): formatting of phon... | 8923c0f69463fc2c2ebc9cfd3dc558e2f2cf3ab2 | <|skeleton|>
class Phone:
"""logic to validate a phone number"""
def __init__(self, number: str):
"""Constructor / Instantiate the class Parameters ---------- number : str phone number to be validated"""
<|body_0|>
def format_number(self):
"""formatting of phone number according to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Phone:
"""logic to validate a phone number"""
def __init__(self, number: str):
"""Constructor / Instantiate the class Parameters ---------- number : str phone number to be validated"""
try:
super().__init__()
Assertor.assert_data_types([number], [str])
... | the_stack_v2_python_sparse | source/domain/phone.py | yanzj/stressa | train | 0 |
cb95696a435f5bbd8193a085e84124929fe8861a | [
"self._object_id = object_id\nself._object_sensor = object_sensor\nself._grid_map = grid_map\nself._robot_id = robot_id\ntransition_model = AdversarialTransitionModel(object_id, robot_id, grid_map, motion_policy)\nobservation_model = AdversarialObservationModel(object_id, robot_id)\nreward_model = AdversarialReward... | <|body_start_0|>
self._object_id = object_id
self._object_sensor = object_sensor
self._grid_map = grid_map
self._robot_id = robot_id
transition_model = AdversarialTransitionModel(object_id, robot_id, grid_map, motion_policy)
observation_model = AdversarialObservationModel... | AdversarialTarget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdversarialTarget:
def __init__(self, object_id, init_object_state, object_sensor, motion_policy, grid_map, robot_id, robot_sensor, **kwargs):
"""kwargs include: sigma, epsilon (observation model parameters) belief_rep="histogram" (belief representation) prior={}, # does the target know ... | stack_v2_sparse_classes_75kplus_train_008926 | 13,574 | no_license | [
{
"docstring": "kwargs include: sigma, epsilon (observation model parameters) belief_rep=\"histogram\" (belief representation) prior={}, # does the target know where the robot is? grid_map, big=100, small=1, action_prior=None",
"name": "__init__",
"signature": "def __init__(self, object_id, init_object_... | 2 | stack_v2_sparse_classes_30k_train_036343 | Implement the Python class `AdversarialTarget` described below.
Class description:
Implement the AdversarialTarget class.
Method signatures and docstrings:
- def __init__(self, object_id, init_object_state, object_sensor, motion_policy, grid_map, robot_id, robot_sensor, **kwargs): kwargs include: sigma, epsilon (obse... | Implement the Python class `AdversarialTarget` described below.
Class description:
Implement the AdversarialTarget class.
Method signatures and docstrings:
- def __init__(self, object_id, init_object_state, object_sensor, motion_policy, grid_map, robot_id, robot_sensor, **kwargs): kwargs include: sigma, epsilon (obse... | 0baf8e9e3410b19ea0bc7b87dc638328eae2d5d2 | <|skeleton|>
class AdversarialTarget:
def __init__(self, object_id, init_object_state, object_sensor, motion_policy, grid_map, robot_id, robot_sensor, **kwargs):
"""kwargs include: sigma, epsilon (observation model parameters) belief_rep="histogram" (belief representation) prior={}, # does the target know ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdversarialTarget:
def __init__(self, object_id, init_object_state, object_sensor, motion_policy, grid_map, robot_id, robot_sensor, **kwargs):
"""kwargs include: sigma, epsilon (observation model parameters) belief_rep="histogram" (belief representation) prior={}, # does the target know where the robo... | the_stack_v2_python_sparse | adversarial_mos/adversary/agent.py | zkytony/dynamic-object-search | train | 0 | |
7610424e221559b22fed52aaaee6fb8c679f4f3e | [
"self._model = model\nself._model.build_graph()\nself._batch_reader = batch_reader\nself._hps = hps\nself._vocab = vocab\nself._saver = tf.train.Saver()\nself._decode_io = DecodeIO(FLAGS.decode_dir)",
"sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\nstep = 0\nwhile step < FLAGS.max_decode_ste... | <|body_start_0|>
self._model = model
self._model.build_graph()
self._batch_reader = batch_reader
self._hps = hps
self._vocab = vocab
self._saver = tf.train.Saver()
self._decode_io = DecodeIO(FLAGS.decode_dir)
<|end_body_0|>
<|body_start_1|>
sess = tf.Sess... | Beam search decoder. | BSDecoder | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSDecoder:
"""Beam search decoder."""
def __init__(self, model, batch_reader, hps, vocab):
"""Beam search decoding. Args: model: The seq2seq attentional model. batch_reader: The batch data reader. hps: Hyperparamters. vocab: Vocabulary"""
<|body_0|>
def DecodeLoop(self):... | stack_v2_sparse_classes_75kplus_train_008927 | 5,579 | permissive | [
{
"docstring": "Beam search decoding. Args: model: The seq2seq attentional model. batch_reader: The batch data reader. hps: Hyperparamters. vocab: Vocabulary",
"name": "__init__",
"signature": "def __init__(self, model, batch_reader, hps, vocab)"
},
{
"docstring": "Decoding loop for long running... | 4 | stack_v2_sparse_classes_30k_train_025735 | Implement the Python class `BSDecoder` described below.
Class description:
Beam search decoder.
Method signatures and docstrings:
- def __init__(self, model, batch_reader, hps, vocab): Beam search decoding. Args: model: The seq2seq attentional model. batch_reader: The batch data reader. hps: Hyperparamters. vocab: Vo... | Implement the Python class `BSDecoder` described below.
Class description:
Beam search decoder.
Method signatures and docstrings:
- def __init__(self, model, batch_reader, hps, vocab): Beam search decoding. Args: model: The seq2seq attentional model. batch_reader: The batch data reader. hps: Hyperparamters. vocab: Vo... | 92ec5ec3efeee852aec5c057798298cd3a8e58ae | <|skeleton|>
class BSDecoder:
"""Beam search decoder."""
def __init__(self, model, batch_reader, hps, vocab):
"""Beam search decoding. Args: model: The seq2seq attentional model. batch_reader: The batch data reader. hps: Hyperparamters. vocab: Vocabulary"""
<|body_0|>
def DecodeLoop(self):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BSDecoder:
"""Beam search decoder."""
def __init__(self, model, batch_reader, hps, vocab):
"""Beam search decoding. Args: model: The seq2seq attentional model. batch_reader: The batch data reader. hps: Hyperparamters. vocab: Vocabulary"""
self._model = model
self._model.build_grap... | the_stack_v2_python_sparse | model_zoo/models/textsum/seq2seq_attention_decode.py | coderSkyChen/Action_Recognition_Zoo | train | 246 |
d3efd2f8f3d27bbd4b365d9cebbf902a3482248c | [
"super(InstanceGroupNetworkMigration, self).__init__()\nself.instance_group = self.build_instance_group()\nself.instance_group_migration_handler = self.build_instance_group_handler()",
"instance_group_helper = InstanceGroupHelper(self.compute, self.project, self.instance_group_name, self.region, self.zone, self.n... | <|body_start_0|>
super(InstanceGroupNetworkMigration, self).__init__()
self.instance_group = self.build_instance_group()
self.instance_group_migration_handler = self.build_instance_group_handler()
<|end_body_0|>
<|body_start_1|>
instance_group_helper = InstanceGroupHelper(self.compute, ... | InstanceGroupNetworkMigration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceGroupNetworkMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target n... | stack_v2_sparse_classes_75kplus_train_008928 | 5,430 | permissive | [
{
"docstring": "Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target network subnetwork_name: target subnetwork preserve_external_ip: whether to preserve instances' external IPs zone: zone of a zonal instance group region: region of regio... | 5 | stack_v2_sparse_classes_30k_train_014294 | Implement the Python class `InstanceGroupNetworkMigration` described below.
Class description:
Implement the InstanceGroupNetworkMigration class.
Method signatures and docstrings:
- def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name): Initialize... | Implement the Python class `InstanceGroupNetworkMigration` described below.
Class description:
Implement the InstanceGroupNetworkMigration class.
Method signatures and docstrings:
- def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name): Initialize... | 1132e44d696ab9da4d1079ebc3d32ed4382cdc28 | <|skeleton|>
class InstanceGroupNetworkMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstanceGroupNetworkMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target network subnetw... | the_stack_v2_python_sparse | vm_network_migration/handlers/instance_group_migration/instance_group_network_migration.py | googleinterns/vm-network-migration | train | 1 | |
5d40f7ee9a5e3b08a51ced198d26641f830966da | [
"threading.Thread.__init__(self)\nself._channel_modeler = channel_modeler\nself._the_device = device\nself._the_channel = the_channel\nself._dist_callback = dist_callback\nself._active = False\nself._status = random.randrange(1, 3)",
"if not self._active:\n raise AttributeError\nif self._status:\n self._the... | <|body_start_0|>
threading.Thread.__init__(self)
self._channel_modeler = channel_modeler
self._the_device = device
self._the_channel = the_channel
self._dist_callback = dist_callback
self._active = False
self._status = random.randrange(1, 3)
<|end_body_0|>
<|body... | Thread representing a channel whose status changes in time. Each channel thread must be associated to a Channel object. When the center_freq method on the ChannelModeler is called, the corresponding ChannelThread is activated. The ChannelThread controls an AbstractDevice object, by changing is central frequency followi... | ChannelThread | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelThread:
"""Thread representing a channel whose status changes in time. Each channel thread must be associated to a Channel object. When the center_freq method on the ChannelModeler is called, the corresponding ChannelThread is activated. The ChannelThread controls an AbstractDevice object,... | stack_v2_sparse_classes_75kplus_train_008929 | 6,582 | permissive | [
{
"docstring": "CTOR. @param channel_modeler ChannelModeler instance. @param device AbstractDevice object instance. @param the_channel Channel object instance. @param dist_callback Distribution callback.",
"name": "__init__",
"signature": "def __init__(self, channel_modeler, device, the_channel, dist_ca... | 4 | stack_v2_sparse_classes_30k_train_012450 | Implement the Python class `ChannelThread` described below.
Class description:
Thread representing a channel whose status changes in time. Each channel thread must be associated to a Channel object. When the center_freq method on the ChannelModeler is called, the corresponding ChannelThread is activated. The ChannelTh... | Implement the Python class `ChannelThread` described below.
Class description:
Thread representing a channel whose status changes in time. Each channel thread must be associated to a Channel object. When the center_freq method on the ChannelModeler is called, the corresponding ChannelThread is activated. The ChannelTh... | aafc0e93a81da86f414743b6b19ff4739045763a | <|skeleton|>
class ChannelThread:
"""Thread representing a channel whose status changes in time. Each channel thread must be associated to a Channel object. When the center_freq method on the ChannelModeler is called, the corresponding ChannelThread is activated. The ChannelThread controls an AbstractDevice object,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChannelThread:
"""Thread representing a channel whose status changes in time. Each channel thread must be associated to a Channel object. When the center_freq method on the ChannelModeler is called, the corresponding ChannelThread is activated. The ChannelThread controls an AbstractDevice object, by changing ... | the_stack_v2_python_sparse | python/utils/channel.py | ComputerNetworks-UFRGS/OpERA | train | 3 |
e50d4668751b33b8d5505a300d5236347070edc0 | [
"if classname in ['ElementDeclaration', 'TypeDefinition', 'LocalElementDeclaration']:\n return type.__new__(cls, classname, bases, classdict)\nif ElementDeclaration in bases:\n if not 'schema' in classdict or not 'literal' in classdict:\n raise AttributeError('ElementDeclaration must define schema and ... | <|body_start_0|>
if classname in ['ElementDeclaration', 'TypeDefinition', 'LocalElementDeclaration']:
return type.__new__(cls, classname, bases, classdict)
if ElementDeclaration in bases:
if not 'schema' in classdict or not 'literal' in classdict:
raise AttributeE... | Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing global type definitions. elements -- dict of typecode classes representing global el... | SchemaInstanceType | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaInstanceType:
"""Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing global type definitions. elements -- d... | stack_v2_sparse_classes_75kplus_train_008930 | 14,557 | permissive | [
{
"docstring": "If classdict has literal and schema register it as a element declaration, else if has type and schema register it as a type definition.",
"name": "__new__",
"signature": "def __new__(cls, classname, bases, classdict)"
},
{
"docstring": "Grab a type definition, returns a typecode ... | 3 | stack_v2_sparse_classes_30k_train_033912 | Implement the Python class `SchemaInstanceType` described below.
Class description:
Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing... | Implement the Python class `SchemaInstanceType` described below.
Class description:
Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing... | 9b890e6a25471037b7485e4999b480de7c86b656 | <|skeleton|>
class SchemaInstanceType:
"""Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing global type definitions. elements -- d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SchemaInstanceType:
"""Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing global type definitions. elements -- dict of typeco... | the_stack_v2_python_sparse | Libraries/DUTs/Community/di_vsphere/pysphere/pysphere/ZSI/schema.py | Spirent/iTest-assets | train | 10 |
9ff0a9d5e878badb56dca68b7b31d21c9f5f5a5e | [
"if collection is None or self.schema is None:\n return\ntry:\n for item in collection:\n self._schema.filter(model=item, context=context if self.use_context else None)\nexcept TypeError:\n pass",
"if self._schema is None or not collection:\n return\nresult = []\ntry:\n for index, item in en... | <|body_start_0|>
if collection is None or self.schema is None:
return
try:
for item in collection:
self._schema.filter(model=item, context=context if self.use_context else None)
except TypeError:
pass
<|end_body_0|>
<|body_start_1|>
if... | Collection property Allows to validate nested collection of entities that exist on a property of another entity. Filters and validators will be applied to collection as whole, when schema will be applied to each item in the collection. | CollectionProperty | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectionProperty:
"""Collection property Allows to validate nested collection of entities that exist on a property of another entity. Filters and validators will be applied to collection as whole, when schema will be applied to each item in the collection."""
def filter_with_schema(self, c... | stack_v2_sparse_classes_75kplus_train_008931 | 5,839 | permissive | [
{
"docstring": "Perform collection items filtering with schema",
"name": "filter_with_schema",
"signature": "def filter_with_schema(self, collection=None, context=None)"
},
{
"docstring": "Validate each item in collection with our schema",
"name": "validate_with_schema",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_005105 | Implement the Python class `CollectionProperty` described below.
Class description:
Collection property Allows to validate nested collection of entities that exist on a property of another entity. Filters and validators will be applied to collection as whole, when schema will be applied to each item in the collection.... | Implement the Python class `CollectionProperty` described below.
Class description:
Collection property Allows to validate nested collection of entities that exist on a property of another entity. Filters and validators will be applied to collection as whole, when schema will be applied to each item in the collection.... | c598d1af5df40fae65cf3878b8f67accbcd059b7 | <|skeleton|>
class CollectionProperty:
"""Collection property Allows to validate nested collection of entities that exist on a property of another entity. Filters and validators will be applied to collection as whole, when schema will be applied to each item in the collection."""
def filter_with_schema(self, c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CollectionProperty:
"""Collection property Allows to validate nested collection of entities that exist on a property of another entity. Filters and validators will be applied to collection as whole, when schema will be applied to each item in the collection."""
def filter_with_schema(self, collection=Non... | the_stack_v2_python_sparse | shiftschema/property.py | projectshift/shift-schema | train | 2 |
b0d31ed8d6ac27fd242b7f214f63a7d458cf8711 | [
"self.render_size = render_size\nself.camera_pos = camera_pos\nself.camera_view_count = len(self.camera_pos)\nself.cameras = []\nfor pos in self.camera_pos:\n self.cameras.append(vapory.Camera('location', pos, 'look_at', [0.0, 0.0, 0.0]))\nself.light = vapory.LightSource([2.0, 3.0, -2.5], 'color', [1.0, 1.0, 1.0... | <|body_start_0|>
self.render_size = render_size
self.camera_pos = camera_pos
self.camera_view_count = len(self.camera_pos)
self.cameras = []
for pos in self.camera_pos:
self.cameras.append(vapory.Camera('location', pos, 'look_at', [0.0, 0.0, 0.0]))
self.light ... | Vision forward model for Shape class (hypothesis.py) Creates 3D scene according to given shape representation and uses POVRay via vapory to render 3D scene to 2D image Each part is assumed to be a rectangular prism. Forward model expects a Shape (from hypothesis.py) instance which contains the position and size of each... | VisionForwardModelPOVRay | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisionForwardModelPOVRay:
"""Vision forward model for Shape class (hypothesis.py) Creates 3D scene according to given shape representation and uses POVRay via vapory to render 3D scene to 2D image Each part is assumed to be a rectangular prism. Forward model expects a Shape (from hypothesis.py) i... | stack_v2_sparse_classes_75kplus_train_008932 | 3,804 | no_license | [
{
"docstring": "Initializes VTK objects for rendering.",
"name": "__init__",
"signature": "def __init__(self, render_size=DEFAULT_RENDER_SIZE, camera_pos=DEFAULT_CAMERA_POS)"
},
{
"docstring": "Construct the 3D object from Shape instance and render it. Returns numpy array with size number of vie... | 5 | null | Implement the Python class `VisionForwardModelPOVRay` described below.
Class description:
Vision forward model for Shape class (hypothesis.py) Creates 3D scene according to given shape representation and uses POVRay via vapory to render 3D scene to 2D image Each part is assumed to be a rectangular prism. Forward model... | Implement the Python class `VisionForwardModelPOVRay` described below.
Class description:
Vision forward model for Shape class (hypothesis.py) Creates 3D scene according to given shape representation and uses POVRay via vapory to render 3D scene to 2D image Each part is assumed to be a rectangular prism. Forward model... | 86569f6d05161d114918ec9dc0adec2c07e87108 | <|skeleton|>
class VisionForwardModelPOVRay:
"""Vision forward model for Shape class (hypothesis.py) Creates 3D scene according to given shape representation and uses POVRay via vapory to render 3D scene to 2D image Each part is assumed to be a rectangular prism. Forward model expects a Shape (from hypothesis.py) i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VisionForwardModelPOVRay:
"""Vision forward model for Shape class (hypothesis.py) Creates 3D scene according to given shape representation and uses POVRay via vapory to render 3D scene to 2D image Each part is assumed to be a rectangular prism. Forward model expects a Shape (from hypothesis.py) instance which... | the_stack_v2_python_sparse | vision_forward_model_povray.py | gokererdogan/Infer3DShape | train | 2 |
32eedb70e6de2cdf40a39859f8bead67d930c783 | [
"methods = ['get_session_key']\nfor method in methods:\n if not (hasattr(uhost, method) and callable(getattr(uhost, method))):\n raise CryptoWorkerEncryptUhostMethodException\nself.__uhost = uhost",
"try:\n crypto = CryptoLayer(self.__uhost.get_session_key(devid))\n logging.debug('Encrypting messa... | <|body_start_0|>
methods = ['get_session_key']
for method in methods:
if not (hasattr(uhost, method) and callable(getattr(uhost, method))):
raise CryptoWorkerEncryptUhostMethodException
self.__uhost = uhost
<|end_body_0|>
<|body_start_1|>
try:
cry... | Encryption worker | CryptoWorkerEncrypt | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CryptoWorkerEncrypt:
"""Encryption worker"""
def __init__(self, uhost):
"""Initialization"""
<|body_0|>
def process(self, devid, data, outbound_queue):
"""Run process"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
methods = ['get_session_key']
... | stack_v2_sparse_classes_75kplus_train_008933 | 1,435 | permissive | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, uhost)"
},
{
"docstring": "Run process",
"name": "process",
"signature": "def process(self, devid, data, outbound_queue)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016243 | Implement the Python class `CryptoWorkerEncrypt` described below.
Class description:
Encryption worker
Method signatures and docstrings:
- def __init__(self, uhost): Initialization
- def process(self, devid, data, outbound_queue): Run process | Implement the Python class `CryptoWorkerEncrypt` described below.
Class description:
Encryption worker
Method signatures and docstrings:
- def __init__(self, uhost): Initialization
- def process(self, devid, data, outbound_queue): Run process
<|skeleton|>
class CryptoWorkerEncrypt:
"""Encryption worker"""
d... | ff4577c321b1ac3439856c98e9ca6d8b88462d7e | <|skeleton|>
class CryptoWorkerEncrypt:
"""Encryption worker"""
def __init__(self, uhost):
"""Initialization"""
<|body_0|>
def process(self, devid, data, outbound_queue):
"""Run process"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CryptoWorkerEncrypt:
"""Encryption worker"""
def __init__(self, uhost):
"""Initialization"""
methods = ['get_session_key']
for method in methods:
if not (hasattr(uhost, method) and callable(getattr(uhost, method))):
raise CryptoWorkerEncryptUhostMethodE... | the_stack_v2_python_sparse | uhost/workers/crypto_worker_encrypt.py | connax-utim/uhost-python | train | 1 |
c5a50c46e8048434c3931d803d3a82f4a3008667 | [
"getargs = {'search': 'action.threat_outputlookup=1', 'output_mode': 'json', 'count': 0}\nunused_response, content = splunk.rest.simpleRequest('configs/conf-savedsearches', sessionKey=session_key, getargs=getargs)\njson_content = json.loads(content)['entry']\noutput_dict = {}\nfor search in json_content:\n searc... | <|body_start_0|>
getargs = {'search': 'action.threat_outputlookup=1', 'output_mode': 'json', 'count': 0}
unused_response, content = splunk.rest.simpleRequest('configs/conf-savedsearches', sessionKey=session_key, getargs=getargs)
json_content = json.loads(content)['entry']
output_dict = {... | IntelUtils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntelUtils:
def get_threatlist_generating_searches(self, session_key):
"""Return a complete list of threatlist generating searches as a dictionary of: {search_name: [kvstore_collection], ...}"""
<|body_0|>
def get_stanza_update_times(cls, conf, app, stanzas, param='modtime')... | stack_v2_sparse_classes_75kplus_train_008934 | 8,784 | no_license | [
{
"docstring": "Return a complete list of threatlist generating searches as a dictionary of: {search_name: [kvstore_collection], ...}",
"name": "get_threatlist_generating_searches",
"signature": "def get_threatlist_generating_searches(self, session_key)"
},
{
"docstring": "Get last update time o... | 3 | null | Implement the Python class `IntelUtils` described below.
Class description:
Implement the IntelUtils class.
Method signatures and docstrings:
- def get_threatlist_generating_searches(self, session_key): Return a complete list of threatlist generating searches as a dictionary of: {search_name: [kvstore_collection], ..... | Implement the Python class `IntelUtils` described below.
Class description:
Implement the IntelUtils class.
Method signatures and docstrings:
- def get_threatlist_generating_searches(self, session_key): Return a complete list of threatlist generating searches as a dictionary of: {search_name: [kvstore_collection], ..... | 70689c54d1a67e809bf134dd586b2ea05ff4c431 | <|skeleton|>
class IntelUtils:
def get_threatlist_generating_searches(self, session_key):
"""Return a complete list of threatlist generating searches as a dictionary of: {search_name: [kvstore_collection], ...}"""
<|body_0|>
def get_stanza_update_times(cls, conf, app, stanzas, param='modtime')... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IntelUtils:
def get_threatlist_generating_searches(self, session_key):
"""Return a complete list of threatlist generating searches as a dictionary of: {search_name: [kvstore_collection], ...}"""
getargs = {'search': 'action.threat_outputlookup=1', 'output_mode': 'json', 'count': 0}
unu... | the_stack_v2_python_sparse | DA-ESS-ThreatIntelligence/bin/parsers/utils.py | reza/es_eventgens | train | 0 | |
ce62854d93d713c3085b9ea2038b607f067d7e81 | [
"self._parameters = parameters\nif not hasattr(self, '_mapper'):\n self._mapper = AWSProviderMap(provider=self.provider, report_type=parameters.report_type, cost_type=parameters.parameters.get('cost_type', KOKU_DEFAULT_COST_TYPE))\nif parameters.get_filter('enabled') is None:\n parameters.set_filter(**{'enabl... | <|body_start_0|>
self._parameters = parameters
if not hasattr(self, '_mapper'):
self._mapper = AWSProviderMap(provider=self.provider, report_type=parameters.report_type, cost_type=parameters.parameters.get('cost_type', KOKU_DEFAULT_COST_TYPE))
if parameters.get_filter('enabled') is N... | Handles tag queries and responses for AWS. | AWSTagQueryHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWSTagQueryHandler:
"""Handles tag queries and responses for AWS."""
def __init__(self, parameters):
"""Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query"""
<|body_0|>
def filter_map(self):
"""Establish which filte... | stack_v2_sparse_classes_75kplus_train_008935 | 3,275 | permissive | [
{
"docstring": "Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query",
"name": "__init__",
"signature": "def __init__(self, parameters)"
},
{
"docstring": "Establish which filter map to use based on tag API.",
"name": "filter_map",
"signature... | 2 | stack_v2_sparse_classes_30k_train_037452 | Implement the Python class `AWSTagQueryHandler` described below.
Class description:
Handles tag queries and responses for AWS.
Method signatures and docstrings:
- def __init__(self, parameters): Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query
- def filter_map(self): ... | Implement the Python class `AWSTagQueryHandler` described below.
Class description:
Handles tag queries and responses for AWS.
Method signatures and docstrings:
- def __init__(self, parameters): Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query
- def filter_map(self): ... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class AWSTagQueryHandler:
"""Handles tag queries and responses for AWS."""
def __init__(self, parameters):
"""Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query"""
<|body_0|>
def filter_map(self):
"""Establish which filte... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AWSTagQueryHandler:
"""Handles tag queries and responses for AWS."""
def __init__(self, parameters):
"""Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query"""
self._parameters = parameters
if not hasattr(self, '_mapper'):
... | the_stack_v2_python_sparse | koku/api/tags/aws/queries.py | project-koku/koku | train | 225 |
671b592552b12e2645fb1e4aa3cb30a68de8592c | [
"pre_changed = 1\npre_not_changed = 0\nmax_num = 2 ** 31\nfor i in range(1, len(A)):\n cur_not_change = max_num\n if A[i] > A[i - 1] and B[i] > B[i - 1]:\n cur_not_change = min(cur_not_change, pre_not_changed)\n if A[i] > B[i - 1] and B[i] > A[i - 1]:\n cur_not_change = min(cur_not_change, pr... | <|body_start_0|>
pre_changed = 1
pre_not_changed = 0
max_num = 2 ** 31
for i in range(1, len(A)):
cur_not_change = max_num
if A[i] > A[i - 1] and B[i] > B[i - 1]:
cur_not_change = min(cur_not_change, pre_not_changed)
if A[i] > B[i - 1] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minSwap(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int"""
<|body_0|>
def minSwap2(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int"""
<|body_1|>
def minSwap1(self, A, B):
""":type A: List[int] :ty... | stack_v2_sparse_classes_75kplus_train_008936 | 11,766 | no_license | [
{
"docstring": ":type A: List[int] :type B: List[int] :rtype: int",
"name": "minSwap",
"signature": "def minSwap(self, A, B)"
},
{
"docstring": ":type A: List[int] :type B: List[int] :rtype: int",
"name": "minSwap2",
"signature": "def minSwap2(self, A, B)"
},
{
"docstring": ":typ... | 3 | stack_v2_sparse_classes_30k_train_021723 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSwap(self, A, B): :type A: List[int] :type B: List[int] :rtype: int
- def minSwap2(self, A, B): :type A: List[int] :type B: List[int] :rtype: int
- def minSwap1(self, A, B... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSwap(self, A, B): :type A: List[int] :type B: List[int] :rtype: int
- def minSwap2(self, A, B): :type A: List[int] :type B: List[int] :rtype: int
- def minSwap1(self, A, B... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def minSwap(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int"""
<|body_0|>
def minSwap2(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int"""
<|body_1|>
def minSwap1(self, A, B):
""":type A: List[int] :ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minSwap(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int"""
pre_changed = 1
pre_not_changed = 0
max_num = 2 ** 31
for i in range(1, len(A)):
cur_not_change = max_num
if A[i] > A[i - 1] and B[i] > B[i - 1]:
... | the_stack_v2_python_sparse | python/leetcode/801_Minimum_Swaps_To_Make_Sequences_Increasing.py | bobcaoge/my-code | train | 0 | |
ce8eefc65189e1c03def86e94c5361f00e3d1251 | [
"try:\n receiver = self.cleaned_data.get('receiver', '')\n self.instance.receiver = User.objects.get(username=receiver)\n return receiver\nexcept User.DoesNotExist:\n raise forms.ValidationError('Receiver does not exist')",
"raw_content = self.cleaned_data.get('content')\nif not len(raw_content):\n ... | <|body_start_0|>
try:
receiver = self.cleaned_data.get('receiver', '')
self.instance.receiver = User.objects.get(username=receiver)
return receiver
except User.DoesNotExist:
raise forms.ValidationError('Receiver does not exist')
<|end_body_0|>
<|body_star... | New message form | MessageForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageForm:
"""New message form"""
def clean_receiver(self):
"""Clean receiver"""
<|body_0|>
def clean_content(self):
"""Clean content"""
<|body_1|>
def save(self, *args, **kwargs):
"""Set sender if not exist"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_008937 | 1,309 | no_license | [
{
"docstring": "Clean receiver",
"name": "clean_receiver",
"signature": "def clean_receiver(self)"
},
{
"docstring": "Clean content",
"name": "clean_content",
"signature": "def clean_content(self)"
},
{
"docstring": "Set sender if not exist",
"name": "save",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_013707 | Implement the Python class `MessageForm` described below.
Class description:
New message form
Method signatures and docstrings:
- def clean_receiver(self): Clean receiver
- def clean_content(self): Clean content
- def save(self, *args, **kwargs): Set sender if not exist | Implement the Python class `MessageForm` described below.
Class description:
New message form
Method signatures and docstrings:
- def clean_receiver(self): Clean receiver
- def clean_content(self): Clean content
- def save(self, *args, **kwargs): Set sender if not exist
<|skeleton|>
class MessageForm:
"""New mes... | 39deb1dc046c80edd6bfdfbef8391842eda35dd2 | <|skeleton|>
class MessageForm:
"""New message form"""
def clean_receiver(self):
"""Clean receiver"""
<|body_0|>
def clean_content(self):
"""Clean content"""
<|body_1|>
def save(self, *args, **kwargs):
"""Set sender if not exist"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MessageForm:
"""New message form"""
def clean_receiver(self):
"""Clean receiver"""
try:
receiver = self.cleaned_data.get('receiver', '')
self.instance.receiver = User.objects.get(username=receiver)
return receiver
except User.DoesNotExist:
... | the_stack_v2_python_sparse | src/messaging/forms.py | nvbn/djang0byte | train | 26 |
3ae17abbc500fc0e7228e614034e9e49eb272962 | [
"self._input = tf.placeholder(tf.float32, self._batch_shape, name='input')\nself._encoding = tf.placeholder(tf.float32, (FLAGS.batch_size, self.layer_narrow), name='encoding')\nself._encode = pt.wrap(self._input).flatten().fully_connected(self.layer_encoder, name='enc_hidden').fully_connected(self.layer_narrow, nam... | <|body_start_0|>
self._input = tf.placeholder(tf.float32, self._batch_shape, name='input')
self._encoding = tf.placeholder(tf.float32, (FLAGS.batch_size, self.layer_narrow), name='encoding')
self._encode = pt.wrap(self._input).flatten().fully_connected(self.layer_encoder, name='enc_hidden').full... | DCIGNModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DCIGNModel:
def _build_encoder(self):
"""Construct encoder network: placeholders, operations, optimizer"""
<|body_0|>
def _build_decoder(self, weight_init=tf.truncated_normal):
"""Construct decoder network: placeholders, operations, optimizer, extract gradient back-p... | stack_v2_sparse_classes_75kplus_train_008938 | 5,064 | permissive | [
{
"docstring": "Construct encoder network: placeholders, operations, optimizer",
"name": "_build_encoder",
"signature": "def _build_encoder(self)"
},
{
"docstring": "Construct decoder network: placeholders, operations, optimizer, extract gradient back-prop for encoding layer",
"name": "_buil... | 2 | stack_v2_sparse_classes_30k_train_001823 | Implement the Python class `DCIGNModel` described below.
Class description:
Implement the DCIGNModel class.
Method signatures and docstrings:
- def _build_encoder(self): Construct encoder network: placeholders, operations, optimizer
- def _build_decoder(self, weight_init=tf.truncated_normal): Construct decoder networ... | Implement the Python class `DCIGNModel` described below.
Class description:
Implement the DCIGNModel class.
Method signatures and docstrings:
- def _build_encoder(self): Construct encoder network: placeholders, operations, optimizer
- def _build_decoder(self, weight_init=tf.truncated_normal): Construct decoder networ... | ff8d85f3a7b7ca1e5c3f50ff003a1c09a70067cd | <|skeleton|>
class DCIGNModel:
def _build_encoder(self):
"""Construct encoder network: placeholders, operations, optimizer"""
<|body_0|>
def _build_decoder(self, weight_init=tf.truncated_normal):
"""Construct decoder network: placeholders, operations, optimizer, extract gradient back-p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DCIGNModel:
def _build_encoder(self):
"""Construct encoder network: placeholders, operations, optimizer"""
self._input = tf.placeholder(tf.float32, self._batch_shape, name='input')
self._encoding = tf.placeholder(tf.float32, (FLAGS.batch_size, self.layer_narrow), name='encoding')
... | the_stack_v2_python_sparse | DCIGNModel.py | yselivonchyk/TensorFlow_DCIGN | train | 23 | |
e8a821bc55287e5e1bffb38bebda5515c1608a55 | [
"self.r_speckle = 4\nself.window_shape = (self.r_speckle * 2 + 1, self.r_speckle * 2 + 1)\np_masked = 0.3\nself.max_masked_values = self.window_shape[0] * self.window_shape[1] * p_masked\nself.r_interp = 2",
"mask_windows = neighbourhood_tools.pad_and_roll(cube.data.mask, self.window_shape, mode='constant', const... | <|body_start_0|>
self.r_speckle = 4
self.window_shape = (self.r_speckle * 2 + 1, self.r_speckle * 2 + 1)
p_masked = 0.3
self.max_masked_values = self.window_shape[0] * self.window_shape[1] * p_masked
self.r_interp = 2
<|end_body_0|>
<|body_start_1|>
mask_windows = neighb... | Fill in small "no data" regions in the radar composite by interpolating in log rainrate space. The log-linear transformation does not preserve non-zero rainrates of less than 0.001 mm/h. Since the radar composite encodes trace rain rates with a value of 0.03 mm/h, this should not have any effect on "real" data from the... | FillRadarHoles | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FillRadarHoles:
"""Fill in small "no data" regions in the radar composite by interpolating in log rainrate space. The log-linear transformation does not preserve non-zero rainrates of less than 0.001 mm/h. Since the radar composite encodes trace rain rates with a value of 0.03 mm/h, this should n... | stack_v2_sparse_classes_75kplus_train_008939 | 16,064 | permissive | [
{
"docstring": "Initialise parameters of interpolation The constants defining neighbourhood size and proportion of neighbouring masked pixels for speckle identification have been empirically tuned for UK radar data. As configured, this method will flag \"holes\" of up to 24 pixels in size (30% of a 9 x 9 neighb... | 3 | stack_v2_sparse_classes_30k_train_026233 | Implement the Python class `FillRadarHoles` described below.
Class description:
Fill in small "no data" regions in the radar composite by interpolating in log rainrate space. The log-linear transformation does not preserve non-zero rainrates of less than 0.001 mm/h. Since the radar composite encodes trace rain rates w... | Implement the Python class `FillRadarHoles` described below.
Class description:
Fill in small "no data" regions in the radar composite by interpolating in log rainrate space. The log-linear transformation does not preserve non-zero rainrates of less than 0.001 mm/h. Since the radar composite encodes trace rain rates w... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class FillRadarHoles:
"""Fill in small "no data" regions in the radar composite by interpolating in log rainrate space. The log-linear transformation does not preserve non-zero rainrates of less than 0.001 mm/h. Since the radar composite encodes trace rain rates with a value of 0.03 mm/h, this should n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FillRadarHoles:
"""Fill in small "no data" regions in the radar composite by interpolating in log rainrate space. The log-linear transformation does not preserve non-zero rainrates of less than 0.001 mm/h. Since the radar composite encodes trace rain rates with a value of 0.03 mm/h, this should not have any e... | the_stack_v2_python_sparse | improver/nowcasting/utilities.py | metoppv/improver | train | 101 |
39b1b30263f8167fb40c9b2ffb01e5d47034a294 | [
"pass\npre = head\nif not pre:\n return head\ni = pre.next\nwhile pre and i != last:\n n = i.next\n i.next = pre\n pre = i\n i = n\nhead.next = i\nreturn pre",
"guard = ListNode(0)\nguard.next = head\npre = guard\nwhile True:\n l = pre.next\n count = 1\n r = l\n while r and count < k:\n... | <|body_start_0|>
pass
pre = head
if not pre:
return head
i = pre.next
while pre and i != last:
n = i.next
i.next = pre
pre = i
i = n
head.next = i
return pre
<|end_body_0|>
<|body_start_1|>
guard... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, head, last=None):
"""reverse [head,last) :param head: ListNode :param last: ListNode :return: ListNode"""
<|body_0|>
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_008940 | 2,393 | no_license | [
{
"docstring": "reverse [head,last) :param head: ListNode :param last: ListNode :return: ListNode",
"name": "reverse",
"signature": "def reverse(self, head, last=None)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "reverseKGroup",
"signature": "def reve... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, head, last=None): reverse [head,last) :param head: ListNode :param last: ListNode :return: ListNode
- def reverseKGroup(self, head, k): :type head: ListNode :ty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, head, last=None): reverse [head,last) :param head: ListNode :param last: ListNode :return: ListNode
- def reverseKGroup(self, head, k): :type head: ListNode :ty... | f8f3b0cdb47ee6bb4bf9bdc7c2a983f4a882d9dd | <|skeleton|>
class Solution:
def reverse(self, head, last=None):
"""reverse [head,last) :param head: ListNode :param last: ListNode :return: ListNode"""
<|body_0|>
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverse(self, head, last=None):
"""reverse [head,last) :param head: ListNode :param last: ListNode :return: ListNode"""
pass
pre = head
if not pre:
return head
i = pre.next
while pre and i != last:
n = i.next
i.n... | the_stack_v2_python_sparse | solutions/025-reverse-nodes-in-k-group/main.py | CallMeNP/leetcode | train | 0 | |
e6164e470ea8b3e7fb60a21db9dd465ee5738e07 | [
"miner = Miner(name='Miner', version='1.0.b')\nminer.slug = get_unique_slug(miner, 'slug', 'name', 'version')\nminer.save()\nother_miner = Miner(name='MineR', version='1.0.b')\nother_miner.slug = get_unique_slug(other_miner, 'slug', 'name', 'version')\nself.assertNotEqual(miner.slug, other_miner.slug)",
"miner = ... | <|body_start_0|>
miner = Miner(name='Miner', version='1.0.b')
miner.slug = get_unique_slug(miner, 'slug', 'name', 'version')
miner.save()
other_miner = Miner(name='MineR', version='1.0.b')
other_miner.slug = get_unique_slug(other_miner, 'slug', 'name', 'version')
self.ass... | Тестирование гнерератора slug | GetSlugTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetSlugTest:
"""Тестирование гнерератора slug"""
def test_get_unique_slug(self):
"""Генерация уникального slug"""
<|body_0|>
def test_get_unique_slug_conflict(self):
"""Генерация уникального slug недопустимого значения"""
<|body_1|>
def test_get_slug... | stack_v2_sparse_classes_75kplus_train_008941 | 13,105 | permissive | [
{
"docstring": "Генерация уникального slug",
"name": "test_get_unique_slug",
"signature": "def test_get_unique_slug(self)"
},
{
"docstring": "Генерация уникального slug недопустимого значения",
"name": "test_get_unique_slug_conflict",
"signature": "def test_get_unique_slug_conflict(self)... | 5 | stack_v2_sparse_classes_30k_train_035872 | Implement the Python class `GetSlugTest` described below.
Class description:
Тестирование гнерератора slug
Method signatures and docstrings:
- def test_get_unique_slug(self): Генерация уникального slug
- def test_get_unique_slug_conflict(self): Генерация уникального slug недопустимого значения
- def test_get_slug(sel... | Implement the Python class `GetSlugTest` described below.
Class description:
Тестирование гнерератора slug
Method signatures and docstrings:
- def test_get_unique_slug(self): Генерация уникального slug
- def test_get_unique_slug_conflict(self): Генерация уникального slug недопустимого значения
- def test_get_slug(sel... | d173f1bee44d0752eefb53b1a0da847a3882a352 | <|skeleton|>
class GetSlugTest:
"""Тестирование гнерератора slug"""
def test_get_unique_slug(self):
"""Генерация уникального slug"""
<|body_0|>
def test_get_unique_slug_conflict(self):
"""Генерация уникального slug недопустимого значения"""
<|body_1|>
def test_get_slug... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetSlugTest:
"""Тестирование гнерератора slug"""
def test_get_unique_slug(self):
"""Генерация уникального slug"""
miner = Miner(name='Miner', version='1.0.b')
miner.slug = get_unique_slug(miner, 'slug', 'name', 'version')
miner.save()
other_miner = Miner(name='Mine... | the_stack_v2_python_sparse | miningstatistic/core/tests.py | crowmurk/miners | train | 0 |
e6586be0231f50ef86ddfc9151476303f4593616 | [
"self.train_set = train_set\nself.val_set = val_set\nself.cost = cost_func\nself.loss = loss_func\nself.training = False\nself.step = 0\npass",
"self.lr = lr\nself.lr_dec = lr_dec\nself.training = True\nfor Y in output_layer.pull_forward():\n L = np.squeeze(self.cost.f(self.T, Y))\n dL = self.cost.d(self.T,... | <|body_start_0|>
self.train_set = train_set
self.val_set = val_set
self.cost = cost_func
self.loss = loss_func
self.training = False
self.step = 0
pass
<|end_body_0|>
<|body_start_1|>
self.lr = lr
self.lr_dec = lr_dec
self.training = True
... | NeuralNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralNetwork:
def __init__(self, train_set, val_set, cost_func, loss_func):
"""Initialization of NeuralNetwork Args: train_set: A generator that iterates through training data. val_set: A generator that iterates through validation data. cost_func: A cost function minimized during traini... | stack_v2_sparse_classes_75kplus_train_008942 | 2,681 | no_license | [
{
"docstring": "Initialization of NeuralNetwork Args: train_set: A generator that iterates through training data. val_set: A generator that iterates through validation data. cost_func: A cost function minimized during training. loss_func: A loss function for performance validation.",
"name": "__init__",
... | 4 | stack_v2_sparse_classes_30k_train_035512 | Implement the Python class `NeuralNetwork` described below.
Class description:
Implement the NeuralNetwork class.
Method signatures and docstrings:
- def __init__(self, train_set, val_set, cost_func, loss_func): Initialization of NeuralNetwork Args: train_set: A generator that iterates through training data. val_set:... | Implement the Python class `NeuralNetwork` described below.
Class description:
Implement the NeuralNetwork class.
Method signatures and docstrings:
- def __init__(self, train_set, val_set, cost_func, loss_func): Initialization of NeuralNetwork Args: train_set: A generator that iterates through training data. val_set:... | 3c10fe77098750c7a6a64a7faa2ea1fb4ad362e0 | <|skeleton|>
class NeuralNetwork:
def __init__(self, train_set, val_set, cost_func, loss_func):
"""Initialization of NeuralNetwork Args: train_set: A generator that iterates through training data. val_set: A generator that iterates through validation data. cost_func: A cost function minimized during traini... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeuralNetwork:
def __init__(self, train_set, val_set, cost_func, loss_func):
"""Initialization of NeuralNetwork Args: train_set: A generator that iterates through training data. val_set: A generator that iterates through validation data. cost_func: A cost function minimized during training. loss_func:... | the_stack_v2_python_sparse | mynn/NeuralNetwork.py | bugerry87/fcnn_scratch | train | 0 | |
bf119a4b4d7003e4ff18618465a83b0e37c164a1 | [
"log_message('*********************** setUp ***********************')\nself.props = get_all_properties(eval(os.environ.get('PARAMS', '{}')), 'INFO', default=DEFAULT_PROPERTIES)\nlog_message('*********************** core testing ***********************')\nself.driver = LocalBrowserInit().get_driver()\nLoginPage(self... | <|body_start_0|>
log_message('*********************** setUp ***********************')
self.props = get_all_properties(eval(os.environ.get('PARAMS', '{}')), 'INFO', default=DEFAULT_PROPERTIES)
log_message('*********************** core testing ***********************')
self.driver = LocalB... | All GUI tests are expected to use it as a superclass | BaseTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseTest:
"""All GUI tests are expected to use it as a superclass"""
def setUp(self):
"""Default setup for the tests using dictionary of properties from environment variable PARAMS If driver is set, open either local or SauceLabs driver :return:"""
<|body_0|>
def tearDow... | stack_v2_sparse_classes_75kplus_train_008943 | 1,642 | no_license | [
{
"docstring": "Default setup for the tests using dictionary of properties from environment variable PARAMS If driver is set, open either local or SauceLabs driver :return:",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "If driver was specified(and opened in setUp), close it... | 2 | stack_v2_sparse_classes_30k_train_009011 | Implement the Python class `BaseTest` described below.
Class description:
All GUI tests are expected to use it as a superclass
Method signatures and docstrings:
- def setUp(self): Default setup for the tests using dictionary of properties from environment variable PARAMS If driver is set, open either local or SauceLa... | Implement the Python class `BaseTest` described below.
Class description:
All GUI tests are expected to use it as a superclass
Method signatures and docstrings:
- def setUp(self): Default setup for the tests using dictionary of properties from environment variable PARAMS If driver is set, open either local or SauceLa... | ad1157a2e98110daf4835e24fe57bc0df7eb507f | <|skeleton|>
class BaseTest:
"""All GUI tests are expected to use it as a superclass"""
def setUp(self):
"""Default setup for the tests using dictionary of properties from environment variable PARAMS If driver is set, open either local or SauceLabs driver :return:"""
<|body_0|>
def tearDow... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseTest:
"""All GUI tests are expected to use it as a superclass"""
def setUp(self):
"""Default setup for the tests using dictionary of properties from environment variable PARAMS If driver is set, open either local or SauceLabs driver :return:"""
log_message('*********************** set... | the_stack_v2_python_sparse | common/base_tests/gui_basetest.py | nsluzky/returnly_affirm | train | 0 |
ba7c15ad207b7ca496aae16e0813f29e05dc157d | [
"self.trie = Trie()\nself.historical_sentence = ''\nself.dct = {}\nfor sentence, count in zip(sentences, times):\n self.trie.insert(sentence, count)\n self.dct[sentence] = count",
"if c == '#':\n self.trie.insert(self.historical_sentence, 1)\n self.historical_sentence = ''\n return []\nelse:\n s... | <|body_start_0|>
self.trie = Trie()
self.historical_sentence = ''
self.dct = {}
for sentence, count in zip(sentences, times):
self.trie.insert(sentence, count)
self.dct[sentence] = count
<|end_body_0|>
<|body_start_1|>
if c == '#':
self.trie.i... | AutocompleteSystem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.trie = Trie()
... | stack_v2_sparse_classes_75kplus_train_008944 | 2,307 | permissive | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047717 | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | 1f30ea37af7b60585d168b15d9397143f53c92a1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
self.trie = Trie()
self.historical_sentence = ''
self.dct = {}
for sentence, count in zip(sentences, times):
self.trie.insert(sentence, count)
... | the_stack_v2_python_sparse | design_search_autocomplete_system.py | pranavdave893/Leetcode | train | 0 | |
e27f9127712359f59833c549c8c26598cb79df6c | [
"super().__init__(config)\nfuncName = config['class'][1:]\nif not hasattr(builtin, funcName):\n raise TypeError('Unknown built-in summarizer \"{}\"'.format(funcName))\nself.ref = getattr(builtin, funcName)",
"if not self.getConfig('outliers', True):\n timeseries = util.reject_outliers(timeseries)\nreturn se... | <|body_start_0|>
super().__init__(config)
funcName = config['class'][1:]
if not hasattr(builtin, funcName):
raise TypeError('Unknown built-in summarizer "{}"'.format(funcName))
self.ref = getattr(builtin, funcName)
<|end_body_0|>
<|body_start_1|>
if not self.getConfi... | A proxy class that calls the built-in summarizer functions :: # Can be used without configuration, like so: metrics: - name: metric ... summarize: [mean, min, ] # Or with configuration like so: metrics: - name: metric ... summarize: - class @mean # The name of the metric in the plots name: mean # [Optional] Set to `yes... | BuiltInSummarizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuiltInSummarizer:
"""A proxy class that calls the built-in summarizer functions :: # Can be used without configuration, like so: metrics: - name: metric ... summarize: [mean, min, ] # Or with configuration like so: metrics: - name: metric ... summarize: - class @mean # The name of the metric in ... | stack_v2_sparse_classes_75kplus_train_008945 | 2,764 | permissive | [
{
"docstring": "Initialize summarizer",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Call the built-in summarizer function",
"name": "calculate",
"signature": "def calculate(self, timeseries: SummarizerAxisTimeseries, parameters: SummarizerAxisParamete... | 2 | stack_v2_sparse_classes_30k_train_019746 | Implement the Python class `BuiltInSummarizer` described below.
Class description:
A proxy class that calls the built-in summarizer functions :: # Can be used without configuration, like so: metrics: - name: metric ... summarize: [mean, min, ] # Or with configuration like so: metrics: - name: metric ... summarize: - c... | Implement the Python class `BuiltInSummarizer` described below.
Class description:
A proxy class that calls the built-in summarizer functions :: # Can be used without configuration, like so: metrics: - name: metric ... summarize: [mean, min, ] # Or with configuration like so: metrics: - name: metric ... summarize: - c... | 8fba87cb6c6f64690c0b5bef5c7d9f2aa0fba06b | <|skeleton|>
class BuiltInSummarizer:
"""A proxy class that calls the built-in summarizer functions :: # Can be used without configuration, like so: metrics: - name: metric ... summarize: [mean, min, ] # Or with configuration like so: metrics: - name: metric ... summarize: - class @mean # The name of the metric in ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BuiltInSummarizer:
"""A proxy class that calls the built-in summarizer functions :: # Can be used without configuration, like so: metrics: - name: metric ... summarize: [mean, min, ] # Or with configuration like so: metrics: - name: metric ... summarize: - class @mean # The name of the metric in the plots nam... | the_stack_v2_python_sparse | performance/driver/core/classes/summarizer.py | mesosphere/dcos-perf-test-driver | train | 2 |
ec07bc3891105831d3c964a675e998d8ab3004eb | [
"if isinstance(image, (glanceclient.v1.images.Image, warlock.model.Model)):\n images = [image_ for image_ in self._client.images.list() if image_.id == image.id]\n if len(images) == 0:\n raise NotFound()\n fresh = images[0]\n data = getattr(fresh, '_info', fresh)\n getattr(image, '_info', imag... | <|body_start_0|>
if isinstance(image, (glanceclient.v1.images.Image, warlock.model.Model)):
images = [image_ for image_ in self._client.images.list() if image_.id == image.id]
if len(images) == 0:
raise NotFound()
fresh = images[0]
data = getattr(f... | Glance base steps. | BaseGlanceSteps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseGlanceSteps:
"""Glance base steps."""
def _refresh_image(self, image):
"""Refresh local image data structure according to its type."""
<|body_0|>
def update_images(self, images, status=None, check=True, **kwargs):
"""Step to update images. Args: images (list)... | stack_v2_sparse_classes_75kplus_train_008946 | 6,671 | no_license | [
{
"docstring": "Refresh local image data structure according to its type.",
"name": "_refresh_image",
"signature": "def _refresh_image(self, image)"
},
{
"docstring": "Step to update images. Args: images (list): glance images status (str): status of image for assertion check (bool): flag whether... | 6 | stack_v2_sparse_classes_30k_train_044923 | Implement the Python class `BaseGlanceSteps` described below.
Class description:
Glance base steps.
Method signatures and docstrings:
- def _refresh_image(self, image): Refresh local image data structure according to its type.
- def update_images(self, images, status=None, check=True, **kwargs): Step to update images... | Implement the Python class `BaseGlanceSteps` described below.
Class description:
Glance base steps.
Method signatures and docstrings:
- def _refresh_image(self, image): Refresh local image data structure according to its type.
- def update_images(self, images, status=None, check=True, **kwargs): Step to update images... | e7583444cd24893ec6ae237b47db7c605b99b0c5 | <|skeleton|>
class BaseGlanceSteps:
"""Glance base steps."""
def _refresh_image(self, image):
"""Refresh local image data structure according to its type."""
<|body_0|>
def update_images(self, images, status=None, check=True, **kwargs):
"""Step to update images. Args: images (list)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseGlanceSteps:
"""Glance base steps."""
def _refresh_image(self, image):
"""Refresh local image data structure according to its type."""
if isinstance(image, (glanceclient.v1.images.Image, warlock.model.Model)):
images = [image_ for image_ in self._client.images.list() if im... | the_stack_v2_python_sparse | stepler/glance/steps/base.py | Mirantis/stepler | train | 16 |
acb158bed21a097adecc23ddab1a1fc3dda7b1e6 | [
"super().__init__()\nself.min_iterations = min_iterations\nself.max_iterations = max_iterations\nself.atol = atol\nself.gaptol = gaptol",
"self.particle_weights = np.array([1])\nmarginal, gap_between_consecutives = loopy_belief_propagation(state.past_test_results, state.past_groups, state.prior_infection_rate, st... | <|body_start_0|>
super().__init__()
self.min_iterations = min_iterations
self.max_iterations = max_iterations
self.atol = atol
self.gaptol = gaptol
<|end_body_0|>
<|body_start_1|>
self.particle_weights = np.array([1])
marginal, gap_between_consecutives = loopy_be... | Loopy Belief Propagation approximation to Marginal. | LbpSampler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LbpSampler:
"""Loopy Belief Propagation approximation to Marginal."""
def __init__(self, min_iterations=10, max_iterations=1000, atol=0.0001, gaptol=0.01):
"""Initialize LbpSampler with parameters passed on to LBP algorithm. Args: min_iterations : int, minimal number of executions pe... | stack_v2_sparse_classes_75kplus_train_008947 | 7,089 | permissive | [
{
"docstring": "Initialize LbpSampler with parameters passed on to LBP algorithm. Args: min_iterations : int, minimal number of executions per loop of LBP max_iterations : int, maximal number of iterations LBP updates marginal atol : float, tolerance parameter used to measure discrepancy between two consecutive... | 2 | stack_v2_sparse_classes_30k_train_003303 | Implement the Python class `LbpSampler` described below.
Class description:
Loopy Belief Propagation approximation to Marginal.
Method signatures and docstrings:
- def __init__(self, min_iterations=10, max_iterations=1000, atol=0.0001, gaptol=0.01): Initialize LbpSampler with parameters passed on to LBP algorithm. Ar... | Implement the Python class `LbpSampler` described below.
Class description:
Loopy Belief Propagation approximation to Marginal.
Method signatures and docstrings:
- def __init__(self, min_iterations=10, max_iterations=1000, atol=0.0001, gaptol=0.01): Initialize LbpSampler with parameters passed on to LBP algorithm. Ar... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class LbpSampler:
"""Loopy Belief Propagation approximation to Marginal."""
def __init__(self, min_iterations=10, max_iterations=1000, atol=0.0001, gaptol=0.01):
"""Initialize LbpSampler with parameters passed on to LBP algorithm. Args: min_iterations : int, minimal number of executions pe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LbpSampler:
"""Loopy Belief Propagation approximation to Marginal."""
def __init__(self, min_iterations=10, max_iterations=1000, atol=0.0001, gaptol=0.01):
"""Initialize LbpSampler with parameters passed on to LBP algorithm. Args: min_iterations : int, minimal number of executions per loop of LBP... | the_stack_v2_python_sparse | grouptesting/samplers/loopy_belief_propagation.py | Ayoob7/google-research | train | 2 |
c97e40fa3f228c914cc5a5ba9ca5208279559bcb | [
"instance_type = ContentType.objects.get_for_model(instance)\ndocument = prov.model.ProvDocument(namespaces={'piot': 'http://www.pedasi-iot.org/', 'foaf': 'http://xmlns.com/foaf/0.1/', 'xsd': 'http://www.w3.org/2001/XMLSchema#'})\nentity = document.entity('piot:e-' + slugify(instance_type.model) + str(instance.pk),... | <|body_start_0|>
instance_type = ContentType.objects.get_for_model(instance)
document = prov.model.ProvDocument(namespaces={'piot': 'http://www.pedasi-iot.org/', 'foaf': 'http://xmlns.com/foaf/0.1/', 'xsd': 'http://www.w3.org/2001/XMLSchema#'})
entity = document.entity('piot:e-' + slugify(instan... | Stored PROV record for a single action. e.g. Update a model's metadata, use a model. These will be referred to by a :class:`ProvWrapper` document. | ProvEntry | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProvEntry:
"""Stored PROV record for a single action. e.g. Update a model's metadata, use a model. These will be referred to by a :class:`ProvWrapper` document."""
def create_prov(cls, instance: BaseAppDataModel, user_uri: str, application: typing.Optional[ProvApplicationModel]=None, activit... | stack_v2_sparse_classes_75kplus_train_008948 | 10,004 | permissive | [
{
"docstring": "Build a PROV document representing a particular activity within PEDASI. :param instance: Application or DataSource which is the object of the activity :param user_uri: URI of user who performed the activity :param application: Application which the user used to perform the activity :param activi... | 2 | stack_v2_sparse_classes_30k_train_021588 | Implement the Python class `ProvEntry` described below.
Class description:
Stored PROV record for a single action. e.g. Update a model's metadata, use a model. These will be referred to by a :class:`ProvWrapper` document.
Method signatures and docstrings:
- def create_prov(cls, instance: BaseAppDataModel, user_uri: s... | Implement the Python class `ProvEntry` described below.
Class description:
Stored PROV record for a single action. e.g. Update a model's metadata, use a model. These will be referred to by a :class:`ProvWrapper` document.
Method signatures and docstrings:
- def create_prov(cls, instance: BaseAppDataModel, user_uri: s... | 25a111ac7cf4b23fee50ad8eac6ea21564954859 | <|skeleton|>
class ProvEntry:
"""Stored PROV record for a single action. e.g. Update a model's metadata, use a model. These will be referred to by a :class:`ProvWrapper` document."""
def create_prov(cls, instance: BaseAppDataModel, user_uri: str, application: typing.Optional[ProvApplicationModel]=None, activit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProvEntry:
"""Stored PROV record for a single action. e.g. Update a model's metadata, use a model. These will be referred to by a :class:`ProvWrapper` document."""
def create_prov(cls, instance: BaseAppDataModel, user_uri: str, application: typing.Optional[ProvApplicationModel]=None, activity_type: typin... | the_stack_v2_python_sparse | provenance/models.py | PEDASI/PEDASI | train | 0 |
3aebbe5d5b739303dd15b72ea10cfe8bd40ff2db | [
"if len(matrix) == 0 or len(matrix[0]) == 0:\n return 0\nretangle = []\nres = 0\nfor arr in matrix:\n if len(retangle) == 0:\n retangle = [int(x) for x in arr]\n else:\n for j in range(len(arr)):\n if arr[j] == '0':\n retangle[j] = 0\n else:\n ... | <|body_start_0|>
if len(matrix) == 0 or len(matrix[0]) == 0:
return 0
retangle = []
res = 0
for arr in matrix:
if len(retangle) == 0:
retangle = [int(x) for x in arr]
else:
for j in range(len(arr)):
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
"""classic approach: dynamic programming + max area within a histogram(leetcode 84) - similar to lc1504 e.g. [ [1,0,1,0,0], [1,0,1,1,1], [1,1,1,1,1], [1,0,0,1,0], ] for each row, we accumulate the ones on the grids on position in previous row... | stack_v2_sparse_classes_75kplus_train_008949 | 2,976 | no_license | [
{
"docstring": "classic approach: dynamic programming + max area within a histogram(leetcode 84) - similar to lc1504 e.g. [ [1,0,1,0,0], [1,0,1,1,1], [1,1,1,1,1], [1,0,0,1,0], ] for each row, we accumulate the ones on the grids on position in previous row and find the area of the current histogram [1,0,1,0,0] <... | 2 | stack_v2_sparse_classes_30k_train_019903 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): classic approach: dynamic programming + max area within a histogram(leetcode 84) - similar to lc1504 e.g. [ [1,0,1,0,0], [1,0,1,1,1], [1,1,1,1... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): classic approach: dynamic programming + max area within a histogram(leetcode 84) - similar to lc1504 e.g. [ [1,0,1,0,0], [1,0,1,1,1], [1,1,1,1... | 1bd17e867d1d557a6ebbbd99f693d5fbd9f5b61e | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
"""classic approach: dynamic programming + max area within a histogram(leetcode 84) - similar to lc1504 e.g. [ [1,0,1,0,0], [1,0,1,1,1], [1,1,1,1,1], [1,0,0,1,0], ] for each row, we accumulate the ones on the grids on position in previous row... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maximalRectangle(self, matrix):
"""classic approach: dynamic programming + max area within a histogram(leetcode 84) - similar to lc1504 e.g. [ [1,0,1,0,0], [1,0,1,1,1], [1,1,1,1,1], [1,0,0,1,0], ] for each row, we accumulate the ones on the grids on position in previous row and find the ... | the_stack_v2_python_sparse | leetcode/85-maximal-retangle/main.py | shriharshs/AlgoDaily | train | 0 | |
1337f3e8f264dfd4087113a6cab64e06222c70f5 | [
"print(\"\\nTéléchargement de l'url:\", someurl)\nreq = Request(someurl)\nreq.add_header('User-agent', 'Multi lame 1.0')\nresponse = None\ntry:\n response = urlopen(req, timeout=timeout)\n response = response.read()\nexcept URLError as e:\n if hasattr(e, 'reason'):\n print('Server is unreachable.')\... | <|body_start_0|>
print("\nTéléchargement de l'url:", someurl)
req = Request(someurl)
req.add_header('User-agent', 'Multi lame 1.0')
response = None
try:
response = urlopen(req, timeout=timeout)
response = response.read()
except URLError as e:
... | Télécharge une url. Retourne - un string si text (html) - des bytes si fichier Enregistre dans un fichier Usage: hd = HttpDownload() # recupère la réponse resp = hd.get_response(url, timeout=2) # ou enregistre hd.save_response(u, timeout=2, name=name) # ou les 2 resp = hd.save_response(u, timeout=2, name=name) | HttpDownload | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpDownload:
"""Télécharge une url. Retourne - un string si text (html) - des bytes si fichier Enregistre dans un fichier Usage: hd = HttpDownload() # recupère la réponse resp = hd.get_response(url, timeout=2) # ou enregistre hd.save_response(u, timeout=2, name=name) # ou les 2 resp = hd.save_re... | stack_v2_sparse_classes_75kplus_train_008950 | 3,792 | no_license | [
{
"docstring": "Télécharge une url. Retourne des bytes: https://bit.ly/2wau8j1 ou string vide",
"name": "request",
"signature": "def request(self, someurl, timeout=2)"
},
{
"docstring": "Decode utf-8 si text, rien si fichier. Donc text = utf-8, fichier = bytes",
"name": "decode_or_not",
... | 4 | null | Implement the Python class `HttpDownload` described below.
Class description:
Télécharge une url. Retourne - un string si text (html) - des bytes si fichier Enregistre dans un fichier Usage: hd = HttpDownload() # recupère la réponse resp = hd.get_response(url, timeout=2) # ou enregistre hd.save_response(u, timeout=2, ... | Implement the Python class `HttpDownload` described below.
Class description:
Télécharge une url. Retourne - un string si text (html) - des bytes si fichier Enregistre dans un fichier Usage: hd = HttpDownload() # recupère la réponse resp = hd.get_response(url, timeout=2) # ou enregistre hd.save_response(u, timeout=2, ... | b931caf107457aea4caea2b0ce821e981d19bd79 | <|skeleton|>
class HttpDownload:
"""Télécharge une url. Retourne - un string si text (html) - des bytes si fichier Enregistre dans un fichier Usage: hd = HttpDownload() # recupère la réponse resp = hd.get_response(url, timeout=2) # ou enregistre hd.save_response(u, timeout=2, name=name) # ou les 2 resp = hd.save_re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HttpDownload:
"""Télécharge une url. Retourne - un string si text (html) - des bytes si fichier Enregistre dans un fichier Usage: hd = HttpDownload() # recupère la réponse resp = hd.get_response(url, timeout=2) # ou enregistre hd.save_response(u, timeout=2, name=name) # ou les 2 resp = hd.save_response(u, tim... | the_stack_v2_python_sparse | py_9_divers/py_80_exo_class_bad/py_85_http/py_85_httpdownload_response.py | sergeLabo/formation_python | train | 0 |
583925a723986655740b8d146306d99914d0ed5d | [
"super(ComboObjScene, self).__init__()\nself.label.setText(label)\nself.folder = folder\nif not os.path.isdir(self.folder):\n raise EnvironmentError('Input: {} is not a valid folder'.format(self.folder))\nself.add_combobox_items()",
"for f in os.listdir(self.folder):\n if os.path.isdir(os.path, join(self.fo... | <|body_start_0|>
super(ComboObjScene, self).__init__()
self.label.setText(label)
self.folder = folder
if not os.path.isdir(self.folder):
raise EnvironmentError('Input: {} is not a valid folder'.format(self.folder))
self.add_combobox_items()
<|end_body_0|>
<|body_star... | The scene folder combo box needs to have its items populated by whatever is in consts.SCENE_FOLDER_DIR and so a sub-class is used. After the scenes are created, the first scene is selected or the user's preferred scene. | ComboObjScene | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComboObjScene:
"""The scene folder combo box needs to have its items populated by whatever is in consts.SCENE_FOLDER_DIR and so a sub-class is used. After the scenes are created, the first scene is selected or the user's preferred scene."""
def __init__(self, label, folder):
"""Inits... | stack_v2_sparse_classes_75kplus_train_008951 | 4,781 | no_license | [
{
"docstring": "Inits the combo box and sets a few small GUI changes Args: label (str): The title of the combo box (will be placed above the box) folder (str): The full path location to a directory",
"name": "__init__",
"signature": "def __init__(self, label, folder)"
},
{
"docstring": "Populate... | 2 | stack_v2_sparse_classes_30k_val_002514 | Implement the Python class `ComboObjScene` described below.
Class description:
The scene folder combo box needs to have its items populated by whatever is in consts.SCENE_FOLDER_DIR and so a sub-class is used. After the scenes are created, the first scene is selected or the user's preferred scene.
Method signatures a... | Implement the Python class `ComboObjScene` described below.
Class description:
The scene folder combo box needs to have its items populated by whatever is in consts.SCENE_FOLDER_DIR and so a sub-class is used. After the scenes are created, the first scene is selected or the user's preferred scene.
Method signatures a... | 6886f05d54ec77b66d13b4eaafe8a66ac49f2f41 | <|skeleton|>
class ComboObjScene:
"""The scene folder combo box needs to have its items populated by whatever is in consts.SCENE_FOLDER_DIR and so a sub-class is used. After the scenes are created, the first scene is selected or the user's preferred scene."""
def __init__(self, label, folder):
"""Inits... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComboObjScene:
"""The scene folder combo box needs to have its items populated by whatever is in consts.SCENE_FOLDER_DIR and so a sub-class is used. After the scenes are created, the first scene is selected or the user's preferred scene."""
def __init__(self, label, folder):
"""Inits the combo bo... | the_stack_v2_python_sparse | Pipeline/the_LATEST/sys_PY/py_MODULES/shotselection/view/_archive/openfiledialog.py | tws0002/pop2-project | train | 1 |
56372b6003ecaffc555fca403c207cf95e64cf51 | [
"super().__init__()\nself.name = 'PillarFeatureNet'\nassert len(num_filters) > 0\nnum_input_features += 0\nif with_distance:\n num_input_features += 1\nself._with_distance = with_distance\nself.height = height\nself.width = width\nself.depth = depth\nnum_filters = [num_input_features] + list(num_filters)\npfn_la... | <|body_start_0|>
super().__init__()
self.name = 'PillarFeatureNet'
assert len(num_filters) > 0
num_input_features += 0
if with_distance:
num_input_features += 1
self._with_distance = with_distance
self.height = height
self.width = width
... | PillarFeatureNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PillarFeatureNet:
def __init__(self, num_input_features=4, use_norm=True, num_filters=(64,), height=480, width=480, depth=2, with_distance=False):
"""Pillar Feature Net. The network prepares the pillar features and performs forward pass through PFNLayers. This net performs a similar role... | stack_v2_sparse_classes_75kplus_train_008952 | 7,758 | no_license | [
{
"docstring": "Pillar Feature Net. The network prepares the pillar features and performs forward pass through PFNLayers. This net performs a similar role to SECOND's second.pytorch.voxelnet.VoxelFeatureExtractor. :param num_input_features: <int>. Number of input features, either x, y, z or x, y, z, r. :param u... | 2 | stack_v2_sparse_classes_30k_train_038526 | Implement the Python class `PillarFeatureNet` described below.
Class description:
Implement the PillarFeatureNet class.
Method signatures and docstrings:
- def __init__(self, num_input_features=4, use_norm=True, num_filters=(64,), height=480, width=480, depth=2, with_distance=False): Pillar Feature Net. The network p... | Implement the Python class `PillarFeatureNet` described below.
Class description:
Implement the PillarFeatureNet class.
Method signatures and docstrings:
- def __init__(self, num_input_features=4, use_norm=True, num_filters=(64,), height=480, width=480, depth=2, with_distance=False): Pillar Feature Net. The network p... | 43388efd911feecde588b27a753de353b8e28265 | <|skeleton|>
class PillarFeatureNet:
def __init__(self, num_input_features=4, use_norm=True, num_filters=(64,), height=480, width=480, depth=2, with_distance=False):
"""Pillar Feature Net. The network prepares the pillar features and performs forward pass through PFNLayers. This net performs a similar role... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PillarFeatureNet:
def __init__(self, num_input_features=4, use_norm=True, num_filters=(64,), height=480, width=480, depth=2, with_distance=False):
"""Pillar Feature Net. The network prepares the pillar features and performs forward pass through PFNLayers. This net performs a similar role to SECOND's s... | the_stack_v2_python_sparse | models/backbones/pointpillars_voxel.py | dragonlong/haoi-pose | train | 0 | |
070b52618092897735850be4d44e6fdc6a66e34c | [
"if 'WORKDIR' not in PATH:\n setattr(PATH, 'WORKDIR', abspath('.'))\nif 'SCRATCH' not in PATH:\n setattr(PATH, 'SCRATCH', PATH.WORKDIR + '/' + 'scratch')\nif 'NODESIZE' not in PAR:\n setattr(PAR, 'NODESIZE', 16)\nsuper(tiger_lg, self).check()",
"if not exists(PATH.SCRATCH):\n path = '/scratch/gpfs' + ... | <|body_start_0|>
if 'WORKDIR' not in PATH:
setattr(PATH, 'WORKDIR', abspath('.'))
if 'SCRATCH' not in PATH:
setattr(PATH, 'SCRATCH', PATH.WORKDIR + '/' + 'scratch')
if 'NODESIZE' not in PAR:
setattr(PAR, 'NODESIZE', 16)
super(tiger_lg, self).check()
<|... | Specially designed system interface for tiger.princeton.edu See parent class for more information. | tiger_lg | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tiger_lg:
"""Specially designed system interface for tiger.princeton.edu See parent class for more information."""
def check(self):
"""Checks parameters and paths"""
<|body_0|>
def submit(self, *args, **kwargs):
"""Submits job"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_008953 | 1,258 | permissive | [
{
"docstring": "Checks parameters and paths",
"name": "check",
"signature": "def check(self)"
},
{
"docstring": "Submits job",
"name": "submit",
"signature": "def submit(self, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `tiger_lg` described below.
Class description:
Specially designed system interface for tiger.princeton.edu See parent class for more information.
Method signatures and docstrings:
- def check(self): Checks parameters and paths
- def submit(self, *args, **kwargs): Submits job | Implement the Python class `tiger_lg` described below.
Class description:
Specially designed system interface for tiger.princeton.edu See parent class for more information.
Method signatures and docstrings:
- def check(self): Checks parameters and paths
- def submit(self, *args, **kwargs): Submits job
<|skeleton|>
c... | 1c3be107a970c1bbbe0f7816f6a3df1fd7e27246 | <|skeleton|>
class tiger_lg:
"""Specially designed system interface for tiger.princeton.edu See parent class for more information."""
def check(self):
"""Checks parameters and paths"""
<|body_0|>
def submit(self, *args, **kwargs):
"""Submits job"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class tiger_lg:
"""Specially designed system interface for tiger.princeton.edu See parent class for more information."""
def check(self):
"""Checks parameters and paths"""
if 'WORKDIR' not in PATH:
setattr(PATH, 'WORKDIR', abspath('.'))
if 'SCRATCH' not in PATH:
... | the_stack_v2_python_sparse | seisflows/system/tiger_lg.py | lhuang-pvamu/seisflows | train | 2 |
8134be26b083bea97f14a1f9d00d6aa12556a004 | [
"super(PositionalEncoding, self).__init__()\nself.d_model = d_model\nself.reverse = reverse\nself.xscale = math.sqrt(self.d_model)\nself.dropout = torch.nn.Dropout(p=dropout_rate)\nself.pe = None\nself.extend_pe(torch.tensor(0.0).expand(1, max_len))\nself._register_load_state_dict_pre_hook(_pre_hook)",
"if self.p... | <|body_start_0|>
super(PositionalEncoding, self).__init__()
self.d_model = d_model
self.reverse = reverse
self.xscale = math.sqrt(self.d_model)
self.dropout = torch.nn.Dropout(p=dropout_rate)
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
... | Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. | PositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position."""
def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False):
... | stack_v2_sparse_classes_75kplus_train_008954 | 37,737 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False)"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, x)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_021260 | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position.
Method signatures and docstrings:
- def __i... | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position.
Method signatures and docstrings:
- def __i... | 31d50b1ea1dea92f4182c5b2b6fe9fe4c981ae39 | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position."""
def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PositionalEncoding:
"""Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position."""
def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False):
"""Const... | the_stack_v2_python_sparse | SVS/model/layers/conformer_related.py | SJTMusicTeam/SVS_system | train | 85 |
9d38ca9868c14c220cca3d9958d4c9ff3a6a87af | [
"super().__init__()\nself.sem_params = sem_params\nself.ins_params = ins_params\nself.num_iterations = num_iterations\nself._softmax = torch.nn.Softmax(dim=0)\nself.stuff_labels = stuff_labels\nself.thing_labels = thing_labels\nself.param_sem_spatial_weights = nn.Parameter(sem_params.spatial_ker_weight * torch.ones... | <|body_start_0|>
super().__init__()
self.sem_params = sem_params
self.ins_params = ins_params
self.num_iterations = num_iterations
self._softmax = torch.nn.Softmax(dim=0)
self.stuff_labels = stuff_labels
self.thing_labels = thing_labels
self.param_sem_spat... | PyTorch implementation of Bipartite CRF | PyTorchBCRF | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyTorchBCRF:
"""PyTorch implementation of Bipartite CRF"""
def __init__(self, sem_params: DenseCRFParams, ins_params: DenseCRFParams, num_labels: int, stuff_labels: Iterable[int], thing_labels: Iterable[int], num_iterations: int):
"""Create a new instance Args: sem_params: Semantic C... | stack_v2_sparse_classes_75kplus_train_008955 | 6,913 | permissive | [
{
"docstring": "Create a new instance Args: sem_params: Semantic CRF parameters ins_params: Instance CRF parameters num_labels: Number of (semantic) labels in the dataset stuff_labels: Stuff label IDs in the dataset num_iterations: Number of mean-field iterations",
"name": "__init__",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_038487 | Implement the Python class `PyTorchBCRF` described below.
Class description:
PyTorch implementation of Bipartite CRF
Method signatures and docstrings:
- def __init__(self, sem_params: DenseCRFParams, ins_params: DenseCRFParams, num_labels: int, stuff_labels: Iterable[int], thing_labels: Iterable[int], num_iterations:... | Implement the Python class `PyTorchBCRF` described below.
Class description:
PyTorch implementation of Bipartite CRF
Method signatures and docstrings:
- def __init__(self, sem_params: DenseCRFParams, ins_params: DenseCRFParams, num_labels: int, stuff_labels: Iterable[int], thing_labels: Iterable[int], num_iterations:... | 7cbdd8a77e54f09cca1addd66c7359e17501b9e4 | <|skeleton|>
class PyTorchBCRF:
"""PyTorch implementation of Bipartite CRF"""
def __init__(self, sem_params: DenseCRFParams, ins_params: DenseCRFParams, num_labels: int, stuff_labels: Iterable[int], thing_labels: Iterable[int], num_iterations: int):
"""Create a new instance Args: sem_params: Semantic C... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PyTorchBCRF:
"""PyTorch implementation of Bipartite CRF"""
def __init__(self, sem_params: DenseCRFParams, ins_params: DenseCRFParams, num_labels: int, stuff_labels: Iterable[int], thing_labels: Iterable[int], num_iterations: int):
"""Create a new instance Args: sem_params: Semantic CRF parameters... | the_stack_v2_python_sparse | pytorch_permuto/pytorch_permuto/pytorch_bcrf.py | repo-collection/bcrf-detectron | train | 0 |
5c57aae2760fa791fe3a9cbc28a6f3ded9639c45 | [
"tile = tiles[2]\nmove = self._first_legal_posn_on_vertical_side(MIN_BOARD_COORDINATE, range(MIN_BOARD_COORDINATE + 1, MAX_BOARD_COORDINATE), board_state, tile)\nif not move:\n move = self._first_legal_posn_on_horizontal_side(MAX_BOARD_COORDINATE, range(MIN_BOARD_COORDINATE, MAX_BOARD_COORDINATE + 1), board_stat... | <|body_start_0|>
tile = tiles[2]
move = self._first_legal_posn_on_vertical_side(MIN_BOARD_COORDINATE, range(MIN_BOARD_COORDINATE + 1, MAX_BOARD_COORDINATE), board_state, tile)
if not move:
move = self._first_legal_posn_on_horizontal_side(MAX_BOARD_COORDINATE, range(MIN_BOARD_COORDINA... | Implements a simple deterministic strategy for Tsuro games as described in Assignment 6 | ThirdS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThirdS:
"""Implements a simple deterministic strategy for Tsuro games as described in Assignment 6"""
def generate_first_move(self, tiles: List[Tile], board_state: BoardState) -> Result[Tuple[BoardPosition, Tile, PortID]]:
"""Generate the first move by choosing from the given list of... | stack_v2_sparse_classes_75kplus_train_008956 | 7,517 | no_license | [
{
"docstring": "Generate the first move by choosing from the given list of 3 tiles. Returns the move along with the port that the player's token should be placed on. `set_color` and `set_rule_checker` will be called prior to this method. This strategy just chooses the first valid move checking positions counter... | 6 | null | Implement the Python class `ThirdS` described below.
Class description:
Implements a simple deterministic strategy for Tsuro games as described in Assignment 6
Method signatures and docstrings:
- def generate_first_move(self, tiles: List[Tile], board_state: BoardState) -> Result[Tuple[BoardPosition, Tile, PortID]]: G... | Implement the Python class `ThirdS` described below.
Class description:
Implements a simple deterministic strategy for Tsuro games as described in Assignment 6
Method signatures and docstrings:
- def generate_first_move(self, tiles: List[Tile], board_state: BoardState) -> Result[Tuple[BoardPosition, Tile, PortID]]: G... | 842de3ad7f3eb869ed1e8cfcf94033ccce38baf7 | <|skeleton|>
class ThirdS:
"""Implements a simple deterministic strategy for Tsuro games as described in Assignment 6"""
def generate_first_move(self, tiles: List[Tile], board_state: BoardState) -> Result[Tuple[BoardPosition, Tile, PortID]]:
"""Generate the first move by choosing from the given list of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThirdS:
"""Implements a simple deterministic strategy for Tsuro games as described in Assignment 6"""
def generate_first_move(self, tiles: List[Tile], board_state: BoardState) -> Result[Tuple[BoardPosition, Tile, PortID]]:
"""Generate the first move by choosing from the given list of 3 tiles. Ret... | the_stack_v2_python_sparse | Player/third_s.py | feliciazhang/tsuro | train | 0 |
7ef7c4cab1fd6df662d7203bf806292f5c6bf103 | [
"search_space_size = len(search_space)\nstart = 0\nend = search_space_size - 1\nwhile start <= end:\n if search_space[start] <= search_space[end]:\n return start\n mid = start + (end - start) // 2\n next = (mid + 1) % search_space_size\n previous = (mid + search_space_size - 1) % search_space_siz... | <|body_start_0|>
search_space_size = len(search_space)
start = 0
end = search_space_size - 1
while start <= end:
if search_space[start] <= search_space[end]:
return start
mid = start + (end - start) // 2
next = (mid + 1) % search_space_... | This class is a python implementation of the problem discussed in the following videos by mycodeschool: 1) No. of rotations - https://www.youtube.com/watch?v=4qjprDkJrjY 2) Search element in circularly rotated array - https://www.youtube.com/watch?v=uufaK2uLnSI :Authors: pranaychandekar | CircularRotatedSortedArray | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CircularRotatedSortedArray:
"""This class is a python implementation of the problem discussed in the following videos by mycodeschool: 1) No. of rotations - https://www.youtube.com/watch?v=4qjprDkJrjY 2) Search element in circularly rotated array - https://www.youtube.com/watch?v=uufaK2uLnSI :Aut... | stack_v2_sparse_classes_75kplus_train_008957 | 3,450 | permissive | [
{
"docstring": "This method performs a binary search on the sorted search space to find the number of circular rotations performed on the array. :param search_space: The sorted list of elements on which target needs to be searched. :type search_space: list :return: The index of the target. :rtype: int",
"na... | 2 | stack_v2_sparse_classes_30k_train_005745 | Implement the Python class `CircularRotatedSortedArray` described below.
Class description:
This class is a python implementation of the problem discussed in the following videos by mycodeschool: 1) No. of rotations - https://www.youtube.com/watch?v=4qjprDkJrjY 2) Search element in circularly rotated array - https://w... | Implement the Python class `CircularRotatedSortedArray` described below.
Class description:
This class is a python implementation of the problem discussed in the following videos by mycodeschool: 1) No. of rotations - https://www.youtube.com/watch?v=4qjprDkJrjY 2) Search element in circularly rotated array - https://w... | 355a72ceb3537e8ec242b6aea4b214deac4432d8 | <|skeleton|>
class CircularRotatedSortedArray:
"""This class is a python implementation of the problem discussed in the following videos by mycodeschool: 1) No. of rotations - https://www.youtube.com/watch?v=4qjprDkJrjY 2) Search element in circularly rotated array - https://www.youtube.com/watch?v=uufaK2uLnSI :Aut... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CircularRotatedSortedArray:
"""This class is a python implementation of the problem discussed in the following videos by mycodeschool: 1) No. of rotations - https://www.youtube.com/watch?v=4qjprDkJrjY 2) Search element in circularly rotated array - https://www.youtube.com/watch?v=uufaK2uLnSI :Authors: pranayc... | the_stack_v2_python_sparse | src/binary_search/circularly_rotated_array.py | pranaychandekar/dsa | train | 5 |
8290f7c7dc8710df3fbb168b4e5bbf78b37d54cb | [
"control_palette = control_instance.palette()\ncontrol_value = control_instance.value()\ncolor = QtCore.Qt.white\nred = QtGui.QColor(255, 220, 220)\nyellow = QtGui.QColor(255, 255, 200)\nis_valid = False\nif control_value in (b'', None, traits.Undefined):\n if control_instance.optional:\n color = yellow\n... | <|body_start_0|>
control_palette = control_instance.palette()
control_value = control_instance.value()
color = QtCore.Qt.white
red = QtGui.QColor(255, 220, 220)
yellow = QtGui.QColor(255, 255, 200)
is_valid = False
if control_value in (b'', None, traits.Undefined)... | Control to enter a bytes string. | BytesControlWidget | [
"CECILL-B"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BytesControlWidget:
"""Control to enter a bytes string."""
def is_valid(control_instance, *args, **kwargs):
"""Method to check if the new control value is correct. If the new entered value is not correct, the backroung control color will be red. Parameters ---------- control_instance... | stack_v2_sparse_classes_75kplus_train_008958 | 4,616 | permissive | [
{
"docstring": "Method to check if the new control value is correct. If the new entered value is not correct, the backroung control color will be red. Parameters ---------- control_instance: QLineEdit (mandatory) the control widget we want to validate Returns ------- out: bool True if the control value is valid... | 2 | stack_v2_sparse_classes_30k_train_001254 | Implement the Python class `BytesControlWidget` described below.
Class description:
Control to enter a bytes string.
Method signatures and docstrings:
- def is_valid(control_instance, *args, **kwargs): Method to check if the new control value is correct. If the new entered value is not correct, the backroung control ... | Implement the Python class `BytesControlWidget` described below.
Class description:
Control to enter a bytes string.
Method signatures and docstrings:
- def is_valid(control_instance, *args, **kwargs): Method to check if the new control value is correct. If the new entered value is not correct, the backroung control ... | 779e254098b183eb312eb589268c474dd65c5679 | <|skeleton|>
class BytesControlWidget:
"""Control to enter a bytes string."""
def is_valid(control_instance, *args, **kwargs):
"""Method to check if the new control value is correct. If the new entered value is not correct, the backroung control color will be red. Parameters ---------- control_instance... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BytesControlWidget:
"""Control to enter a bytes string."""
def is_valid(control_instance, *args, **kwargs):
"""Method to check if the new control value is correct. If the new entered value is not correct, the backroung control color will be red. Parameters ---------- control_instance: QLineEdit (... | the_stack_v2_python_sparse | python/soma/qt_gui/controls/Bytes.py | populse/soma-base | train | 0 |
37b7b25d91417ed99dc8b6b5fa6636c08d6fc391 | [
"super(PIFuhd_Surface_Head, self).__init__()\nself.name = 'PIFuhd_Surface_Head'\nif last_op == 'sigmoid':\n self.last_op = nn.Sigmoid()\nelse:\n raise NotImplementedError('only sigmoid function could be used in terms of sigmoid')\nself.filters = nn.ModuleList()\nself.norms = nn.ModuleList()\nself.merge_layer ... | <|body_start_0|>
super(PIFuhd_Surface_Head, self).__init__()
self.name = 'PIFuhd_Surface_Head'
if last_op == 'sigmoid':
self.last_op = nn.Sigmoid()
else:
raise NotImplementedError('only sigmoid function could be used in terms of sigmoid')
self.filters = nn... | MLP: aims at learn iso-surface function Implicit function where 0->outside, 1-> inside therefore, we define 0.5 is iso-surface | PIFuhd_Surface_Head | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PIFuhd_Surface_Head:
"""MLP: aims at learn iso-surface function Implicit function where 0->outside, 1-> inside therefore, we define 0.5 is iso-surface"""
def __init__(self, filter_channels, merge_layer=0, res_layers=[], norm='group', last_op=None):
"""Parameters: filter_channels: Lis... | stack_v2_sparse_classes_75kplus_train_008959 | 3,326 | permissive | [
{
"docstring": "Parameters: filter_channels: List mlp layers default [257, 1024, 512, 256, 128, 1] merge_layer: it means which layer you want to employ in fine PIFu model res_layers: whether you wana employ residual block ? Default [2,3,4] norm: use group normalization or not last_op: what kind of operator you ... | 2 | stack_v2_sparse_classes_30k_train_004895 | Implement the Python class `PIFuhd_Surface_Head` described below.
Class description:
MLP: aims at learn iso-surface function Implicit function where 0->outside, 1-> inside therefore, we define 0.5 is iso-surface
Method signatures and docstrings:
- def __init__(self, filter_channels, merge_layer=0, res_layers=[], norm... | Implement the Python class `PIFuhd_Surface_Head` described below.
Class description:
MLP: aims at learn iso-surface function Implicit function where 0->outside, 1-> inside therefore, we define 0.5 is iso-surface
Method signatures and docstrings:
- def __init__(self, filter_channels, merge_layer=0, res_layers=[], norm... | 3a66b647bcf5591e818af62735e64a93c4aaef85 | <|skeleton|>
class PIFuhd_Surface_Head:
"""MLP: aims at learn iso-surface function Implicit function where 0->outside, 1-> inside therefore, we define 0.5 is iso-surface"""
def __init__(self, filter_channels, merge_layer=0, res_layers=[], norm='group', last_op=None):
"""Parameters: filter_channels: Lis... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PIFuhd_Surface_Head:
"""MLP: aims at learn iso-surface function Implicit function where 0->outside, 1-> inside therefore, we define 0.5 is iso-surface"""
def __init__(self, filter_channels, merge_layer=0, res_layers=[], norm='group', last_op=None):
"""Parameters: filter_channels: List mlp layers ... | the_stack_v2_python_sparse | engineer/models/heads/PIFuhd_Surface_head.py | yukangcao/Open-PIFuhd | train | 0 |
ef74079c0ce3f76a35b637bed9a010c9d630d612 | [
"row, col = (-1, -1)\nfor i in range(len(matrix)):\n for j in range(len(matrix[i])):\n if matrix[i][j] == 0:\n row, col = (i, j)\nif row == -1 or col == -1:\n return\nfor i in range(len(matrix)):\n for j in range(len(matrix[i])):\n if matrix[i][j] == 0:\n matrix[i][col] ... | <|body_start_0|>
row, col = (-1, -1)
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == 0:
row, col = (i, j)
if row == -1 or col == -1:
return
for i in range(len(matrix)):
for j in range(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes_v2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify mat... | stack_v2_sparse_classes_75kplus_train_008960 | 2,791 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instea... | 2 | stack_v2_sparse_classes_30k_train_006219 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes_v2(self, matrix): :type matrix: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes_v2(self, matrix): :type matrix: Li... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes_v2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify mat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
row, col = (-1, -1)
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == 0:
... | the_stack_v2_python_sparse | src/lt_73.py | oxhead/CodingYourWay | train | 0 | |
4db98fa874688afb81c2b08f6a7f20443f6768c3 | [
"try:\n return Category.objects.get(pk=pk)\nexcept Category.DoesNotExist:\n raise Http404",
"category = self.get_object(pk)\nserializer = CategorySerializers(category)\nreturn Response({'serializer': serializer, 'category': category})"
] | <|body_start_0|>
try:
return Category.objects.get(pk=pk)
except Category.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
category = self.get_object(pk)
serializer = CategorySerializers(category)
return Response({'serializer': serializer, 'cate... | Details of the particular category is displayed | CategoryDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryDetail:
"""Details of the particular category is displayed"""
def get_object(self, pk):
"""get the category object of the given pk."""
<|body_0|>
def get(self, request, pk, format=None):
"""renders the categoryDetail html file."""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus_train_008961 | 7,364 | no_license | [
{
"docstring": "get the category object of the given pk.",
"name": "get_object",
"signature": "def get_object(self, pk)"
},
{
"docstring": "renders the categoryDetail html file.",
"name": "get",
"signature": "def get(self, request, pk, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024021 | Implement the Python class `CategoryDetail` described below.
Class description:
Details of the particular category is displayed
Method signatures and docstrings:
- def get_object(self, pk): get the category object of the given pk.
- def get(self, request, pk, format=None): renders the categoryDetail html file. | Implement the Python class `CategoryDetail` described below.
Class description:
Details of the particular category is displayed
Method signatures and docstrings:
- def get_object(self, pk): get the category object of the given pk.
- def get(self, request, pk, format=None): renders the categoryDetail html file.
<|ske... | c2a279e4ee48374396f80884d6514fa16d2c5b06 | <|skeleton|>
class CategoryDetail:
"""Details of the particular category is displayed"""
def get_object(self, pk):
"""get the category object of the given pk."""
<|body_0|>
def get(self, request, pk, format=None):
"""renders the categoryDetail html file."""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CategoryDetail:
"""Details of the particular category is displayed"""
def get_object(self, pk):
"""get the category object of the given pk."""
try:
return Category.objects.get(pk=pk)
except Category.DoesNotExist:
raise Http404
def get(self, request, pk... | the_stack_v2_python_sparse | ecommerce/ecom_module/views.py | merishabh/DjangoTraining | train | 0 |
050a01071cf805dc052a57619e0ee47c7fb67af8 | [
"nRows = self.rowCount()\nnCols = self.columnCount()\nrowTitles = []\nrowData = []\nfor i in range(nRows):\n rowTitles.append(self.verticalHeaderItem(i).text())\n data = []\n for j in range(nCols):\n data.append(self.item(i, j).text())\n rowData.append(data)\nreturn {title: data for title, data i... | <|body_start_0|>
nRows = self.rowCount()
nCols = self.columnCount()
rowTitles = []
rowData = []
for i in range(nRows):
rowTitles.append(self.verticalHeaderItem(i).text())
data = []
for j in range(nCols):
data.append(self.item(i,... | Table | TableWidget | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TableWidget:
"""Table"""
def getData(self):
"""Get the data from the table."""
<|body_0|>
def getHorizontalHeaders(self):
"""Get the headers from the table."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nRows = self.rowCount()
nCols = ... | stack_v2_sparse_classes_75kplus_train_008962 | 3,196 | permissive | [
{
"docstring": "Get the data from the table.",
"name": "getData",
"signature": "def getData(self)"
},
{
"docstring": "Get the headers from the table.",
"name": "getHorizontalHeaders",
"signature": "def getHorizontalHeaders(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025210 | Implement the Python class `TableWidget` described below.
Class description:
Table
Method signatures and docstrings:
- def getData(self): Get the data from the table.
- def getHorizontalHeaders(self): Get the headers from the table. | Implement the Python class `TableWidget` described below.
Class description:
Table
Method signatures and docstrings:
- def getData(self): Get the data from the table.
- def getHorizontalHeaders(self): Get the headers from the table.
<|skeleton|>
class TableWidget:
"""Table"""
def getData(self):
"""G... | fa6363b38b3e6cfbb33ef458ce499459fb4145c5 | <|skeleton|>
class TableWidget:
"""Table"""
def getData(self):
"""Get the data from the table."""
<|body_0|>
def getHorizontalHeaders(self):
"""Get the headers from the table."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TableWidget:
"""Table"""
def getData(self):
"""Get the data from the table."""
nRows = self.rowCount()
nCols = self.columnCount()
rowTitles = []
rowData = []
for i in range(nRows):
rowTitles.append(self.verticalHeaderItem(i).text())
... | the_stack_v2_python_sparse | qcodes_measurements/plot/local/UIItems.py | QNLSydney/qcodes_measurements | train | 2 |
b65ba5373553057638cf900f5631fd94c98898b0 | [
"params = kwargs.get('params')\nheaders = kwargs.get('headers')\ntry:\n reqult = requests.get(url, params=params, headers=headers)\n return\nexcept Exception as e:\n print('get请求错误: %s' % e)",
"params = kwargs.get('params')\ndata = kwargs.get('data')\njson = kwargs.get('json')\ntry:\n reqult = request... | <|body_start_0|>
params = kwargs.get('params')
headers = kwargs.get('headers')
try:
reqult = requests.get(url, params=params, headers=headers)
return
except Exception as e:
print('get请求错误: %s' % e)
<|end_body_0|>
<|body_start_1|>
params = kwar... | ReuquestHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReuquestHandler:
def get(self, url, **kwargs):
"""封装get方法"""
<|body_0|>
def post(self, url, **kwargs):
"""封装post请求方法"""
<|body_1|>
def run_man(self, method, **kwargs):
"""判断请求类型 :param method:请求接口类型 :param kwargs:选填参数 :return:接口返回内容"""
<|... | stack_v2_sparse_classes_75kplus_train_008963 | 2,512 | no_license | [
{
"docstring": "封装get方法",
"name": "get",
"signature": "def get(self, url, **kwargs)"
},
{
"docstring": "封装post请求方法",
"name": "post",
"signature": "def post(self, url, **kwargs)"
},
{
"docstring": "判断请求类型 :param method:请求接口类型 :param kwargs:选填参数 :return:接口返回内容",
"name": "run_ma... | 3 | stack_v2_sparse_classes_30k_train_004523 | Implement the Python class `ReuquestHandler` described below.
Class description:
Implement the ReuquestHandler class.
Method signatures and docstrings:
- def get(self, url, **kwargs): 封装get方法
- def post(self, url, **kwargs): 封装post请求方法
- def run_man(self, method, **kwargs): 判断请求类型 :param method:请求接口类型 :param kwargs:选... | Implement the Python class `ReuquestHandler` described below.
Class description:
Implement the ReuquestHandler class.
Method signatures and docstrings:
- def get(self, url, **kwargs): 封装get方法
- def post(self, url, **kwargs): 封装post请求方法
- def run_man(self, method, **kwargs): 判断请求类型 :param method:请求接口类型 :param kwargs:选... | 876bea3d771695319159dbb0ccff099301256829 | <|skeleton|>
class ReuquestHandler:
def get(self, url, **kwargs):
"""封装get方法"""
<|body_0|>
def post(self, url, **kwargs):
"""封装post请求方法"""
<|body_1|>
def run_man(self, method, **kwargs):
"""判断请求类型 :param method:请求接口类型 :param kwargs:选填参数 :return:接口返回内容"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReuquestHandler:
def get(self, url, **kwargs):
"""封装get方法"""
params = kwargs.get('params')
headers = kwargs.get('headers')
try:
reqult = requests.get(url, params=params, headers=headers)
return
except Exception as e:
print('get请求错误: %... | the_stack_v2_python_sparse | utils/httpHandler.py | luomxcc/exercise_two-master | train | 0 | |
86fb1e3951d579b6b2023346d0cc8b054f5586b5 | [
"if not root or root == p or root == q:\n return root\nleft = self.lowestCommonAncestor(root.left, p, q)\nright = self.lowestCommonAncestor(root.right, p, q)\nif not left:\n return right\nif not right:\n return left\nreturn root",
"if not root or root == p or root == q:\n return root\nleft = self.lowe... | <|body_start_0|>
if not root or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if not left:
return right
if not right:
return left
return root
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点root.left 和右子节点 root.right都不是p和q的公共祖先,则称root是“最近的公共祖先” 根据以上定义,若root是p,q的最近公共祖先,则只可能为以下情况之一: 1,p和q ... | stack_v2_sparse_classes_75kplus_train_008964 | 4,599 | no_license | [
{
"docstring": "祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点root.left 和右子节点 root.right都不是p和q的公共祖先,则称root是“最近的公共祖先” 根据以上定义,若root是p,q的最近公共祖先,则只可能为以下情况之一: 1,p和q 在root的子树中,且分列root的异侧,(即分别在左,右子树中) 2,p=root,且q在root的左子树或右子树中 3,q=root,且p在root的左子树或右子树中 考虑通过递归对二叉树进行后续遍历,当遇到节点p和q时返回,... | 2 | stack_v2_sparse_classes_30k_train_033313 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点r... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点root.left 和右子节点 root.right都不是p和q的公共祖先,则称root是“最近的公共祖先” 根据以上定义,若root是p,q的最近公共祖先,则只可能为以下情况之一: 1,p和q ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点root.left 和右子节点 root.right都不是p和q的公共祖先,则称root是“最近的公共祖先” 根据以上定义,若root是p,q的最近公共祖先,则只可能为以下情况之一: 1,p和q 在root的子树中,且分列r... | the_stack_v2_python_sparse | 剑指offer/PythonVersion/68_2_二叉树的最近公共祖先.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
5703af9b2848664babd7923497692046257bcfaf | [
"u = self.get_user(ins, *param, **kws)\nif not u:\n return False\nreturn True",
"self.controller = ins\nurl = self.authenticate_redirect()\nif not url:\n raise ValueError(\"authenticate_redirect() didn't return url.\")\nins.redirect(url)",
"key = ins.cookies.get(OAUTH_ACCESS_TOKEN_COOKIE, '')\nif key:\n ... | <|body_start_0|>
u = self.get_user(ins, *param, **kws)
if not u:
return False
return True
<|end_body_0|>
<|body_start_1|>
self.controller = ins
url = self.authenticate_redirect()
if not url:
raise ValueError("authenticate_redirect() didn't return ... | A class to performs authentication via twitter oauth authentication. When you want to use twitter authentication in aha application, you may set auth_obj in configuration in config.py like following: from plugin.twitteroauth.twitter_auth import TwitterOAuth config.auth_obj = TwitterOAuth You may also set consume key an... | TwitterOAuth | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwitterOAuth:
"""A class to performs authentication via twitter oauth authentication. When you want to use twitter authentication in aha application, you may set auth_obj in configuration in config.py like following: from plugin.twitteroauth.twitter_auth import TwitterOAuth config.auth_obj = Twit... | stack_v2_sparse_classes_75kplus_train_008965 | 3,766 | permissive | [
{
"docstring": "A method to perform authentication, or to check if the authentication has been performed. It returns true on success, false on failure. :param ins : a controller instance. :param param : parameters to be passed to authentication function. :param kws : keyword arguments to be passed to authentica... | 5 | stack_v2_sparse_classes_30k_train_041091 | Implement the Python class `TwitterOAuth` described below.
Class description:
A class to performs authentication via twitter oauth authentication. When you want to use twitter authentication in aha application, you may set auth_obj in configuration in config.py like following: from plugin.twitteroauth.twitter_auth imp... | Implement the Python class `TwitterOAuth` described below.
Class description:
A class to performs authentication via twitter oauth authentication. When you want to use twitter authentication in aha application, you may set auth_obj in configuration in config.py like following: from plugin.twitteroauth.twitter_auth imp... | e1209f7d44d1c59ff9d373b7d89d414f31a9c28b | <|skeleton|>
class TwitterOAuth:
"""A class to performs authentication via twitter oauth authentication. When you want to use twitter authentication in aha application, you may set auth_obj in configuration in config.py like following: from plugin.twitteroauth.twitter_auth import TwitterOAuth config.auth_obj = Twit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwitterOAuth:
"""A class to performs authentication via twitter oauth authentication. When you want to use twitter authentication in aha application, you may set auth_obj in configuration in config.py like following: from plugin.twitteroauth.twitter_auth import TwitterOAuth config.auth_obj = TwitterOAuth You ... | the_stack_v2_python_sparse | plugins/aha.plugin.twitteroauth/twitteroauth/twitter_auth.py | Letractively/aha-gae | train | 0 |
4f5868ddf3175f4015ed64fe5d99e5776734f617 | [
"self.assertEqual(comp.embryo_cat_variables(identifier(33, False, True, 'NY'))[0], 'FshNDCycle')\nself.assertEqual(comp.embryo_cat_variables(identifier(33, False, True, 'NY'))[6], 'FshNDLvBirths_TransRate')\nself.assertEqual(comp.embryo_cat_variables(identifier(25, True, True, 'NY'))[0], 'FshDnrTotCycles')\nself.as... | <|body_start_0|>
self.assertEqual(comp.embryo_cat_variables(identifier(33, False, True, 'NY'))[0], 'FshNDCycle')
self.assertEqual(comp.embryo_cat_variables(identifier(33, False, True, 'NY'))[6], 'FshNDLvBirths_TransRate')
self.assertEqual(comp.embryo_cat_variables(identifier(25, True, True, 'NY'... | Test2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test2:
def test_variables_to_plot(self):
"""Check whether correct variables are plotter per specified user profile"""
<|body_0|>
def test_other_clinics_set1(self):
"""Check whether correct set of clinics gets selected by other_clinics_set function"""
<|body_1... | stack_v2_sparse_classes_75kplus_train_008966 | 8,537 | no_license | [
{
"docstring": "Check whether correct variables are plotter per specified user profile",
"name": "test_variables_to_plot",
"signature": "def test_variables_to_plot(self)"
},
{
"docstring": "Check whether correct set of clinics gets selected by other_clinics_set function",
"name": "test_other... | 4 | null | Implement the Python class `Test2` described below.
Class description:
Implement the Test2 class.
Method signatures and docstrings:
- def test_variables_to_plot(self): Check whether correct variables are plotter per specified user profile
- def test_other_clinics_set1(self): Check whether correct set of clinics gets ... | Implement the Python class `Test2` described below.
Class description:
Implement the Test2 class.
Method signatures and docstrings:
- def test_variables_to_plot(self): Check whether correct variables are plotter per specified user profile
- def test_other_clinics_set1(self): Check whether correct set of clinics gets ... | dc9185cbc5e65650d985ebecf877a157c8c19a13 | <|skeleton|>
class Test2:
def test_variables_to_plot(self):
"""Check whether correct variables are plotter per specified user profile"""
<|body_0|>
def test_other_clinics_set1(self):
"""Check whether correct set of clinics gets selected by other_clinics_set function"""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test2:
def test_variables_to_plot(self):
"""Check whether correct variables are plotter per specified user profile"""
self.assertEqual(comp.embryo_cat_variables(identifier(33, False, True, 'NY'))[0], 'FshNDCycle')
self.assertEqual(comp.embryo_cat_variables(identifier(33, False, True, '... | the_stack_v2_python_sparse | IVF_Analysis/Tests.py | ds-ga-1007/final_project | train | 0 | |
11cee98590d0d7d8bc1c574c889af8bd27f720fd | [
"self.xknx = xknx\nself.data_secure: DataSecure | None = None\nself._l_data_confirmation_event = asyncio.Event()",
"if keyring is None:\n self.data_secure = None\nelse:\n self.data_secure = DataSecure.init_from_keyring(keyring)",
"cemi_data = CEMILData.init_from_telegram(telegram=telegram, src_addr=self.x... | <|body_start_0|>
self.xknx = xknx
self.data_secure: DataSecure | None = None
self._l_data_confirmation_event = asyncio.Event()
<|end_body_0|>
<|body_start_1|>
if keyring is None:
self.data_secure = None
else:
self.data_secure = DataSecure.init_from_keyrin... | Class for handling CEMI frames from/to the TelegramQueue. | CEMIHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CEMIHandler:
"""Class for handling CEMI frames from/to the TelegramQueue."""
def __init__(self, xknx: XKNX) -> None:
"""Initialize CEMIHandler class."""
<|body_0|>
def data_secure_init(self, keyring: Keyring | None) -> None:
"""Initialize DataSecure."""
<... | stack_v2_sparse_classes_75kplus_train_008967 | 5,636 | permissive | [
{
"docstring": "Initialize CEMIHandler class.",
"name": "__init__",
"signature": "def __init__(self, xknx: XKNX) -> None"
},
{
"docstring": "Initialize DataSecure.",
"name": "data_secure_init",
"signature": "def data_secure_init(self, keyring: Keyring | None) -> None"
},
{
"docst... | 6 | stack_v2_sparse_classes_30k_train_054497 | Implement the Python class `CEMIHandler` described below.
Class description:
Class for handling CEMI frames from/to the TelegramQueue.
Method signatures and docstrings:
- def __init__(self, xknx: XKNX) -> None: Initialize CEMIHandler class.
- def data_secure_init(self, keyring: Keyring | None) -> None: Initialize Dat... | Implement the Python class `CEMIHandler` described below.
Class description:
Class for handling CEMI frames from/to the TelegramQueue.
Method signatures and docstrings:
- def __init__(self, xknx: XKNX) -> None: Initialize CEMIHandler class.
- def data_secure_init(self, keyring: Keyring | None) -> None: Initialize Dat... | 48d4e31365c15e632b275f0d129cd9f2b2b5717d | <|skeleton|>
class CEMIHandler:
"""Class for handling CEMI frames from/to the TelegramQueue."""
def __init__(self, xknx: XKNX) -> None:
"""Initialize CEMIHandler class."""
<|body_0|>
def data_secure_init(self, keyring: Keyring | None) -> None:
"""Initialize DataSecure."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CEMIHandler:
"""Class for handling CEMI frames from/to the TelegramQueue."""
def __init__(self, xknx: XKNX) -> None:
"""Initialize CEMIHandler class."""
self.xknx = xknx
self.data_secure: DataSecure | None = None
self._l_data_confirmation_event = asyncio.Event()
def d... | the_stack_v2_python_sparse | xknx/cemi/cemi_handler.py | XKNX/xknx | train | 248 |
c9950d5f65369bee186b501cdc67df4a5e18a41d | [
"super().__init__()\nthreading.Thread.__init__(self)\nself.mediator = mediator\nself.logger.debug('Initialized. Assuming %3d max threads', max_workers)\nself.parser = Parser()\nself.db = DatabaseManager()\nself.parse_worker = ParserWorker(self.mediator, self, self.parser)\nself.crawl_worker = CrawlerWorker(self.med... | <|body_start_0|>
super().__init__()
threading.Thread.__init__(self)
self.mediator = mediator
self.logger.debug('Initialized. Assuming %3d max threads', max_workers)
self.parser = Parser()
self.db = DatabaseManager()
self.parse_worker = ParserWorker(self.mediator, ... | Worker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Worker:
def __init__(self, mediator: Mediator, max_workers: int):
"""Default constructor :type mediator: Mediator Design Pattern :type max_workers: Max workers"""
<|body_0|>
def run(self) -> None:
"""Default overriden thread run method"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_008968 | 1,314 | no_license | [
{
"docstring": "Default constructor :type mediator: Mediator Design Pattern :type max_workers: Max workers",
"name": "__init__",
"signature": "def __init__(self, mediator: Mediator, max_workers: int)"
},
{
"docstring": "Default overriden thread run method",
"name": "run",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_037355 | Implement the Python class `Worker` described below.
Class description:
Implement the Worker class.
Method signatures and docstrings:
- def __init__(self, mediator: Mediator, max_workers: int): Default constructor :type mediator: Mediator Design Pattern :type max_workers: Max workers
- def run(self) -> None: Default ... | Implement the Python class `Worker` described below.
Class description:
Implement the Worker class.
Method signatures and docstrings:
- def __init__(self, mediator: Mediator, max_workers: int): Default constructor :type mediator: Mediator Design Pattern :type max_workers: Max workers
- def run(self) -> None: Default ... | 0d4f782443046682b02e435cdfa6b2927f97b2ce | <|skeleton|>
class Worker:
def __init__(self, mediator: Mediator, max_workers: int):
"""Default constructor :type mediator: Mediator Design Pattern :type max_workers: Max workers"""
<|body_0|>
def run(self) -> None:
"""Default overriden thread run method"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Worker:
def __init__(self, mediator: Mediator, max_workers: int):
"""Default constructor :type mediator: Mediator Design Pattern :type max_workers: Max workers"""
super().__init__()
threading.Thread.__init__(self)
self.mediator = mediator
self.logger.debug('Initialized.... | the_stack_v2_python_sparse | Thread/worker.py | mszynka/PythonCrawler | train | 1 | |
d9ccbece2541e2627e422c6f4c85442de487d564 | [
"super(attnLoss, self).__init__()\nself.mse_loss = nn.MSELoss(reduction='none')\nself.temperature = temperature\nself.pos_weight = pos_weight\nself.attn_fn = Attention(att_type, x_h_dim=input_dim, y_h_dim=input_dim)\nself.input_dim = input_dim\nself.dim_back = self.input_dim\nself.cat = cat\nif self.cat:\n self.... | <|body_start_0|>
super(attnLoss, self).__init__()
self.mse_loss = nn.MSELoss(reduction='none')
self.temperature = temperature
self.pos_weight = pos_weight
self.attn_fn = Attention(att_type, x_h_dim=input_dim, y_h_dim=input_dim)
self.input_dim = input_dim
self.dim_... | attnLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class attnLoss:
def __init__(self, temperature=1.0, pos_weight=10.0, sim_type='dot', att_type='dot', input_dim=300, cat=True):
"""emb -> lstm lstm -> lstm_attention"""
<|body_0|>
def forward(self, hidden, y_label, input_mask):
"""hidden: batch_size_x * (1 + batch_size_y) *... | stack_v2_sparse_classes_75kplus_train_008969 | 9,041 | no_license | [
{
"docstring": "emb -> lstm lstm -> lstm_attention",
"name": "__init__",
"signature": "def __init__(self, temperature=1.0, pos_weight=10.0, sim_type='dot', att_type='dot', input_dim=300, cat=True)"
},
{
"docstring": "hidden: batch_size_x * (1 + batch_size_y) * max_seq_length * h_dim y_label: bat... | 2 | stack_v2_sparse_classes_30k_val_000100 | Implement the Python class `attnLoss` described below.
Class description:
Implement the attnLoss class.
Method signatures and docstrings:
- def __init__(self, temperature=1.0, pos_weight=10.0, sim_type='dot', att_type='dot', input_dim=300, cat=True): emb -> lstm lstm -> lstm_attention
- def forward(self, hidden, y_la... | Implement the Python class `attnLoss` described below.
Class description:
Implement the attnLoss class.
Method signatures and docstrings:
- def __init__(self, temperature=1.0, pos_weight=10.0, sim_type='dot', att_type='dot', input_dim=300, cat=True): emb -> lstm lstm -> lstm_attention
- def forward(self, hidden, y_la... | afca5410c85e0c30b24b5cd411b241b36e790136 | <|skeleton|>
class attnLoss:
def __init__(self, temperature=1.0, pos_weight=10.0, sim_type='dot', att_type='dot', input_dim=300, cat=True):
"""emb -> lstm lstm -> lstm_attention"""
<|body_0|>
def forward(self, hidden, y_label, input_mask):
"""hidden: batch_size_x * (1 + batch_size_y) *... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class attnLoss:
def __init__(self, temperature=1.0, pos_weight=10.0, sim_type='dot', att_type='dot', input_dim=300, cat=True):
"""emb -> lstm lstm -> lstm_attention"""
super(attnLoss, self).__init__()
self.mse_loss = nn.MSELoss(reduction='none')
self.temperature = temperature
... | the_stack_v2_python_sparse | lstm/model.py | 2212168851/CHIP2020_term_normalization | train | 0 | |
e98fca8960ac4d32c6e5f58d330dff1dc14eaab7 | [
"self.config = utils.get_config()\nsuper().__init__(command_prefix=commands.when_mentioned_or(*self.config['prefixes']), case_insensitive=True, intents=discord.Intents.all())\nself.remove_command('help')\nself.load_extensions()\nself.checks = utils.checks(self)",
"self.load_extension('jishaku')\nfor file in os.li... | <|body_start_0|>
self.config = utils.get_config()
super().__init__(command_prefix=commands.when_mentioned_or(*self.config['prefixes']), case_insensitive=True, intents=discord.Intents.all())
self.remove_command('help')
self.load_extensions()
self.checks = utils.checks(self)
<|end_... | Praestes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Praestes:
def __init__(self):
"""initialize bot object"""
<|body_0|>
def load_extensions(self):
"""at initialization, load all cogs"""
<|body_1|>
async def is_owner(self, user: discord.User):
"""override `is_owner` check so all managers can use `... | stack_v2_sparse_classes_75kplus_train_008970 | 1,648 | no_license | [
{
"docstring": "initialize bot object",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "at initialization, load all cogs",
"name": "load_extensions",
"signature": "def load_extensions(self)"
},
{
"docstring": "override `is_owner` check so all managers can... | 4 | stack_v2_sparse_classes_30k_test_001769 | Implement the Python class `Praestes` described below.
Class description:
Implement the Praestes class.
Method signatures and docstrings:
- def __init__(self): initialize bot object
- def load_extensions(self): at initialization, load all cogs
- async def is_owner(self, user: discord.User): override `is_owner` check ... | Implement the Python class `Praestes` described below.
Class description:
Implement the Praestes class.
Method signatures and docstrings:
- def __init__(self): initialize bot object
- def load_extensions(self): at initialization, load all cogs
- async def is_owner(self, user: discord.User): override `is_owner` check ... | 0009be823805e59391ba8b24ca366983d1b3c234 | <|skeleton|>
class Praestes:
def __init__(self):
"""initialize bot object"""
<|body_0|>
def load_extensions(self):
"""at initialization, load all cogs"""
<|body_1|>
async def is_owner(self, user: discord.User):
"""override `is_owner` check so all managers can use `... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Praestes:
def __init__(self):
"""initialize bot object"""
self.config = utils.get_config()
super().__init__(command_prefix=commands.when_mentioned_or(*self.config['prefixes']), case_insensitive=True, intents=discord.Intents.all())
self.remove_command('help')
self.load_e... | the_stack_v2_python_sparse | main.py | voidoak/Praestes | train | 4 | |
bd780ff7f8f6bab39584cc790bc85361ba2bd0b3 | [
"self.p = p\nself.min_angle = min_angle\nself.max_angle = max_angle",
"if uniform() <= self.p:\n rotation_angle = randint(self.min_angle, self.max_angle)\n return (rotate(img, rotation_angle), rotate(mask, rotation_angle))\nreturn (img, mask)"
] | <|body_start_0|>
self.p = p
self.min_angle = min_angle
self.max_angle = max_angle
<|end_body_0|>
<|body_start_1|>
if uniform() <= self.p:
rotation_angle = randint(self.min_angle, self.max_angle)
return (rotate(img, rotation_angle), rotate(mask, rotation_angle))
... | Random rotation. Represents random rotation which transforms image and segmentation mask. | SegRandomRotation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegRandomRotation:
"""Random rotation. Represents random rotation which transforms image and segmentation mask."""
def __init__(self, p: float=0.5, min_angle: int=-10, max_angle: int=10):
"""Initializes a random rotation. Parameters ---------- p : float Probability with which transfo... | stack_v2_sparse_classes_75kplus_train_008971 | 9,320 | permissive | [
{
"docstring": "Initializes a random rotation. Parameters ---------- p : float Probability with which transformation is applied. min_angle : int Minimal angle bound for rotation (inclusive). max_angle : int Max angle bound for rotation (exclusive).",
"name": "__init__",
"signature": "def __init__(self, ... | 2 | stack_v2_sparse_classes_30k_train_017317 | Implement the Python class `SegRandomRotation` described below.
Class description:
Random rotation. Represents random rotation which transforms image and segmentation mask.
Method signatures and docstrings:
- def __init__(self, p: float=0.5, min_angle: int=-10, max_angle: int=10): Initializes a random rotation. Param... | Implement the Python class `SegRandomRotation` described below.
Class description:
Random rotation. Represents random rotation which transforms image and segmentation mask.
Method signatures and docstrings:
- def __init__(self, p: float=0.5, min_angle: int=-10, max_angle: int=10): Initializes a random rotation. Param... | 7187b78463136eef140893b216d1d311b20c827e | <|skeleton|>
class SegRandomRotation:
"""Random rotation. Represents random rotation which transforms image and segmentation mask."""
def __init__(self, p: float=0.5, min_angle: int=-10, max_angle: int=10):
"""Initializes a random rotation. Parameters ---------- p : float Probability with which transfo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SegRandomRotation:
"""Random rotation. Represents random rotation which transforms image and segmentation mask."""
def __init__(self, p: float=0.5, min_angle: int=-10, max_angle: int=10):
"""Initializes a random rotation. Parameters ---------- p : float Probability with which transformation is ap... | the_stack_v2_python_sparse | carotids/segmentation/transformations.py | kostelansky17/carotids | train | 2 |
9427c82edb38610ba856344cc1f2859207c166b7 | [
"c0 = c1 = c2 = 0\nfor elem in nums:\n if elem == 0:\n c0 += 1\n elif elem == 1:\n c1 += 1\n else:\n c2 += 1\nnums[:c0] = [0] * c0\nnums[c0:c0 + c1] = [1] * c1\nnums[c0 + c1:] = [2] * c2",
"zero, l, two = (0, 0, len(nums) - 1)\nwhile l <= two:\n if nums[l] == 0:\n nums[zero... | <|body_start_0|>
c0 = c1 = c2 = 0
for elem in nums:
if elem == 0:
c0 += 1
elif elem == 1:
c1 += 1
else:
c2 += 1
nums[:c0] = [0] * c0
nums[c0:c0 + c1] = [1] * c1
nums[c0 + c1:] = [2] * c2
<|end_bod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_008972 | 1,453 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "sortColors1",
"signature": "def sortColors1(self, nums: List[int]) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "sortColors2",
"signature": "def sortColors2(sel... | 2 | stack_v2_sparse_classes_30k_train_035350 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors1(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def sortColors2(self, nums: List[int]) -> None: Do not return anything, mo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors1(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def sortColors2(self, nums: List[int]) -> None: Do not return anything, mo... | 466de0bbd64e6783831568ae35495dcc8b41b2b9 | <|skeleton|>
class Solution:
def sortColors1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sortColors1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
c0 = c1 = c2 = 0
for elem in nums:
if elem == 0:
c0 += 1
elif elem == 1:
c1 += 1
else:
... | the_stack_v2_python_sparse | SortColors.py | jwu424/Leetcode | train | 0 | |
f2226f0bea76cf8bde0550a9749e8e1b27991c42 | [
"super(WCEPCalculator, self).__init__(name=name)\nself.num_wceps = num_wceps\nself.warper = bk.CepstralWarper()\nself.channel = channel\nself.window = None\nself.channel_sel = LambdaNode.LambdaNode(lambda x, sel_channel=self.channel: x[:, [sel_channel]], name=name + '.ChannelSel')\nself.audio_fb = FrameBuffer.Frame... | <|body_start_0|>
super(WCEPCalculator, self).__init__(name=name)
self.num_wceps = num_wceps
self.warper = bk.CepstralWarper()
self.channel = channel
self.window = None
self.channel_sel = LambdaNode.LambdaNode(lambda x, sel_channel=self.channel: x[:, [sel_channel]], name=n... | Takes a continuous stream of data as input and outputs a spectrogram. | WCEPCalculator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WCEPCalculator:
"""Takes a continuous stream of data as input and outputs a spectrogram."""
def __init__(self, frame_len_ms, frame_shift_ms, sample_rate, num_wceps=25, channel=0, warm_start=True, name='WCEPCalculator'):
"""Initializes all the nodes used to run-on calculate WCEP featu... | stack_v2_sparse_classes_75kplus_train_008973 | 2,676 | no_license | [
{
"docstring": "Initializes all the nodes used to run-on calculate WCEP features.",
"name": "__init__",
"signature": "def __init__(self, frame_len_ms, frame_shift_ms, sample_rate, num_wceps=25, channel=0, warm_start=True, name='WCEPCalculator')"
},
{
"docstring": "Returns warped MFCCs.",
"na... | 2 | stack_v2_sparse_classes_30k_train_043216 | Implement the Python class `WCEPCalculator` described below.
Class description:
Takes a continuous stream of data as input and outputs a spectrogram.
Method signatures and docstrings:
- def __init__(self, frame_len_ms, frame_shift_ms, sample_rate, num_wceps=25, channel=0, warm_start=True, name='WCEPCalculator'): Init... | Implement the Python class `WCEPCalculator` described below.
Class description:
Takes a continuous stream of data as input and outputs a spectrogram.
Method signatures and docstrings:
- def __init__(self, frame_len_ms, frame_shift_ms, sample_rate, num_wceps=25, channel=0, warm_start=True, name='WCEPCalculator'): Init... | 8766168c07f1fe8ab9743034a7512bc1861388a7 | <|skeleton|>
class WCEPCalculator:
"""Takes a continuous stream of data as input and outputs a spectrogram."""
def __init__(self, frame_len_ms, frame_shift_ms, sample_rate, num_wceps=25, channel=0, warm_start=True, name='WCEPCalculator'):
"""Initializes all the nodes used to run-on calculate WCEP featu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WCEPCalculator:
"""Takes a continuous stream of data as input and outputs a spectrogram."""
def __init__(self, frame_len_ms, frame_shift_ms, sample_rate, num_wceps=25, channel=0, warm_start=True, name='WCEPCalculator'):
"""Initializes all the nodes used to run-on calculate WCEP features."""
... | the_stack_v2_python_sparse | Nodes/WCEPCalculator.py | cognitive-systems-lab/EMG-GUI | train | 0 |
f1a089362b59205a0729fa49c2177c38fd35c9ed | [
"if std_rec.id is None:\n std_rec.id = 'SV'\nelse:\n std_rec.id = std_rec.id.replace(':', '_')\n std_rec.id = std_rec.id.replace(',', ';')\nstd_rec.info['SVTYPE'] = raw_rec.info['SVTYPE']\nstd_rec.info['CHR2'] = std_rec.chrom\nstd_rec.stop = raw_rec.stop\nif std_rec.info['SVTYPE'] == 'DEL':\n strands = ... | <|body_start_0|>
if std_rec.id is None:
std_rec.id = 'SV'
else:
std_rec.id = std_rec.id.replace(':', '_')
std_rec.id = std_rec.id.replace(',', ';')
std_rec.info['SVTYPE'] = raw_rec.info['SVTYPE']
std_rec.info['CHR2'] = std_rec.chrom
std_rec.sto... | WhamStandardizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhamStandardizer:
def standardize_info(self, std_rec, raw_rec):
"""Standardize Wham record."""
<|body_0|>
def standardize_format(self, std_rec, raw_rec):
"""Parse called samples from TAGS field"""
<|body_1|>
def standardize_format(self, std_rec, raw_rec)... | stack_v2_sparse_classes_75kplus_train_008974 | 2,556 | no_license | [
{
"docstring": "Standardize Wham record.",
"name": "standardize_info",
"signature": "def standardize_info(self, std_rec, raw_rec)"
},
{
"docstring": "Parse called samples from TAGS field",
"name": "standardize_format",
"signature": "def standardize_format(self, std_rec, raw_rec)"
},
... | 3 | stack_v2_sparse_classes_30k_train_005331 | Implement the Python class `WhamStandardizer` described below.
Class description:
Implement the WhamStandardizer class.
Method signatures and docstrings:
- def standardize_info(self, std_rec, raw_rec): Standardize Wham record.
- def standardize_format(self, std_rec, raw_rec): Parse called samples from TAGS field
- de... | Implement the Python class `WhamStandardizer` described below.
Class description:
Implement the WhamStandardizer class.
Method signatures and docstrings:
- def standardize_info(self, std_rec, raw_rec): Standardize Wham record.
- def standardize_format(self, std_rec, raw_rec): Parse called samples from TAGS field
- de... | 3214cac465ee46e531c3cf5d78258b7aba4319a4 | <|skeleton|>
class WhamStandardizer:
def standardize_info(self, std_rec, raw_rec):
"""Standardize Wham record."""
<|body_0|>
def standardize_format(self, std_rec, raw_rec):
"""Parse called samples from TAGS field"""
<|body_1|>
def standardize_format(self, std_rec, raw_rec)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WhamStandardizer:
def standardize_info(self, std_rec, raw_rec):
"""Standardize Wham record."""
if std_rec.id is None:
std_rec.id = 'SV'
else:
std_rec.id = std_rec.id.replace(':', '_')
std_rec.id = std_rec.id.replace(',', ';')
std_rec.info['SV... | the_stack_v2_python_sparse | svtk/standardize/std_wham.py | xuefzhao/svtk | train | 2 | |
8110bf869ef019ace883d7fb958fc6b6c37c2a8c | [
"val = self.cleaned_data.get('user')\nuser = UserInfo.objects.filter(username=val).first()\nif user:\n raise ValidationError('用户已经存在')\nelse:\n return val",
"val = self.cleaned_data.get('pwd')\nif val.isdigit():\n raise ValidationError('密码不能为纯数字')\nelse:\n return val",
"pwd = self.cleaned_data.get('... | <|body_start_0|>
val = self.cleaned_data.get('user')
user = UserInfo.objects.filter(username=val).first()
if user:
raise ValidationError('用户已经存在')
else:
return val
<|end_body_0|>
<|body_start_1|>
val = self.cleaned_data.get('pwd')
if val.isdigit()... | UserForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserForm:
def clean_user(self):
"""判断用户名是否重复"""
<|body_0|>
def clean_pwd(self):
"""判断用户密码是否为纯数字"""
<|body_1|>
def clean(self):
"""判断两次输入的密码是否相同"""
<|body_2|>
def clean_email(self):
"""判断邮箱是否与QQ邮箱"""
<|body_3|>
<|end_... | stack_v2_sparse_classes_75kplus_train_008975 | 4,784 | no_license | [
{
"docstring": "判断用户名是否重复",
"name": "clean_user",
"signature": "def clean_user(self)"
},
{
"docstring": "判断用户密码是否为纯数字",
"name": "clean_pwd",
"signature": "def clean_pwd(self)"
},
{
"docstring": "判断两次输入的密码是否相同",
"name": "clean",
"signature": "def clean(self)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_048479 | Implement the Python class `UserForm` described below.
Class description:
Implement the UserForm class.
Method signatures and docstrings:
- def clean_user(self): 判断用户名是否重复
- def clean_pwd(self): 判断用户密码是否为纯数字
- def clean(self): 判断两次输入的密码是否相同
- def clean_email(self): 判断邮箱是否与QQ邮箱 | Implement the Python class `UserForm` described below.
Class description:
Implement the UserForm class.
Method signatures and docstrings:
- def clean_user(self): 判断用户名是否重复
- def clean_pwd(self): 判断用户密码是否为纯数字
- def clean(self): 判断两次输入的密码是否相同
- def clean_email(self): 判断邮箱是否与QQ邮箱
<|skeleton|>
class UserForm:
def c... | 7698f8ce260439abb3cbdf478586fa1888791a61 | <|skeleton|>
class UserForm:
def clean_user(self):
"""判断用户名是否重复"""
<|body_0|>
def clean_pwd(self):
"""判断用户密码是否为纯数字"""
<|body_1|>
def clean(self):
"""判断两次输入的密码是否相同"""
<|body_2|>
def clean_email(self):
"""判断邮箱是否与QQ邮箱"""
<|body_3|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserForm:
def clean_user(self):
"""判断用户名是否重复"""
val = self.cleaned_data.get('user')
user = UserInfo.objects.filter(username=val).first()
if user:
raise ValidationError('用户已经存在')
else:
return val
def clean_pwd(self):
"""判断用户密码是否为纯数字""... | the_stack_v2_python_sparse | python练习/django exercise/cms/first/views.py | JacksonMike/python_exercise | train | 0 | |
8d297867decce94ad6bf8b061e4f9bccfce0be4a | [
"if v is not None:\n for i, submod in enumerate(sub_modules):\n try:\n submod.v = v['submodules']['v' + str(i)]\n except KeyError:\n if submod.v:\n raise Exception('variables v passed to Sequential class must have key chains in the form of\"submodules/v{}\", whe... | <|body_start_0|>
if v is not None:
for i, submod in enumerate(sub_modules):
try:
submod.v = v['submodules']['v' + str(i)]
except KeyError:
if submod.v:
raise Exception('variables v passed to Sequential cl... | Sequential | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sequential:
def __init__(self, *sub_modules, dev_str='cpu', v=None):
"""A sequential container. Modules will be added to it in the order they are passed in the constructor. :param submodules: Submodules to chain together into a sequence. :type submodules: sequence of ivy.Module instances... | stack_v2_sparse_classes_75kplus_train_008976 | 1,979 | permissive | [
{
"docstring": "A sequential container. Modules will be added to it in the order they are passed in the constructor. :param submodules: Submodules to chain together into a sequence. :type submodules: sequence of ivy.Module instances :param dev_str: device on which to create the layer's variables 'cuda:0', 'cuda... | 2 | stack_v2_sparse_classes_30k_val_002662 | Implement the Python class `Sequential` described below.
Class description:
Implement the Sequential class.
Method signatures and docstrings:
- def __init__(self, *sub_modules, dev_str='cpu', v=None): A sequential container. Modules will be added to it in the order they are passed in the constructor. :param submodule... | Implement the Python class `Sequential` described below.
Class description:
Implement the Sequential class.
Method signatures and docstrings:
- def __init__(self, *sub_modules, dev_str='cpu', v=None): A sequential container. Modules will be added to it in the order they are passed in the constructor. :param submodule... | 02ac7e8ee2202563049116186fe6595313d65cc1 | <|skeleton|>
class Sequential:
def __init__(self, *sub_modules, dev_str='cpu', v=None):
"""A sequential container. Modules will be added to it in the order they are passed in the constructor. :param submodules: Submodules to chain together into a sequence. :type submodules: sequence of ivy.Module instances... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sequential:
def __init__(self, *sub_modules, dev_str='cpu', v=None):
"""A sequential container. Modules will be added to it in the order they are passed in the constructor. :param submodules: Submodules to chain together into a sequence. :type submodules: sequence of ivy.Module instances :param dev_st... | the_stack_v2_python_sparse | ivy/neural_net_stateful/sequential.py | MZSHAN/ivy | train | 0 | |
976a9822f0280abefb4ca2aa8d1ff24f0598e8e2 | [
"super(focal_loss, self).__init__()\nself.alpha = alpha\nself.gamma = gamma\nself.logits = with_logits",
"if self.logits:\n CE_loss = F.binary_cross_entropy_with_logits(prediction, labels)\nelse:\n CE_loss = F.binary_cross_entropy(prediction, labels)\npt = torch.exp(-CE_loss)\nF_loss = self.alpha * (1 - pt)... | <|body_start_0|>
super(focal_loss, self).__init__()
self.alpha = alpha
self.gamma = gamma
self.logits = with_logits
<|end_body_0|>
<|body_start_1|>
if self.logits:
CE_loss = F.binary_cross_entropy_with_logits(prediction, labels)
else:
CE_loss = F.... | Loss function for classification tasks with large data imbalance. Focal loss (FL) is define as: FL(p_t) = -alpha*((1-p_t)^gamma))*log(p_t), where p_t is a cross-entropy loss for binary classification. For more details, see https://arxiv.org/abs/1708.02002. Args: alpha (float): "balance" coefficient, gamma (float): "foc... | focal_loss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class focal_loss:
"""Loss function for classification tasks with large data imbalance. Focal loss (FL) is define as: FL(p_t) = -alpha*((1-p_t)^gamma))*log(p_t), where p_t is a cross-entropy loss for binary classification. For more details, see https://arxiv.org/abs/1708.02002. Args: alpha (float): "bal... | stack_v2_sparse_classes_75kplus_train_008977 | 6,385 | permissive | [
{
"docstring": "Parameter initialization",
"name": "__init__",
"signature": "def __init__(self, alpha: int=0.5, gamma: int=2, with_logits: bool=True) -> None"
},
{
"docstring": "Calculates loss",
"name": "forward",
"signature": "def forward(self, prediction: torch.Tensor, labels: torch.T... | 2 | stack_v2_sparse_classes_30k_train_019633 | Implement the Python class `focal_loss` described below.
Class description:
Loss function for classification tasks with large data imbalance. Focal loss (FL) is define as: FL(p_t) = -alpha*((1-p_t)^gamma))*log(p_t), where p_t is a cross-entropy loss for binary classification. For more details, see https://arxiv.org/ab... | Implement the Python class `focal_loss` described below.
Class description:
Loss function for classification tasks with large data imbalance. Focal loss (FL) is define as: FL(p_t) = -alpha*((1-p_t)^gamma))*log(p_t), where p_t is a cross-entropy loss for binary classification. For more details, see https://arxiv.org/ab... | 6d187296074143d017ca8fc60302364cd946b180 | <|skeleton|>
class focal_loss:
"""Loss function for classification tasks with large data imbalance. Focal loss (FL) is define as: FL(p_t) = -alpha*((1-p_t)^gamma))*log(p_t), where p_t is a cross-entropy loss for binary classification. For more details, see https://arxiv.org/abs/1708.02002. Args: alpha (float): "bal... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class focal_loss:
"""Loss function for classification tasks with large data imbalance. Focal loss (FL) is define as: FL(p_t) = -alpha*((1-p_t)^gamma))*log(p_t), where p_t is a cross-entropy loss for binary classification. For more details, see https://arxiv.org/abs/1708.02002. Args: alpha (float): "balance" coeffic... | the_stack_v2_python_sparse | atomai/losses_metrics/losses.py | pycroscopy/atomai | train | 157 |
8daa5f12dd1d00a875dfda5d2bd86dd33fedcb16 | [
"question = Helper.check_if_question_posted_exists(self, question_id)\nif not question:\n return make_response(jsonify({'status': 404, 'msg': 'Question with that ID not found'}))\ndata = {'user_id': user_id, 'question_id': question_id, 'title': title, 'comment': comment}\ntry:\n add_comment = \"INSERT INTO ... | <|body_start_0|>
question = Helper.check_if_question_posted_exists(self, question_id)
if not question:
return make_response(jsonify({'status': 404, 'msg': 'Question with that ID not found'}))
data = {'user_id': user_id, 'question_id': question_id, 'title': title, 'comment': comment}
... | A class that handles all the comments operations | Comments | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Comments:
"""A class that handles all the comments operations"""
def create_comment(self, user_id, question_id, title, comment):
"""Method to create a comment"""
<|body_0|>
def get_all_comments(self):
"""Method to get all comments"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_008978 | 2,475 | permissive | [
{
"docstring": "Method to create a comment",
"name": "create_comment",
"signature": "def create_comment(self, user_id, question_id, title, comment)"
},
{
"docstring": "Method to get all comments",
"name": "get_all_comments",
"signature": "def get_all_comments(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015867 | Implement the Python class `Comments` described below.
Class description:
A class that handles all the comments operations
Method signatures and docstrings:
- def create_comment(self, user_id, question_id, title, comment): Method to create a comment
- def get_all_comments(self): Method to get all comments | Implement the Python class `Comments` described below.
Class description:
A class that handles all the comments operations
Method signatures and docstrings:
- def create_comment(self, user_id, question_id, title, comment): Method to create a comment
- def get_all_comments(self): Method to get all comments
<|skeleton... | 514de4fd3af1726b7f89525c6bfaaed230842853 | <|skeleton|>
class Comments:
"""A class that handles all the comments operations"""
def create_comment(self, user_id, question_id, title, comment):
"""Method to create a comment"""
<|body_0|>
def get_all_comments(self):
"""Method to get all comments"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Comments:
"""A class that handles all the comments operations"""
def create_comment(self, user_id, question_id, title, comment):
"""Method to create a comment"""
question = Helper.check_if_question_posted_exists(self, question_id)
if not question:
return make_response(... | the_stack_v2_python_sparse | app/API/version2/comments/models.py | SimonAwiti/Questioner-APIs | train | 0 |
b38b3087f26b833c2944e78c5b7f6d4901a000af | [
"if root is None:\n return True\nif self.checkBalanced(root.left) and self.checkBalanced(root.right) and (abs(self.getHeight(root.left) - self.getHeight(root.right)) <= 1):\n return True\nelse:\n return False",
"if root is None:\n return True\nif self.checkBalanced(root.left) and self.checkBalanced(ro... | <|body_start_0|>
if root is None:
return True
if self.checkBalanced(root.left) and self.checkBalanced(root.right) and (abs(self.getHeight(root.left) - self.getHeight(root.right)) <= 1):
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def checkBalanced(self, root):
"""检验以root为根结点的两棵树的高度是不是一样 :param root: :return:"""
<|body_1|>
def getHeight(self, root):
"""获取以root为结点的树的高度 :param root: :ret... | stack_v2_sparse_classes_75kplus_train_008979 | 1,500 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isBalanced",
"signature": "def isBalanced(self, root)"
},
{
"docstring": "检验以root为根结点的两棵树的高度是不是一样 :param root: :return:",
"name": "checkBalanced",
"signature": "def checkBalanced(self, root)"
},
{
"docstring": "获取以root为... | 3 | stack_v2_sparse_classes_30k_train_022311 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def checkBalanced(self, root): 检验以root为根结点的两棵树的高度是不是一样 :param root: :return:
- def getHeight(self, root): 获取以root为... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def checkBalanced(self, root): 检验以root为根结点的两棵树的高度是不是一样 :param root: :return:
- def getHeight(self, root): 获取以root为... | 163b376acab84e28c74cb784d10fe39f11510921 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def checkBalanced(self, root):
"""检验以root为根结点的两棵树的高度是不是一样 :param root: :return:"""
<|body_1|>
def getHeight(self, root):
"""获取以root为结点的树的高度 :param root: :ret... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
if root is None:
return True
if self.checkBalanced(root.left) and self.checkBalanced(root.right) and (abs(self.getHeight(root.left) - self.getHeight(root.right)) <= 1):
return True
... | the_stack_v2_python_sparse | code/Tree/110_E_Balanced Binary Tree.py | cathyxingchang/leetcode | train | 2 | |
e3079993328eb502d206b4fe93ef708a18071277 | [
"if filters is None:\n filters = {}\norm_filters = super(EventResource, self).build_filters(filters)\nquery = filters.get('q')\ncategory_pk = filters.get('catpk')\nif query is not None:\n sqs = SearchQuerySet().models(Event).load_all().auto_query(query)\n orm_filters['pk__in'] = [i.pk for i in sqs]\nif cat... | <|body_start_0|>
if filters is None:
filters = {}
orm_filters = super(EventResource, self).build_filters(filters)
query = filters.get('q')
category_pk = filters.get('catpk')
if query is not None:
sqs = SearchQuerySet().models(Event).load_all().auto_query(q... | EventResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventResource:
def build_filters(self, filters=None):
"""Custom filters used for category and searching."""
<|body_0|>
def dehydrate_image(self, bundle):
"""Ensures data includes a url for an app-sized thumbnail"""
<|body_1|>
def dehydrate(self, bundle):... | stack_v2_sparse_classes_75kplus_train_008980 | 2,337 | no_license | [
{
"docstring": "Custom filters used for category and searching.",
"name": "build_filters",
"signature": "def build_filters(self, filters=None)"
},
{
"docstring": "Ensures data includes a url for an app-sized thumbnail",
"name": "dehydrate_image",
"signature": "def dehydrate_image(self, b... | 3 | stack_v2_sparse_classes_30k_train_028558 | Implement the Python class `EventResource` described below.
Class description:
Implement the EventResource class.
Method signatures and docstrings:
- def build_filters(self, filters=None): Custom filters used for category and searching.
- def dehydrate_image(self, bundle): Ensures data includes a url for an app-sized... | Implement the Python class `EventResource` described below.
Class description:
Implement the EventResource class.
Method signatures and docstrings:
- def build_filters(self, filters=None): Custom filters used for category and searching.
- def dehydrate_image(self, bundle): Ensures data includes a url for an app-sized... | 3ed85e856a026001a1d91d09d31d944c64704824 | <|skeleton|>
class EventResource:
def build_filters(self, filters=None):
"""Custom filters used for category and searching."""
<|body_0|>
def dehydrate_image(self, bundle):
"""Ensures data includes a url for an app-sized thumbnail"""
<|body_1|>
def dehydrate(self, bundle):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventResource:
def build_filters(self, filters=None):
"""Custom filters used for category and searching."""
if filters is None:
filters = {}
orm_filters = super(EventResource, self).build_filters(filters)
query = filters.get('q')
category_pk = filters.get('c... | the_stack_v2_python_sparse | scenable/events/api.py | gregarious/betasite | train | 0 | |
ab05300cfd4140101590757baf160461dda9d87b | [
"QtGui.QValidator.__init__(self, None)\nself._baseRepositoryModel = baseRepositoryModel\nself._errorHandler = errorHandler\nself._checkTargetDataTypesExistence = checkTargetDataTypesExistence\nself._item = None\nself._currentItemName = ''",
"self._currentItemName = unicode(itemName)\nself._performItemNameValidati... | <|body_start_0|>
QtGui.QValidator.__init__(self, None)
self._baseRepositoryModel = baseRepositoryModel
self._errorHandler = errorHandler
self._checkTargetDataTypesExistence = checkTargetDataTypesExistence
self._item = None
self._currentItemName = ''
<|end_body_0|>
<|body... | Custom validator for item name checking. | _ItemNameValidator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ItemNameValidator:
"""Custom validator for item name checking."""
def __init__(self, baseRepositoryModel, errorHandler, checkTargetDataTypesExistence=False):
"""Constructor. @param baseRepositoryModel: The not filtered repository model. @type baseRepositoryModel: L{RepositoryModel<d... | stack_v2_sparse_classes_75kplus_train_008981 | 11,494 | no_license | [
{
"docstring": "Constructor. @param baseRepositoryModel: The not filtered repository model. @type baseRepositoryModel: L{RepositoryModel<datafinder.gui.user.models.repository.repository.RepositoryModel>} @param errorHandler: Reference to the error handler instance. @type errorHandler: L{ErrorHandler<datafinder.... | 4 | stack_v2_sparse_classes_30k_train_007396 | Implement the Python class `_ItemNameValidator` described below.
Class description:
Custom validator for item name checking.
Method signatures and docstrings:
- def __init__(self, baseRepositoryModel, errorHandler, checkTargetDataTypesExistence=False): Constructor. @param baseRepositoryModel: The not filtered reposit... | Implement the Python class `_ItemNameValidator` described below.
Class description:
Custom validator for item name checking.
Method signatures and docstrings:
- def __init__(self, baseRepositoryModel, errorHandler, checkTargetDataTypesExistence=False): Constructor. @param baseRepositoryModel: The not filtered reposit... | 958fda4f3064f9f6b2034da396a20ac9d9abd52f | <|skeleton|>
class _ItemNameValidator:
"""Custom validator for item name checking."""
def __init__(self, baseRepositoryModel, errorHandler, checkTargetDataTypesExistence=False):
"""Constructor. @param baseRepositoryModel: The not filtered repository model. @type baseRepositoryModel: L{RepositoryModel<d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _ItemNameValidator:
"""Custom validator for item name checking."""
def __init__(self, baseRepositoryModel, errorHandler, checkTargetDataTypesExistence=False):
"""Constructor. @param baseRepositoryModel: The not filtered repository model. @type baseRepositoryModel: L{RepositoryModel<datafinder.gui... | the_stack_v2_python_sparse | src/datafinder/gui/user/dialogs/creation_wizard/pages/item_selection_page.py | DLR-SC/DataFinder | train | 9 |
9ed44e8405a992a194d64ef1dfe95b7da8b63d1b | [
"outString = ''\nunitLen = 8\nfor singleStr in strs:\n strLen = len(singleStr)\n strLenLen = len(str(strLen))\n outString += '0' * (unitLen - strLenLen) + str(strLen)\n outString += singleStr\nreturn outString",
"strList = []\ninputLen = len(s)\nif inputLen > 0:\n unitLen = 8\n curIdx = 0\n w... | <|body_start_0|>
outString = ''
unitLen = 8
for singleStr in strs:
strLen = len(singleStr)
strLenLen = len(str(strLen))
outString += '0' * (unitLen - strLenLen) + str(strLen)
outString += singleStr
return outString
<|end_body_0|>
<|body_st... | Codec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
outString... | stack_v2_sparse_classes_75kplus_train_008982 | 1,253 | permissive | [
{
"docstring": "Encodes a list of strings to a single string.",
"name": "encode",
"signature": "def encode(self, strs: [str]) -> str"
},
{
"docstring": "Decodes a single string to a list of strings.",
"name": "decode",
"signature": "def decode(self, s: str) -> [str]"
}
] | 2 | stack_v2_sparse_classes_30k_train_017906 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings.
<|skeleton|>
cla... | 48a57f6a5d5745199c5685cd2c8f5c4fa293e54a | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
outString = ''
unitLen = 8
for singleStr in strs:
strLen = len(singleStr)
strLenLen = len(str(strLen))
outString += '0' * (unitLen - strLenLen) +... | the_stack_v2_python_sparse | Q02__/71_Encode_and_Decode_Strings/Solution.py | hsclinical/leetcode | train | 0 | |
e09885733bee99ea6c512a79229363a91495664e | [
"self._dir = dir_\nself._find_wav = find_wav\nself._file_map = {}\nassert dir_\nself._wav_file_cache = wav.WavFileCache(dir_)",
"if file_ in self._file_map:\n return self._file_map[file_]\nelse:\n try:\n file_on_disk = self._wav_file_cache(file_)\n except FileNotFoundError:\n if self._find_... | <|body_start_0|>
self._dir = dir_
self._find_wav = find_wav
self._file_map = {}
assert dir_
self._wav_file_cache = wav.WavFileCache(dir_)
<|end_body_0|>
<|body_start_1|>
if file_ in self._file_map:
return self._file_map[file_]
else:
try:
... | Return the path to a valid WAV file in the files system using the input :param:`file_` value. If the WAV file can not be found and :param:`_find_wav` is :data:`True`, then an exception is raised. | _FileLookup | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _FileLookup:
"""Return the path to a valid WAV file in the files system using the input :param:`file_` value. If the WAV file can not be found and :param:`_find_wav` is :data:`True`, then an exception is raised."""
def __init__(self, dir_, find_wav):
""":param dir_: Path location of ... | stack_v2_sparse_classes_75kplus_train_008983 | 18,864 | permissive | [
{
"docstring": ":param dir_: Path location of the working directory :type dir_: string :param find_wav: :data:`True`/:data:`False1, :data:`True` causes exceptions to be raised if a WAV file can not be found in the FS. :type find_wav: bool .. Document private members .. automethod:: __call__",
"name": "__ini... | 2 | stack_v2_sparse_classes_30k_train_006978 | Implement the Python class `_FileLookup` described below.
Class description:
Return the path to a valid WAV file in the files system using the input :param:`file_` value. If the WAV file can not be found and :param:`_find_wav` is :data:`True`, then an exception is raised.
Method signatures and docstrings:
- def __ini... | Implement the Python class `_FileLookup` described below.
Class description:
Return the path to a valid WAV file in the files system using the input :param:`file_` value. If the WAV file can not be found and :param:`_find_wav` is :data:`True`, then an exception is raised.
Method signatures and docstrings:
- def __ini... | 36dd86b71c79c1f02ca07743b4bdea08527bafda | <|skeleton|>
class _FileLookup:
"""Return the path to a valid WAV file in the files system using the input :param:`file_` value. If the WAV file can not be found and :param:`_find_wav` is :data:`True`, then an exception is raised."""
def __init__(self, dir_, find_wav):
""":param dir_: Path location of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _FileLookup:
"""Return the path to a valid WAV file in the files system using the input :param:`file_` value. If the WAV file can not be found and :param:`_find_wav` is :data:`True`, then an exception is raised."""
def __init__(self, dir_, find_wav):
""":param dir_: Path location of the working d... | the_stack_v2_python_sparse | mktoc/parser.py | cmcginty/mktoc | train | 12 |
51471a242c9778609113ef6ff9775962dcd5ab44 | [
"if not s or len(s.strip(' ')) == 0:\n return ''\nres = s.split(' ')\nstr = ''\nfor i in range(len(res) - 1, -1, -1):\n str = str.strip(' ') + ' ' + res[i]\nreturn str.strip(' ')",
"if not s or len(s.strip(' ')) == 0:\n return ''\nslist = s.split()\nslist = slist[::-1]\nreturn ' '.join(slist)"
] | <|body_start_0|>
if not s or len(s.strip(' ')) == 0:
return ''
res = s.split(' ')
str = ''
for i in range(len(res) - 1, -1, -1):
str = str.strip(' ') + ' ' + res[i]
return str.strip(' ')
<|end_body_0|>
<|body_start_1|>
if not s or len(s.strip(' ')... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseWordsSol(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s or len(s.strip(' ')) == 0:
return ''
... | stack_v2_sparse_classes_75kplus_train_008984 | 1,018 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWords",
"signature": "def reverseWords(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWordsSol",
"signature": "def reverseWordsSol(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040008 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverseWordsSol(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverseWordsSol(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def reverseWords(self, s):
... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseWordsSol(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
if not s or len(s.strip(' ')) == 0:
return ''
res = s.split(' ')
str = ''
for i in range(len(res) - 1, -1, -1):
str = str.strip(' ') + ' ' + res[i]
return str.strip(' ')
... | the_stack_v2_python_sparse | medium/reverse_words_in_string.py | gerrycfchang/leetcode-python | train | 2 | |
2132f693cd3d9057d4094bcc1b5431be37171a0e | [
"with CommandGroup(self, '', 'superbench.cli._handler#{}') as g:\n g.command('version', 'version_command_handler')\n g.command('deploy', 'deploy_command_handler')\n g.command('exec', 'exec_command_handler')\n g.command('run', 'run_command_handler')\nreturn super().load_command_table(args)",
"with Argu... | <|body_start_0|>
with CommandGroup(self, '', 'superbench.cli._handler#{}') as g:
g.command('version', 'version_command_handler')
g.command('deploy', 'deploy_command_handler')
g.command('exec', 'exec_command_handler')
g.command('run', 'run_command_handler')
... | SuperBench CLI commands loader. | SuperBenchCommandsLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperBenchCommandsLoader:
"""SuperBench CLI commands loader."""
def load_command_table(self, args):
"""Load commands into the command table. Args: args (list): List of arguments from the command line. Returns: collections.OrderedDict: Load commands into the command table."""
... | stack_v2_sparse_classes_75kplus_train_008985 | 2,668 | permissive | [
{
"docstring": "Load commands into the command table. Args: args (list): List of arguments from the command line. Returns: collections.OrderedDict: Load commands into the command table.",
"name": "load_command_table",
"signature": "def load_command_table(self, args)"
},
{
"docstring": "Load argu... | 2 | stack_v2_sparse_classes_30k_train_026809 | Implement the Python class `SuperBenchCommandsLoader` described below.
Class description:
SuperBench CLI commands loader.
Method signatures and docstrings:
- def load_command_table(self, args): Load commands into the command table. Args: args (list): List of arguments from the command line. Returns: collections.Order... | Implement the Python class `SuperBenchCommandsLoader` described below.
Class description:
SuperBench CLI commands loader.
Method signatures and docstrings:
- def load_command_table(self, args): Load commands into the command table. Args: args (list): List of arguments from the command line. Returns: collections.Order... | 43620c3f46701d11514901e5c238d7a571ab3ea9 | <|skeleton|>
class SuperBenchCommandsLoader:
"""SuperBench CLI commands loader."""
def load_command_table(self, args):
"""Load commands into the command table. Args: args (list): List of arguments from the command line. Returns: collections.OrderedDict: Load commands into the command table."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SuperBenchCommandsLoader:
"""SuperBench CLI commands loader."""
def load_command_table(self, args):
"""Load commands into the command table. Args: args (list): List of arguments from the command line. Returns: collections.OrderedDict: Load commands into the command table."""
with CommandG... | the_stack_v2_python_sparse | superbench/cli/_commands.py | QPC-database/superbenchmark | train | 1 |
942f7e2ac06f33815a91e6f04e0527deb23a6d66 | [
"expected_result = np.array([[0.0, 0.0, 0.1, 0.0, 0.0], [0.0, 0.0, 0.175, 0.0, 0.0], [0.05, 0.125, 0.3375, 0.125, 0.05], [0.025, 0.0625, 0.29375, 0.0625, 0.025], [0.0125, 0.03125, 0.196875, 0.03125, 0.0125]])\nresult = RecursiveFilter(edge_width=1)._recurse_forward(self.cube.data[0, :], self.smoothing_coefficients[... | <|body_start_0|>
expected_result = np.array([[0.0, 0.0, 0.1, 0.0, 0.0], [0.0, 0.0, 0.175, 0.0, 0.0], [0.05, 0.125, 0.3375, 0.125, 0.05], [0.025, 0.0625, 0.29375, 0.0625, 0.025], [0.0125, 0.03125, 0.196875, 0.03125, 0.0125]])
result = RecursiveFilter(edge_width=1)._recurse_forward(self.cube.data[0, :], s... | Test the _recurse_forward method | Test__recurse_forward | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__recurse_forward:
"""Test the _recurse_forward method"""
def test_first_axis(self):
"""Test that the returned _recurse_forward array has the expected type and result."""
<|body_0|>
def test_second_axis(self):
"""Test that the returned _recurse_forward array ... | stack_v2_sparse_classes_75kplus_train_008986 | 22,857 | permissive | [
{
"docstring": "Test that the returned _recurse_forward array has the expected type and result.",
"name": "test_first_axis",
"signature": "def test_first_axis(self)"
},
{
"docstring": "Test that the returned _recurse_forward array has the expected type and result.",
"name": "test_second_axis... | 2 | stack_v2_sparse_classes_30k_train_047318 | Implement the Python class `Test__recurse_forward` described below.
Class description:
Test the _recurse_forward method
Method signatures and docstrings:
- def test_first_axis(self): Test that the returned _recurse_forward array has the expected type and result.
- def test_second_axis(self): Test that the returned _r... | Implement the Python class `Test__recurse_forward` described below.
Class description:
Test the _recurse_forward method
Method signatures and docstrings:
- def test_first_axis(self): Test that the returned _recurse_forward array has the expected type and result.
- def test_second_axis(self): Test that the returned _r... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__recurse_forward:
"""Test the _recurse_forward method"""
def test_first_axis(self):
"""Test that the returned _recurse_forward array has the expected type and result."""
<|body_0|>
def test_second_axis(self):
"""Test that the returned _recurse_forward array ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test__recurse_forward:
"""Test the _recurse_forward method"""
def test_first_axis(self):
"""Test that the returned _recurse_forward array has the expected type and result."""
expected_result = np.array([[0.0, 0.0, 0.1, 0.0, 0.0], [0.0, 0.0, 0.175, 0.0, 0.0], [0.05, 0.125, 0.3375, 0.125, 0... | the_stack_v2_python_sparse | improver_tests/nbhood/recursive_filter/test_RecursiveFilter.py | metoppv/improver | train | 101 |
ae76aaf55b778b74240786decc0467ee065347c7 | [
"self.model = model\nself.target_source_type = target_source_type\nself.sample_rate = sample_rate\nself.mono = mono\nself.segment_samples = segment_samples\nself.evaluate_step_frequency = evaluate_step_frequency\nself.logger = logger\nself.statistics_container = statistics_container\nself.evaluation_audios_dir = ev... | <|body_start_0|>
self.model = model
self.target_source_type = target_source_type
self.sample_rate = sample_rate
self.mono = mono
self.segment_samples = segment_samples
self.evaluate_step_frequency = evaluate_step_frequency
self.logger = logger
self.statist... | EvaluationCallback | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluationCallback:
def __init__(self, model: nn.Module, input_channels: int, evaluation_audios_dir: str, target_source_type: str, sample_rate: int, mono: bool, segment_samples: int, batch_size: int, device: str, evaluate_step_frequency: int, logger: pl.loggers.TensorBoardLogger, statistics_cont... | stack_v2_sparse_classes_75kplus_train_008987 | 6,884 | permissive | [
{
"docstring": "Callback to evaluate every #save_step_frequency steps. Args: model: nn.Module input_channels: int evaluation_audios_dir: str, directory containing audios for evaluation target_source_type: str, e.g., 'violin' sample_rate: int mono: bool segment_samples: int, length of segments to be input to a m... | 2 | stack_v2_sparse_classes_30k_train_034937 | Implement the Python class `EvaluationCallback` described below.
Class description:
Implement the EvaluationCallback class.
Method signatures and docstrings:
- def __init__(self, model: nn.Module, input_channels: int, evaluation_audios_dir: str, target_source_type: str, sample_rate: int, mono: bool, segment_samples: ... | Implement the Python class `EvaluationCallback` described below.
Class description:
Implement the EvaluationCallback class.
Method signatures and docstrings:
- def __init__(self, model: nn.Module, input_channels: int, evaluation_audios_dir: str, target_source_type: str, sample_rate: int, mono: bool, segment_samples: ... | 0a088e1fc852a15d7e558a7e203888de0577dfb1 | <|skeleton|>
class EvaluationCallback:
def __init__(self, model: nn.Module, input_channels: int, evaluation_audios_dir: str, target_source_type: str, sample_rate: int, mono: bool, segment_samples: int, batch_size: int, device: str, evaluate_step_frequency: int, logger: pl.loggers.TensorBoardLogger, statistics_cont... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EvaluationCallback:
def __init__(self, model: nn.Module, input_channels: int, evaluation_audios_dir: str, target_source_type: str, sample_rate: int, mono: bool, segment_samples: int, batch_size: int, device: str, evaluate_step_frequency: int, logger: pl.loggers.TensorBoardLogger, statistics_container: Statist... | the_stack_v2_python_sparse | bytesep/callbacks/instruments_callbacks.py | XinyuanLiu2018/music_source_separation | train | 0 | |
e7e3cbe6a193ef0613a60c5ddb7a015fcf014f25 | [
"if 'Origin' in self.request.headers:\n self.set_header('Access-Control-Allow-Origin', self.request.headers['Origin'])\nschedule_uuids = (yield models.schedule.list())\nschedules = (yield [models.schedule.read(schedule_uuid) for schedule_uuid in schedule_uuids])\nfor schedule in schedules:\n schedule.setdefau... | <|body_start_0|>
if 'Origin' in self.request.headers:
self.set_header('Access-Control-Allow-Origin', self.request.headers['Origin'])
schedule_uuids = (yield models.schedule.list())
schedules = (yield [models.schedule.read(schedule_uuid) for schedule_uuid in schedule_uuids])
f... | Schedule Collection Resource :``URL``: ``/schedules/`` | ScheduleCollectionHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduleCollectionHandler:
"""Schedule Collection Resource :``URL``: ``/schedules/``"""
def get(self):
"""Get Schedule Collection Resource Parameters ---------- Headers ^^^^^^^ :``Origin``: serving domain of requesting page; **optional** Return Value(s) --------------- :``200 OK``: :... | stack_v2_sparse_classes_75kplus_train_008988 | 12,091 | permissive | [
{
"docstring": "Get Schedule Collection Resource Parameters ---------- Headers ^^^^^^^ :``Origin``: serving domain of requesting page; **optional** Return Value(s) --------------- :``200 OK``: :**headers**: * ``Content-Type`` if ``Origin`` in request: * ``Access-Control-Allow-Origin`` :**body**: JSON representa... | 3 | stack_v2_sparse_classes_30k_train_005099 | Implement the Python class `ScheduleCollectionHandler` described below.
Class description:
Schedule Collection Resource :``URL``: ``/schedules/``
Method signatures and docstrings:
- def get(self): Get Schedule Collection Resource Parameters ---------- Headers ^^^^^^^ :``Origin``: serving domain of requesting page; **... | Implement the Python class `ScheduleCollectionHandler` described below.
Class description:
Schedule Collection Resource :``URL``: ``/schedules/``
Method signatures and docstrings:
- def get(self): Get Schedule Collection Resource Parameters ---------- Headers ^^^^^^^ :``Origin``: serving domain of requesting page; **... | 0e4f0a7cdc0f5ff016dc6e9271631953a0fe4092 | <|skeleton|>
class ScheduleCollectionHandler:
"""Schedule Collection Resource :``URL``: ``/schedules/``"""
def get(self):
"""Get Schedule Collection Resource Parameters ---------- Headers ^^^^^^^ :``Origin``: serving domain of requesting page; **optional** Return Value(s) --------------- :``200 OK``: :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScheduleCollectionHandler:
"""Schedule Collection Resource :``URL``: ``/schedules/``"""
def get(self):
"""Get Schedule Collection Resource Parameters ---------- Headers ^^^^^^^ :``Origin``: serving domain of requesting page; **optional** Return Value(s) --------------- :``200 OK``: :**headers**: ... | the_stack_v2_python_sparse | muniments/scheduler/api/schedule.py | alunduil/muniments | train | 1 |
7388a0bf5e0a68f56846b162caaba45cefbfccac | [
"device = Device.query.get(device_id)\nif not device:\n return ('Device Not Found', 400)\nif not device.user_id == current_user.id:\n return ('Access Denied', 403)\nreturn (device.view(), 200)",
"device = Device.query.get(device_id)\nif not device:\n return ('Device Not Found', 404)\nif not device.user_i... | <|body_start_0|>
device = Device.query.get(device_id)
if not device:
return ('Device Not Found', 400)
if not device.user_id == current_user.id:
return ('Access Denied', 403)
return (device.view(), 200)
<|end_body_0|>
<|body_start_1|>
device = Device.query... | DeviceDetailsResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceDetailsResource:
def get(self, device_id):
"""Get Device Detail"""
<|body_0|>
def put(self, device_id):
"""Edit Device Detail"""
<|body_1|>
def delete(self, device_id):
"""Delete Device Detail"""
<|body_2|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_008989 | 4,394 | no_license | [
{
"docstring": "Get Device Detail",
"name": "get",
"signature": "def get(self, device_id)"
},
{
"docstring": "Edit Device Detail",
"name": "put",
"signature": "def put(self, device_id)"
},
{
"docstring": "Delete Device Detail",
"name": "delete",
"signature": "def delete(s... | 3 | stack_v2_sparse_classes_30k_train_020559 | Implement the Python class `DeviceDetailsResource` described below.
Class description:
Implement the DeviceDetailsResource class.
Method signatures and docstrings:
- def get(self, device_id): Get Device Detail
- def put(self, device_id): Edit Device Detail
- def delete(self, device_id): Delete Device Detail | Implement the Python class `DeviceDetailsResource` described below.
Class description:
Implement the DeviceDetailsResource class.
Method signatures and docstrings:
- def get(self, device_id): Get Device Detail
- def put(self, device_id): Edit Device Detail
- def delete(self, device_id): Delete Device Detail
<|skelet... | 1865ce093c30b834af23583ceb1ad8024424c117 | <|skeleton|>
class DeviceDetailsResource:
def get(self, device_id):
"""Get Device Detail"""
<|body_0|>
def put(self, device_id):
"""Edit Device Detail"""
<|body_1|>
def delete(self, device_id):
"""Delete Device Detail"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeviceDetailsResource:
def get(self, device_id):
"""Get Device Detail"""
device = Device.query.get(device_id)
if not device:
return ('Device Not Found', 400)
if not device.user_id == current_user.id:
return ('Access Denied', 403)
return (device.v... | the_stack_v2_python_sparse | fisbang/api/device.py | Fisbang/fisbang-app | train | 0 | |
d169f06c49e9beae3dc4d69b030f5ba9b0cf214c | [
"self.file_select_policy = file_select_policy\nself.file_size = file_size\nself.file_size_policy = file_size_policy\nself.hot_file_window = hot_file_window\nself.nfs_mount_path = nfs_mount_path\nself.num_file_access = num_file_access\nself.source_view_name = source_view_name\nself.uptier_all_files = uptier_all_file... | <|body_start_0|>
self.file_select_policy = file_select_policy
self.file_size = file_size
self.file_size_policy = file_size_policy
self.hot_file_window = hot_file_window
self.nfs_mount_path = nfs_mount_path
self.num_file_access = num_file_access
self.source_view_na... | Implementation of the 'FileUptieringParams' model. File Uptiering Parameters for NAS migration. Attributes: file_select_policy (int): File uptier policy based on file access/modify time. file_size (int): Gives the size criteria to be used for selecting the files to be uptiered. The hot files, which are greater or small... | FileUptieringParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileUptieringParams:
"""Implementation of the 'FileUptieringParams' model. File Uptiering Parameters for NAS migration. Attributes: file_select_policy (int): File uptier policy based on file access/modify time. file_size (int): Gives the size criteria to be used for selecting the files to be upti... | stack_v2_sparse_classes_75kplus_train_008990 | 4,196 | permissive | [
{
"docstring": "Constructor for the FileUptieringParams class",
"name": "__init__",
"signature": "def __init__(self, file_select_policy=None, file_size=None, file_size_policy=None, hot_file_window=None, nfs_mount_path=None, num_file_access=None, source_view_name=None, uptier_all_files=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_035084 | Implement the Python class `FileUptieringParams` described below.
Class description:
Implementation of the 'FileUptieringParams' model. File Uptiering Parameters for NAS migration. Attributes: file_select_policy (int): File uptier policy based on file access/modify time. file_size (int): Gives the size criteria to be ... | Implement the Python class `FileUptieringParams` described below.
Class description:
Implementation of the 'FileUptieringParams' model. File Uptiering Parameters for NAS migration. Attributes: file_select_policy (int): File uptier policy based on file access/modify time. file_size (int): Gives the size criteria to be ... | 0093194d125fc6746f55b8499da1270c64f473fc | <|skeleton|>
class FileUptieringParams:
"""Implementation of the 'FileUptieringParams' model. File Uptiering Parameters for NAS migration. Attributes: file_select_policy (int): File uptier policy based on file access/modify time. file_size (int): Gives the size criteria to be used for selecting the files to be upti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileUptieringParams:
"""Implementation of the 'FileUptieringParams' model. File Uptiering Parameters for NAS migration. Attributes: file_select_policy (int): File uptier policy based on file access/modify time. file_size (int): Gives the size criteria to be used for selecting the files to be uptiered. The hot... | the_stack_v2_python_sparse | cohesity_management_sdk/models/file_uptiering_params.py | hsantoyo2/management-sdk-python | train | 0 |
9fefa89098e76daa0973711d6d7f38d505fb8fdf | [
"super(DropStripes, self).__init__()\nassert dim in [2, 3]\nself.dim = dim\nself.drop_width = drop_width\nself.stripes_num = stripes_num",
"assert input.ndimension() == 4\nif self.training is False:\n return input\nelse:\n batch_size = input.shape[0]\n total_width = input.shape[self.dim]\n shuffle_bat... | <|body_start_0|>
super(DropStripes, self).__init__()
assert dim in [2, 3]
self.dim = dim
self.drop_width = drop_width
self.stripes_num = stripes_num
<|end_body_0|>
<|body_start_1|>
assert input.ndimension() == 4
if self.training is False:
return input... | DropStripes | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DropStripes:
def __init__(self, dim, drop_width, stripes_num):
"""Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop"""
<|body_0|>
def forward(self, input):
"""input... | stack_v2_sparse_classes_75kplus_train_008991 | 4,579 | permissive | [
{
"docstring": "Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop",
"name": "__init__",
"signature": "def __init__(self, dim, drop_width, stripes_num)"
},
{
"docstring": "input: (batch_size, ch... | 3 | stack_v2_sparse_classes_30k_train_024170 | Implement the Python class `DropStripes` described below.
Class description:
Implement the DropStripes class.
Method signatures and docstrings:
- def __init__(self, dim, drop_width, stripes_num): Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num:... | Implement the Python class `DropStripes` described below.
Class description:
Implement the DropStripes class.
Method signatures and docstrings:
- def __init__(self, dim, drop_width, stripes_num): Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num:... | d7cf7b39e3164a75547ee50cc9a29bd5ed4c29bd | <|skeleton|>
class DropStripes:
def __init__(self, dim, drop_width, stripes_num):
"""Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop"""
<|body_0|>
def forward(self, input):
"""input... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DropStripes:
def __init__(self, dim, drop_width, stripes_num):
"""Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop"""
super(DropStripes, self).__init__()
assert dim in [2, 3]
... | the_stack_v2_python_sparse | src/kvt/augmentation/spec_augmentation.py | Ynakatsuka/birdclef-2021 | train | 6 | |
fcde832f47a715dfa74df8d8796d491c846c6a68 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | we start with everything as "required" while developing / debugging. This forces correctness better. FIXME: move to "optional" once development is complete | AggregatorServicer | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-protobuf",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AggregatorServicer:
"""we start with everything as "required" while developing / debugging. This forces correctness better. FIXME: move to "optional" once development is complete"""
def RequestJob(self, request, context):
"""Missing associated documentation comment in .proto file"""
... | stack_v2_sparse_classes_75kplus_train_008992 | 8,057 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file",
"name": "RequestJob",
"signature": "def RequestJob(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file",
"name": "DownloadModel",
"signature": "def DownloadModel(self... | 4 | stack_v2_sparse_classes_30k_train_047197 | Implement the Python class `AggregatorServicer` described below.
Class description:
we start with everything as "required" while developing / debugging. This forces correctness better. FIXME: move to "optional" once development is complete
Method signatures and docstrings:
- def RequestJob(self, request, context): Mi... | Implement the Python class `AggregatorServicer` described below.
Class description:
we start with everything as "required" while developing / debugging. This forces correctness better. FIXME: move to "optional" once development is complete
Method signatures and docstrings:
- def RequestJob(self, request, context): Mi... | d8e2d22dfccfb8488f70f1fb5593d4e6ee1eca1f | <|skeleton|>
class AggregatorServicer:
"""we start with everything as "required" while developing / debugging. This forces correctness better. FIXME: move to "optional" once development is complete"""
def RequestJob(self, request, context):
"""Missing associated documentation comment in .proto file"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AggregatorServicer:
"""we start with everything as "required" while developing / debugging. This forces correctness better. FIXME: move to "optional" once development is complete"""
def RequestJob(self, request, context):
"""Missing associated documentation comment in .proto file"""
conte... | the_stack_v2_python_sparse | openfl/proto/collaborator_aggregator_interface_pb2_grpc.py | sbakas/OpenFederatedLearning-1 | train | 0 |
e45b82ff7692afab42642610824cf7c103d911c7 | [
"self.id = 1\nself.title = title\nself._analyzer = analyzer",
"parameter_dict = aggregation.parameters\nif agg_type:\n parameter_dict['supported_charts'] = agg_type\nelse:\n agg_type = parameter_dict.get('supported_charts')\n if not agg_type:\n agg_type = 'table'\n parameter_dict['supported... | <|body_start_0|>
self.id = 1
self.title = title
self._analyzer = analyzer
<|end_body_0|>
<|body_start_1|>
parameter_dict = aggregation.parameters
if agg_type:
parameter_dict['supported_charts'] = agg_type
else:
agg_type = parameter_dict.get('suppo... | Mocked story object. | Story | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Story:
"""Mocked story object."""
def __init__(self, analyzer, title):
"""Initialize the story."""
<|body_0|>
def add_aggregation(self, aggregation, agg_type=''):
"""Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved aggregation to add t... | stack_v2_sparse_classes_75kplus_train_008993 | 31,229 | permissive | [
{
"docstring": "Initialize the story.",
"name": "__init__",
"signature": "def __init__(self, analyzer, title)"
},
{
"docstring": "Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved aggregation to add to the story. agg_type (str): string indicating the type of aggregatio... | 5 | stack_v2_sparse_classes_30k_train_028372 | Implement the Python class `Story` described below.
Class description:
Mocked story object.
Method signatures and docstrings:
- def __init__(self, analyzer, title): Initialize the story.
- def add_aggregation(self, aggregation, agg_type=''): Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved... | Implement the Python class `Story` described below.
Class description:
Mocked story object.
Method signatures and docstrings:
- def __init__(self, analyzer, title): Initialize the story.
- def add_aggregation(self, aggregation, agg_type=''): Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class Story:
"""Mocked story object."""
def __init__(self, analyzer, title):
"""Initialize the story."""
<|body_0|>
def add_aggregation(self, aggregation, agg_type=''):
"""Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved aggregation to add t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Story:
"""Mocked story object."""
def __init__(self, analyzer, title):
"""Initialize the story."""
self.id = 1
self.title = title
self._analyzer = analyzer
def add_aggregation(self, aggregation, agg_type=''):
"""Add a saved aggregation to the Story. Args: aggr... | the_stack_v2_python_sparse | test_tools/timesketch/lib/analyzers/interface.py | google/timesketch | train | 2,263 |
b45c54f00a29c74ae5f76c572052b7f80c19fa3e | [
"self.attack = attack\nself.x_test = x_test\nself.y_test = y_test\nself.source_class = source_class\nself.target_class = target_class\nself.trigger_index = trigger_index\nself.data_filepath = data_filepath",
"if len(x_train) != len(y_train):\n raise ValueError('Sizes of x and y do not match')\nif None in self.... | <|body_start_0|>
self.attack = attack
self.x_test = x_test
self.y_test = y_test
self.source_class = source_class
self.target_class = target_class
self.trigger_index = trigger_index
self.data_filepath = data_filepath
<|end_body_0|>
<|body_start_1|>
if len(... | DatasetPoisonerWitchesBrew | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetPoisonerWitchesBrew:
def __init__(self, attack, x_test, y_test, source_class, target_class, trigger_index, data_filepath):
"""Individual source-class triggers are chosen from x_test. At poison time, the train set is modified to induce misclassification of the triggers as target_cl... | stack_v2_sparse_classes_75kplus_train_008994 | 18,241 | permissive | [
{
"docstring": "Individual source-class triggers are chosen from x_test. At poison time, the train set is modified to induce misclassification of the triggers as target_class.",
"name": "__init__",
"signature": "def __init__(self, attack, x_test, y_test, source_class, target_class, trigger_index, data_f... | 2 | stack_v2_sparse_classes_30k_train_028436 | Implement the Python class `DatasetPoisonerWitchesBrew` described below.
Class description:
Implement the DatasetPoisonerWitchesBrew class.
Method signatures and docstrings:
- def __init__(self, attack, x_test, y_test, source_class, target_class, trigger_index, data_filepath): Individual source-class triggers are cho... | Implement the Python class `DatasetPoisonerWitchesBrew` described below.
Class description:
Implement the DatasetPoisonerWitchesBrew class.
Method signatures and docstrings:
- def __init__(self, attack, x_test, y_test, source_class, target_class, trigger_index, data_filepath): Individual source-class triggers are cho... | 3efd21652cfdc8cd192681e9daf58a4b08e82db4 | <|skeleton|>
class DatasetPoisonerWitchesBrew:
def __init__(self, attack, x_test, y_test, source_class, target_class, trigger_index, data_filepath):
"""Individual source-class triggers are chosen from x_test. At poison time, the train set is modified to induce misclassification of the triggers as target_cl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatasetPoisonerWitchesBrew:
def __init__(self, attack, x_test, y_test, source_class, target_class, trigger_index, data_filepath):
"""Individual source-class triggers are chosen from x_test. At poison time, the train set is modified to induce misclassification of the triggers as target_class."""
... | the_stack_v2_python_sparse | armory/scenarios/poisoning_witches_brew.py | twosixlabs/armory | train | 153 | |
211dbb5ced2387c153dbcbd6687efd69f181f479 | [
"get_patch.return_value = payload\ngithub_client = GithubOrgClient(url)\nresponse = github_client.org\nself.assertEqual(response, payload)\nget_patch.assert_called_once()",
"with patch.object(GithubOrgClient, 'org', new_callable=PropertyMock) as mock_o:\n test_json = {'url': 'facebook', 'repos_url': 'http://ta... | <|body_start_0|>
get_patch.return_value = payload
github_client = GithubOrgClient(url)
response = github_client.org
self.assertEqual(response, payload)
get_patch.assert_called_once()
<|end_body_0|>
<|body_start_1|>
with patch.object(GithubOrgClient, 'org', new_callable=P... | a test class that inherits from unittest.TestCase | TestGithubOrgClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGithubOrgClient:
"""a test class that inherits from unittest.TestCase"""
def test_org(self, url, payload, get_patch):
"""test that GithubOrgClient.org returns the correct value."""
<|body_0|>
def test_public_repos_url(self):
"""Test that the result of _public... | stack_v2_sparse_classes_75kplus_train_008995 | 2,677 | no_license | [
{
"docstring": "test that GithubOrgClient.org returns the correct value.",
"name": "test_org",
"signature": "def test_org(self, url, payload, get_patch)"
},
{
"docstring": "Test that the result of _public_repos_url is the expected one based on the mocked payload.",
"name": "test_public_repos... | 4 | stack_v2_sparse_classes_30k_train_043978 | Implement the Python class `TestGithubOrgClient` described below.
Class description:
a test class that inherits from unittest.TestCase
Method signatures and docstrings:
- def test_org(self, url, payload, get_patch): test that GithubOrgClient.org returns the correct value.
- def test_public_repos_url(self): Test that ... | Implement the Python class `TestGithubOrgClient` described below.
Class description:
a test class that inherits from unittest.TestCase
Method signatures and docstrings:
- def test_org(self, url, payload, get_patch): test that GithubOrgClient.org returns the correct value.
- def test_public_repos_url(self): Test that ... | cf61d1607676d0a4e2c79723f221e560d1af02ee | <|skeleton|>
class TestGithubOrgClient:
"""a test class that inherits from unittest.TestCase"""
def test_org(self, url, payload, get_patch):
"""test that GithubOrgClient.org returns the correct value."""
<|body_0|>
def test_public_repos_url(self):
"""Test that the result of _public... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestGithubOrgClient:
"""a test class that inherits from unittest.TestCase"""
def test_org(self, url, payload, get_patch):
"""test that GithubOrgClient.org returns the correct value."""
get_patch.return_value = payload
github_client = GithubOrgClient(url)
response = github_... | the_stack_v2_python_sparse | 0x09-Unittests_and_integration_tests/test_client.py | OnsJannet/holbertonschool-web_back_end | train | 1 |
641967cae612d725d5f28cd852bbff22a99e5b83 | [
"length = len(nums)\nleft, right, ans = ([0] * length, [0] * length, [0] * length)\nleft[0] = 1\nfor i in range(1, length):\n left[i] = nums[i - 1] * left[i - 1]\nright[length - 1] = 1\nfor i in reversed(range(length - 1)):\n right[i] = nums[i + 1] * right[i + 1]\nfor i in range(length):\n ans[i] = left[i]... | <|body_start_0|>
length = len(nums)
left, right, ans = ([0] * length, [0] * length, [0] * length)
left[0] = 1
for i in range(1, length):
left[i] = nums[i - 1] * left[i - 1]
right[length - 1] = 1
for i in reversed(range(length - 1)):
right[i] = nums... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def product_except_self(self, nums):
""":param nums: List[int] :return: List[int]"""
<|body_0|>
def product_except_self1(self, nums):
""":param nums: List[int] :return: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = len... | stack_v2_sparse_classes_75kplus_train_008996 | 993 | no_license | [
{
"docstring": ":param nums: List[int] :return: List[int]",
"name": "product_except_self",
"signature": "def product_except_self(self, nums)"
},
{
"docstring": ":param nums: List[int] :return: List[int]",
"name": "product_except_self1",
"signature": "def product_except_self1(self, nums)"... | 2 | stack_v2_sparse_classes_30k_test_000757 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def product_except_self(self, nums): :param nums: List[int] :return: List[int]
- def product_except_self1(self, nums): :param nums: List[int] :return: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def product_except_self(self, nums): :param nums: List[int] :return: List[int]
- def product_except_self1(self, nums): :param nums: List[int] :return: List[int]
<|skeleton|>
cla... | 8cb8b3882219bdfe5fa65d16abf5d4ffb3185994 | <|skeleton|>
class Solution:
def product_except_self(self, nums):
""":param nums: List[int] :return: List[int]"""
<|body_0|>
def product_except_self1(self, nums):
""":param nums: List[int] :return: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def product_except_self(self, nums):
""":param nums: List[int] :return: List[int]"""
length = len(nums)
left, right, ans = ([0] * length, [0] * length, [0] * length)
left[0] = 1
for i in range(1, length):
left[i] = nums[i - 1] * left[i - 1]
... | the_stack_v2_python_sparse | leetcode/algorithms/238_product_except_self.py | big-roc/Python3Projects | train | 0 | |
6b7104d96b1ad7d70d0f4bcd6d31574c1c0d1121 | [
"super(CSM, self).__init__()\nself.sentence_size = sentence_size\nself.conv1 = nn.Parameter(torch.randn((2, embed_size)))\nself.conv2 = nn.Parameter(torch.randn((2, embed_size)))\nself.conv3 = nn.Parameter(torch.randn((3, embed_size)))\nif sentence_size == 7:\n self.conv4 = nn.Parameter(torch.randn((3, embed_siz... | <|body_start_0|>
super(CSM, self).__init__()
self.sentence_size = sentence_size
self.conv1 = nn.Parameter(torch.randn((2, embed_size)))
self.conv2 = nn.Parameter(torch.randn((2, embed_size)))
self.conv3 = nn.Parameter(torch.randn((3, embed_size)))
if sentence_size == 7:
... | CSM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSM:
def __init__(self, vocab_size, embed_size, sentence_size):
"""@param vocab_size: 词表大小 embed_size:每个词向量的维度,相当于论文中的q sentence_size: 诗句的长度,5或7"""
<|body_0|>
def convolute(self, X, kernel):
"""论文中的卷积操作 @param X 形状是(batch_size, sentence_size, embed_size) kernel 形状是(h... | stack_v2_sparse_classes_75kplus_train_008997 | 1,985 | no_license | [
{
"docstring": "@param vocab_size: 词表大小 embed_size:每个词向量的维度,相当于论文中的q sentence_size: 诗句的长度,5或7",
"name": "__init__",
"signature": "def __init__(self, vocab_size, embed_size, sentence_size)"
},
{
"docstring": "论文中的卷积操作 @param X 形状是(batch_size, sentence_size, embed_size) kernel 形状是(h, embed_size) @... | 3 | null | Implement the Python class `CSM` described below.
Class description:
Implement the CSM class.
Method signatures and docstrings:
- def __init__(self, vocab_size, embed_size, sentence_size): @param vocab_size: 词表大小 embed_size:每个词向量的维度,相当于论文中的q sentence_size: 诗句的长度,5或7
- def convolute(self, X, kernel): 论文中的卷积操作 @param X... | Implement the Python class `CSM` described below.
Class description:
Implement the CSM class.
Method signatures and docstrings:
- def __init__(self, vocab_size, embed_size, sentence_size): @param vocab_size: 词表大小 embed_size:每个词向量的维度,相当于论文中的q sentence_size: 诗句的长度,5或7
- def convolute(self, X, kernel): 论文中的卷积操作 @param X... | ce5bb336605d1831724eaac90c221a32b4b55be1 | <|skeleton|>
class CSM:
def __init__(self, vocab_size, embed_size, sentence_size):
"""@param vocab_size: 词表大小 embed_size:每个词向量的维度,相当于论文中的q sentence_size: 诗句的长度,5或7"""
<|body_0|>
def convolute(self, X, kernel):
"""论文中的卷积操作 @param X 形状是(batch_size, sentence_size, embed_size) kernel 形状是(h... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CSM:
def __init__(self, vocab_size, embed_size, sentence_size):
"""@param vocab_size: 词表大小 embed_size:每个词向量的维度,相当于论文中的q sentence_size: 诗句的长度,5或7"""
super(CSM, self).__init__()
self.sentence_size = sentence_size
self.conv1 = nn.Parameter(torch.randn((2, embed_size)))
sel... | the_stack_v2_python_sparse | 整合/rnn/CSM.py | dromniscience/nlp_ai_2020 | train | 0 | |
0bc268e0959ebd52db661aadc09388190f61175c | [
"super(Linker_complex, self).__init__()\nself.config = config\nself.encoder = encoder\nself.entity_embeddings_real = nn.Embedding(self.config.entity_size, self.config.embedding_dim)\nself.entity_embeddings_img = nn.Embedding(self.config.entity_size, self.config.embedding_dim)\nif self.config.priors:\n self.char_... | <|body_start_0|>
super(Linker_complex, self).__init__()
self.config = config
self.encoder = encoder
self.entity_embeddings_real = nn.Embedding(self.config.entity_size, self.config.embedding_dim)
self.entity_embeddings_img = nn.Embedding(self.config.entity_size, self.config.embedd... | Linker_complex | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linker_complex:
def __init__(self, config, encoder):
""":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions"""
<|body_0|>
def forward(self, entity_candidates, mention_representation, sentence, char_sc... | stack_v2_sparse_classes_75kplus_train_008998 | 42,719 | permissive | [
{
"docstring": ":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions",
"name": "__init__",
"signature": "def __init__(self, config, encoder)"
},
{
"docstring": ":return: unnormalized log probabilities (logits) of gold enti... | 2 | stack_v2_sparse_classes_30k_train_035991 | Implement the Python class `Linker_complex` described below.
Class description:
Implement the Linker_complex class.
Method signatures and docstrings:
- def __init__(self, config, encoder): :param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions
- ... | Implement the Python class `Linker_complex` described below.
Class description:
Implement the Linker_complex class.
Method signatures and docstrings:
- def __init__(self, config, encoder): :param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions
- ... | 6a7dcd7d3756327c61ef949e5b4f6af6e2849187 | <|skeleton|>
class Linker_complex:
def __init__(self, config, encoder):
""":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions"""
<|body_0|>
def forward(self, entity_candidates, mention_representation, sentence, char_sc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Linker_complex:
def __init__(self, config, encoder):
""":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions"""
super(Linker_complex, self).__init__()
self.config = config
self.encoder = encoder
s... | the_stack_v2_python_sparse | typenet/src/model.py | dhruvdcoder/dl-with-constraints | train | 0 | |
bfdbc8eba6aaed9b09cddb141349a5b992d944aa | [
"super().__init__(coordinator)\nself.entity_description = SensorEntityDescription(key=account, name=f'steam_{account}', icon='mdi:steam')\nself._attr_unique_id = f'sensor.steam_{account}'",
"if self.entity_description.key in self.coordinator.data:\n player = self.coordinator.data[self.entity_description.key]\n... | <|body_start_0|>
super().__init__(coordinator)
self.entity_description = SensorEntityDescription(key=account, name=f'steam_{account}', icon='mdi:steam')
self._attr_unique_id = f'sensor.steam_{account}'
<|end_body_0|>
<|body_start_1|>
if self.entity_description.key in self.coordinator.da... | A class for the Steam account. | SteamSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SteamSensor:
"""A class for the Steam account."""
def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None:
"""Initialize the sensor."""
<|body_0|>
def native_value(self) -> StateType:
"""Return the state of the sensor."""
<|body_... | stack_v2_sparse_classes_75kplus_train_008999 | 3,561 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None"
},
{
"docstring": "Return the state of the sensor.",
"name": "native_value",
"signature": "def native_value(self) -> StateType"
... | 4 | stack_v2_sparse_classes_30k_train_015164 | Implement the Python class `SteamSensor` described below.
Class description:
A class for the Steam account.
Method signatures and docstrings:
- def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None: Initialize the sensor.
- def native_value(self) -> StateType: Return the state of the senso... | Implement the Python class `SteamSensor` described below.
Class description:
A class for the Steam account.
Method signatures and docstrings:
- def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None: Initialize the sensor.
- def native_value(self) -> StateType: Return the state of the senso... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SteamSensor:
"""A class for the Steam account."""
def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None:
"""Initialize the sensor."""
<|body_0|>
def native_value(self) -> StateType:
"""Return the state of the sensor."""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SteamSensor:
"""A class for the Steam account."""
def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self.entity_description = SensorEntityDescription(key=account, name=f'steam_{account}', i... | the_stack_v2_python_sparse | homeassistant/components/steam_online/sensor.py | home-assistant/core | train | 35,501 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.