blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6c19ab63d4d57f14cb3effe810195a952433acb7 | [
"outputs = conv1D_cuda(input, filter, bias, padding, index_back)\noutput = outputs[0]\nxfft, yfft, W, WW, fft_size = outputs[1:]\nif ctx:\n ctx.W = W\n ctx.WW = WW\n ctx.fft_size = fft_size\n ctx.save_for_backward(xfft, yfft)\nreturn output",
"xfft, yfft = ctx.saved_tensors\nW = ctx.W\nWW = ctx.WW\nff... | <|body_start_0|>
outputs = conv1D_cuda(input, filter, bias, padding, index_back)
output = outputs[0]
xfft, yfft, W, WW, fft_size = outputs[1:]
if ctx:
ctx.W = W
ctx.WW = WW
ctx.fft_size = fft_size
ctx.save_for_backward(xfft, yfft)
r... | Implement the 1D convolution via FFT with compression of the input map and the filter. | Conv1dfftFunctionCuda | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv1dfftFunctionCuda:
"""Implement the 1D convolution via FFT with compression of the input map and the filter."""
def forward(ctx, input, filter, bias=None, padding=None, index_back=None):
"""Compute the forward pass for the 1D convolution. :param ctx: context to save intermediate ... | stack_v2_sparse_classes_36k_train_031300 | 4,816 | permissive | [
{
"docstring": "Compute the forward pass for the 1D convolution. :param ctx: context to save intermediate results, in other words, a context object that can be used to stash information for backward computation :param input: the input map to the convolution (e.g. a time-series). The other parameters are similar... | 2 | stack_v2_sparse_classes_30k_train_007787 | Implement the Python class `Conv1dfftFunctionCuda` described below.
Class description:
Implement the 1D convolution via FFT with compression of the input map and the filter.
Method signatures and docstrings:
- def forward(ctx, input, filter, bias=None, padding=None, index_back=None): Compute the forward pass for the ... | Implement the Python class `Conv1dfftFunctionCuda` described below.
Class description:
Implement the 1D convolution via FFT with compression of the input map and the filter.
Method signatures and docstrings:
- def forward(ctx, input, filter, bias=None, padding=None, index_back=None): Compute the forward pass for the ... | 81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a | <|skeleton|>
class Conv1dfftFunctionCuda:
"""Implement the 1D convolution via FFT with compression of the input map and the filter."""
def forward(ctx, input, filter, bias=None, padding=None, index_back=None):
"""Compute the forward pass for the 1D convolution. :param ctx: context to save intermediate ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conv1dfftFunctionCuda:
"""Implement the 1D convolution via FFT with compression of the input map and the filter."""
def forward(ctx, input, filter, bias=None, padding=None, index_back=None):
"""Compute the forward pass for the 1D convolution. :param ctx: context to save intermediate results, in o... | the_stack_v2_python_sparse | cnns/nnlib/pytorch_layers/conv1D_cuda/conv.py | adam-dziedzic/bandlimited-cnns | train | 17 |
14ec508165c847208ce145afee0e95f12258c64d | [
"n = len(nums)\nfor i in range(0, n - 1):\n y = target - nums[i]\n for j in range(i + 1, n):\n if y == nums[j]:\n return [i, j]\nreturn []",
"seen = dict()\nfor i, x in enumerate(nums):\n y = target - x\n if y in seen:\n j = seen[y]\n return [j, i]\n seen[x] = i\nret... | <|body_start_0|>
n = len(nums)
for i in range(0, n - 1):
y = target - nums[i]
for j in range(i + 1, n):
if y == nums[j]:
return [i, j]
return []
<|end_body_0|>
<|body_start_1|>
seen = dict()
for i, x in enumerate(nums):... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_v1(self, nums: List[int], target: int) -> List[int]:
"""Use a nested loop."""
<|body_0|>
def twoSum_v2(self, nums: List[int], target: int) -> List[int]:
"""Use a dictionary to speed up the process. This versin is fast."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_031301 | 2,250 | no_license | [
{
"docstring": "Use a nested loop.",
"name": "twoSum_v1",
"signature": "def twoSum_v1(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "Use a dictionary to speed up the process. This versin is fast.",
"name": "twoSum_v2",
"signature": "def twoSum_v2(self, nums: List[in... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_v1(self, nums: List[int], target: int) -> List[int]: Use a nested loop.
- def twoSum_v2(self, nums: List[int], target: int) -> List[int]: Use a dictionary to speed up ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_v1(self, nums: List[int], target: int) -> List[int]: Use a nested loop.
- def twoSum_v2(self, nums: List[int], target: int) -> List[int]: Use a dictionary to speed up ... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def twoSum_v1(self, nums: List[int], target: int) -> List[int]:
"""Use a nested loop."""
<|body_0|>
def twoSum_v2(self, nums: List[int], target: int) -> List[int]:
"""Use a dictionary to speed up the process. This versin is fast."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum_v1(self, nums: List[int], target: int) -> List[int]:
"""Use a nested loop."""
n = len(nums)
for i in range(0, n - 1):
y = target - nums[i]
for j in range(i + 1, n):
if y == nums[j]:
return [i, j]
r... | the_stack_v2_python_sparse | python3/string_array/two_sum.py | victorchu/algorithms | train | 0 | |
2e7282e735f1c82347a1486d95e6a1e25ae956ae | [
"try:\n ds_orig = self._do_stage\n self._do_stage = functools.partial(self.__do_stage, _ds=ds_orig)\n super(Deinstall, self).work()\nfinally:\n self._do_stage = ds_orig",
"if self.port.install_status == pkg.ABSENT:\n self._do_stage = _ds\n self._do_stage()\nelse:\n self.port.install_status = ... | <|body_start_0|>
try:
ds_orig = self._do_stage
self._do_stage = functools.partial(self.__do_stage, _ds=ds_orig)
super(Deinstall, self).work()
finally:
self._do_stage = ds_orig
<|end_body_0|>
<|body_start_1|>
if self.port.install_status == pkg.ABSE... | Deinstall a port's packages before doing the stage. | Deinstall | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Deinstall:
"""Deinstall a port's packages before doing the stage."""
def work(self):
"""Deinstall the port's package before continuing with the stage."""
<|body_0|>
def __do_stage(self, _ds):
"""Issue a pkg.remove() or proceed with the stage."""
<|body_1|... | stack_v2_sparse_classes_36k_train_031302 | 5,619 | permissive | [
{
"docstring": "Deinstall the port's package before continuing with the stage.",
"name": "work",
"signature": "def work(self)"
},
{
"docstring": "Issue a pkg.remove() or proceed with the stage.",
"name": "__do_stage",
"signature": "def __do_stage(self, _ds)"
},
{
"docstring": "Pr... | 3 | stack_v2_sparse_classes_30k_train_016287 | Implement the Python class `Deinstall` described below.
Class description:
Deinstall a port's packages before doing the stage.
Method signatures and docstrings:
- def work(self): Deinstall the port's package before continuing with the stage.
- def __do_stage(self, _ds): Issue a pkg.remove() or proceed with the stage.... | Implement the Python class `Deinstall` described below.
Class description:
Deinstall a port's packages before doing the stage.
Method signatures and docstrings:
- def work(self): Deinstall the port's package before continuing with the stage.
- def __do_stage(self, _ds): Issue a pkg.remove() or proceed with the stage.... | 1d0041382dc68738018401cdda2e69836a534e1d | <|skeleton|>
class Deinstall:
"""Deinstall a port's packages before doing the stage."""
def work(self):
"""Deinstall the port's package before continuing with the stage."""
<|body_0|>
def __do_stage(self, _ds):
"""Issue a pkg.remove() or proceed with the stage."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Deinstall:
"""Deinstall a port's packages before doing the stage."""
def work(self):
"""Deinstall the port's package before continuing with the stage."""
try:
ds_orig = self._do_stage
self._do_stage = functools.partial(self.__do_stage, _ds=ds_orig)
supe... | the_stack_v2_python_sparse | libpb/stacks/mutators.py | DragonSA/portbuilder | train | 10 |
17af97c1b2350a2b9299788d2423628893ae3c59 | [
"print('init vtkAnimCameraAroundZ')\nvtkAnimation.__init__(self, t)\nself.turn = turn\nself.time_anim_ends = t + abs(self.turn) / 10\nprint('time_anim_starts', self.time_anim_starts)\nprint('time_anim_ends', self.time_anim_ends)\nprint('turn', self.turn)\nself.camera = cam",
"do = vtkAnimation.pre_execute(self)\n... | <|body_start_0|>
print('init vtkAnimCameraAroundZ')
vtkAnimation.__init__(self, t)
self.turn = turn
self.time_anim_ends = t + abs(self.turn) / 10
print('time_anim_starts', self.time_anim_starts)
print('time_anim_ends', self.time_anim_ends)
print('turn', self.turn)... | Animate the camera around the vertical axis. This class can be used to generate a series of images (default 36) while the camera rotate around the vertical axis (defined by the camera SetViewUp method). | vtkAnimCameraAroundZ | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class vtkAnimCameraAroundZ:
"""Animate the camera around the vertical axis. This class can be used to generate a series of images (default 36) while the camera rotate around the vertical axis (defined by the camera SetViewUp method)."""
def __init__(self, t, cam, turn=360):
"""Initialize t... | stack_v2_sparse_classes_36k_train_031303 | 12,455 | permissive | [
{
"docstring": "Initialize the animation. The animation perform a full turn in 36 frames by default.",
"name": "__init__",
"signature": "def __init__(self, t, cam, turn=360)"
},
{
"docstring": "Execute method called to rotate the camera.",
"name": "execute",
"signature": "def execute(sel... | 2 | stack_v2_sparse_classes_30k_train_002844 | Implement the Python class `vtkAnimCameraAroundZ` described below.
Class description:
Animate the camera around the vertical axis. This class can be used to generate a series of images (default 36) while the camera rotate around the vertical axis (defined by the camera SetViewUp method).
Method signatures and docstri... | Implement the Python class `vtkAnimCameraAroundZ` described below.
Class description:
Animate the camera around the vertical axis. This class can be used to generate a series of images (default 36) while the camera rotate around the vertical axis (defined by the camera SetViewUp method).
Method signatures and docstri... | c1546b7a8925fd1b2e887beb8bf1f86e2a40216f | <|skeleton|>
class vtkAnimCameraAroundZ:
"""Animate the camera around the vertical axis. This class can be used to generate a series of images (default 36) while the camera rotate around the vertical axis (defined by the camera SetViewUp method)."""
def __init__(self, t, cam, turn=360):
"""Initialize t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class vtkAnimCameraAroundZ:
"""Animate the camera around the vertical axis. This class can be used to generate a series of images (default 36) while the camera rotate around the vertical axis (defined by the camera SetViewUp method)."""
def __init__(self, t, cam, turn=360):
"""Initialize the animation.... | the_stack_v2_python_sparse | pymicro/view/vtk_anim.py | heprom/pymicro | train | 39 |
feeb2dffb2ece069fe6fdedd8b456f797a9b8564 | [
"arr, path = ([], '')\nself.recursion(root, path, arr)\nreturn [col for col in arr if sum(col) == summary]",
"if root:\n path += str(root.val) + ','\n if not root.left and (not root.right):\n arr.append([int(node) for node in path.split(',') if node != ''])\n path = ''\n self.recursion(root... | <|body_start_0|>
arr, path = ([], '')
self.recursion(root, path, arr)
return [col for col in arr if sum(col) == summary]
<|end_body_0|>
<|body_start_1|>
if root:
path += str(root.val) + ','
if not root.left and (not root.right):
arr.append([int(no... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root, summary):
""":type root: TreeNode :type summary: int :rtype: List[List[int]]"""
<|body_0|>
def recursion(self, root, path, arr):
""":param root: :param path: :param arr: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_031304 | 915 | no_license | [
{
"docstring": ":type root: TreeNode :type summary: int :rtype: List[List[int]]",
"name": "pathSum",
"signature": "def pathSum(self, root, summary)"
},
{
"docstring": ":param root: :param path: :param arr: :return:",
"name": "recursion",
"signature": "def recursion(self, root, path, arr)... | 2 | stack_v2_sparse_classes_30k_train_013561 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, summary): :type root: TreeNode :type summary: int :rtype: List[List[int]]
- def recursion(self, root, path, arr): :param root: :param path: :param arr: :r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, summary): :type root: TreeNode :type summary: int :rtype: List[List[int]]
- def recursion(self, root, path, arr): :param root: :param path: :param arr: :r... | b38cc7d24c85ef6e7a1342d7ae0054f6c663e600 | <|skeleton|>
class Solution:
def pathSum(self, root, summary):
""":type root: TreeNode :type summary: int :rtype: List[List[int]]"""
<|body_0|>
def recursion(self, root, path, arr):
""":param root: :param path: :param arr: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum(self, root, summary):
""":type root: TreeNode :type summary: int :rtype: List[List[int]]"""
arr, path = ([], '')
self.recursion(root, path, arr)
return [col for col in arr if sum(col) == summary]
def recursion(self, root, path, arr):
""":param... | the_stack_v2_python_sparse | 101~200/113.py | strategist922/leetcode-5 | train | 0 | |
78d14cf55078c93108950c6e5aef9377914cdd2b | [
"if root:\n head, tail = self.helper(root)\n return head\nreturn None",
"head, tail = (root, root)\nif root.left:\n lh, lt = self.helper(root.left)\n lt.right = root\n root.left = lt\n head = lh\nif root.right:\n rh, rt = self.helper(root.right)\n rh.left = root\n root.right = rh\n t... | <|body_start_0|>
if root:
head, tail = self.helper(root)
return head
return None
<|end_body_0|>
<|body_start_1|>
head, tail = (root, root)
if root.left:
lh, lt = self.helper(root.left)
lt.right = root
root.left = lt
... | Solution3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution3:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node"""
<|body_0|>
def helper(self, root):
"""Idea: Construct a DLL for each subtree, then return the head and tail"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root:
... | stack_v2_sparse_classes_36k_train_031305 | 3,060 | no_license | [
{
"docstring": ":type root: Node :rtype: Node",
"name": "treeToDoublyList",
"signature": "def treeToDoublyList(self, root)"
},
{
"docstring": "Idea: Construct a DLL for each subtree, then return the head and tail",
"name": "helper",
"signature": "def helper(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008896 | Implement the Python class `Solution3` described below.
Class description:
Implement the Solution3 class.
Method signatures and docstrings:
- def treeToDoublyList(self, root): :type root: Node :rtype: Node
- def helper(self, root): Idea: Construct a DLL for each subtree, then return the head and tail | Implement the Python class `Solution3` described below.
Class description:
Implement the Solution3 class.
Method signatures and docstrings:
- def treeToDoublyList(self, root): :type root: Node :rtype: Node
- def helper(self, root): Idea: Construct a DLL for each subtree, then return the head and tail
<|skeleton|>
cl... | 11d6bf2ba7b50c07e048df37c4e05c8f46b92241 | <|skeleton|>
class Solution3:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node"""
<|body_0|>
def helper(self, root):
"""Idea: Construct a DLL for each subtree, then return the head and tail"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution3:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node"""
if root:
head, tail = self.helper(root)
return head
return None
def helper(self, root):
"""Idea: Construct a DLL for each subtree, then return the head and tail"""
... | the_stack_v2_python_sparse | LeetCodes/facebook/Convert Binary SearchTreetoSortedDoublyLinkedList.py | chutianwen/LeetCodes | train | 0 | |
50fdbde31667d08178d009ec1db4541d28f8761a | [
"if len(s3) != len(s1) + len(s2):\n return False\nm, n = (len(s1), len(s2))\ndp = [[False] * (n + 1) for _ in range(m + 1)]\ndp[0][0] = True\nfor i in range(1, m + 1):\n dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1]\nfor j in range(1, n + 1):\n dp[0][j] = dp[0][j - 1] and s2[j - 1] == s3[j - 1]\nfor i... | <|body_start_0|>
if len(s3) != len(s1) + len(s2):
return False
m, n = (len(s1), len(s2))
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
for i in range(1, m + 1):
dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1]
for j in range(1, n... | Solution | [
"WTFPL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
"""DP"""
<|body_0|>
def isInterleave2(self, s1: str, s2: str, s3: str) -> bool:
"""DFS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(s3) != len(s1) + len(s2):
... | stack_v2_sparse_classes_36k_train_031306 | 1,437 | permissive | [
{
"docstring": "DP",
"name": "isInterleave",
"signature": "def isInterleave(self, s1: str, s2: str, s3: str) -> bool"
},
{
"docstring": "DFS",
"name": "isInterleave2",
"signature": "def isInterleave2(self, s1: str, s2: str, s3: str) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_001036 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isInterleave(self, s1: str, s2: str, s3: str) -> bool: DP
- def isInterleave2(self, s1: str, s2: str, s3: str) -> bool: DFS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isInterleave(self, s1: str, s2: str, s3: str) -> bool: DP
- def isInterleave2(self, s1: str, s2: str, s3: str) -> bool: DFS
<|skeleton|>
class Solution:
def isInterleav... | 5e5e7098d2310c972314c9c9895aafd048047fe6 | <|skeleton|>
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
"""DP"""
<|body_0|>
def isInterleave2(self, s1: str, s2: str, s3: str) -> bool:
"""DFS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
"""DP"""
if len(s3) != len(s1) + len(s2):
return False
m, n = (len(s1), len(s2))
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
for i in range(1, m + 1):
... | the_stack_v2_python_sparse | 0097_Interleaving_String.py | imguozr/LC-Solutions | train | 0 | |
db4429045801388bbfc1be193371cc25ddc2d17e | [
"super(LMFinetune, self).__init__(opt)\nself.lm_model = lm_model\nself.lm_model.to(device=self.device)",
"de_rewards = super(LMFinetune, self).get_rewards(de_batch_results, trans_en, trans_en_lengths)\nenglishness = self.lm_model.get_lm_reward(trans_en, trans_en_lengths)\nrewards = de_rewards + self.opt.lm_coeff ... | <|body_start_0|>
super(LMFinetune, self).__init__(opt)
self.lm_model = lm_model
self.lm_model.to(device=self.device)
<|end_body_0|>
<|body_start_1|>
de_rewards = super(LMFinetune, self).get_rewards(de_batch_results, trans_en, trans_en_lengths)
englishness = self.lm_model.get_lm_... | Trainer with Language Model | LMFinetune | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LMFinetune:
"""Trainer with Language Model"""
def __init__(self, opt, lm_model):
"""Constructor"""
<|body_0|>
def get_rewards(self, de_batch_results, trans_en, trans_en_lengths):
"""Return the rewards"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_031307 | 24,529 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, opt, lm_model)"
},
{
"docstring": "Return the rewards",
"name": "get_rewards",
"signature": "def get_rewards(self, de_batch_results, trans_en, trans_en_lengths)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000366 | Implement the Python class `LMFinetune` described below.
Class description:
Trainer with Language Model
Method signatures and docstrings:
- def __init__(self, opt, lm_model): Constructor
- def get_rewards(self, de_batch_results, trans_en, trans_en_lengths): Return the rewards | Implement the Python class `LMFinetune` described below.
Class description:
Trainer with Language Model
Method signatures and docstrings:
- def __init__(self, opt, lm_model): Constructor
- def get_rewards(self, de_batch_results, trans_en, trans_en_lengths): Return the rewards
<|skeleton|>
class LMFinetune:
"""Tr... | 858559c7e39ad82a87ac2546162c7dbadf7d4de8 | <|skeleton|>
class LMFinetune:
"""Trainer with Language Model"""
def __init__(self, opt, lm_model):
"""Constructor"""
<|body_0|>
def get_rewards(self, de_batch_results, trans_en, trans_en_lengths):
"""Return the rewards"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LMFinetune:
"""Trainer with Language Model"""
def __init__(self, opt, lm_model):
"""Constructor"""
super(LMFinetune, self).__init__(opt)
self.lm_model = lm_model
self.lm_model.to(device=self.device)
def get_rewards(self, de_batch_results, trans_en, trans_en_lengths):
... | the_stack_v2_python_sparse | ld_research/training/finetune.py | JACKHAHA363/translation_game_drift | train | 2 |
d034dccccfa15c62ae5986af406f6ea4028dd84c | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"choise_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\ndirection = choice([1, -1])\ndistance = choice(choise_list)\nstep = direction * distance\nreturn step",
"while len(self.x_values) < self.num_points:\n x_step = self.get_step()\n y_step ... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
choise_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
direction = choice([1, -1])
distance = choice(choise_list)
step = direction * distance
retur... | 一个生成随机漫步数据的类 | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
<|body_0|>
def get_step(self):
"""确定漫步的距离和方向"""
<|body_1|>
def fill_walk(self):
"""计算随机漫步包含的所有点"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_031308 | 1,449 | no_license | [
{
"docstring": "初始化随机漫步的属性",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "确定漫步的距离和方向",
"name": "get_step",
"signature": "def get_step(self)"
},
{
"docstring": "计算随机漫步包含的所有点",
"name": "fill_walk",
"signature": "def fill_walk(sel... | 3 | stack_v2_sparse_classes_30k_train_010305 | Implement the Python class `RandomWalk` described below.
Class description:
一个生成随机漫步数据的类
Method signatures and docstrings:
- def __init__(self, num_points=5000): 初始化随机漫步的属性
- def get_step(self): 确定漫步的距离和方向
- def fill_walk(self): 计算随机漫步包含的所有点 | Implement the Python class `RandomWalk` described below.
Class description:
一个生成随机漫步数据的类
Method signatures and docstrings:
- def __init__(self, num_points=5000): 初始化随机漫步的属性
- def get_step(self): 确定漫步的距离和方向
- def fill_walk(self): 计算随机漫步包含的所有点
<|skeleton|>
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(sel... | 5aa4f0adbec0176cee8cc73a27eb02a95469d651 | <|skeleton|>
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
<|body_0|>
def get_step(self):
"""确定漫步的距离和方向"""
<|body_1|>
def fill_walk(self):
"""计算随机漫步包含的所有点"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def get_step(self):
"""确定漫步的距离和方向"""
choise_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
directio... | the_stack_v2_python_sparse | random_walk/random_walk.py | chenlfc/learnPython | train | 0 |
50a2241e571b188277e4497d3c0965683db3acda | [
"self.lock = Lock()\nself.lock.acquire()\nself.value = Exception()\nself.raised = False",
"self.value = value\nself.raised = raised\nself.lock.release()",
"self.lock.acquire()\ntry:\n if self.raised:\n raise self.value\n return self.value\nfinally:\n self.lock.release()"
] | <|body_start_0|>
self.lock = Lock()
self.lock.acquire()
self.value = Exception()
self.raised = False
<|end_body_0|>
<|body_start_1|>
self.value = value
self.raised = raised
self.lock.release()
<|end_body_1|>
<|body_start_2|>
self.lock.acquire()
t... | Used to communicate job result values and exceptions. | Result | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Result:
"""Used to communicate job result values and exceptions."""
def __init__(self):
"""Initialize."""
<|body_0|>
def put(self, value, raised):
"""Worker puts value or exception into result. Args: value (object): A value or exception. raised (bool): Whether ex... | stack_v2_sparse_classes_36k_train_031309 | 3,470 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Worker puts value or exception into result. Args: value (object): A value or exception. raised (bool): Whether exception was raised.",
"name": "put",
"signature": "def put(self, value, ... | 3 | null | Implement the Python class `Result` described below.
Class description:
Used to communicate job result values and exceptions.
Method signatures and docstrings:
- def __init__(self): Initialize.
- def put(self, value, raised): Worker puts value or exception into result. Args: value (object): A value or exception. rais... | Implement the Python class `Result` described below.
Class description:
Used to communicate job result values and exceptions.
Method signatures and docstrings:
- def __init__(self): Initialize.
- def put(self, value, raised): Worker puts value or exception into result. Args: value (object): A value or exception. rais... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class Result:
"""Used to communicate job result values and exceptions."""
def __init__(self):
"""Initialize."""
<|body_0|>
def put(self, value, raised):
"""Worker puts value or exception into result. Args: value (object): A value or exception. raised (bool): Whether ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Result:
"""Used to communicate job result values and exceptions."""
def __init__(self):
"""Initialize."""
self.lock = Lock()
self.lock.acquire()
self.value = Exception()
self.raised = False
def put(self, value, raised):
"""Worker puts value or exceptio... | the_stack_v2_python_sparse | google/cloud/forseti/common/util/threadpool.py | kevensen/forseti-security | train | 1 |
aaa6d4aefaa30e3f711ea2793a4ec33fd2a046f8 | [
"image = self.images.first()\nif image:\n return image.url\nreturn image",
"user = self.user\ntry:\n return user.standardmethod_set.filter(origin=self.location, country=to_location.country, zipcode_start__lte=int(to_location.zip_code), zipcode_end__gte=int(to_location.zip_code)).first()\nexcept AttributeErr... | <|body_start_0|>
image = self.images.first()
if image:
return image.url
return image
<|end_body_0|>
<|body_start_1|>
user = self.user
try:
return user.standardmethod_set.filter(origin=self.location, country=to_location.country, zipcode_start__lte=int(to_l... | Class to store Product information .. note:: Can not be deleted, use ``Product.is_active`` to make it unusable | Product | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Product:
"""Class to store Product information .. note:: Can not be deleted, use ``Product.is_active`` to make it unusable"""
def image(self):
"""Shortcut property to get first image."""
<|body_0|>
def get_standard_shipping_method(self, to_location):
"""Get stand... | stack_v2_sparse_classes_36k_train_031310 | 6,080 | no_license | [
{
"docstring": "Shortcut property to get first image.",
"name": "image",
"signature": "def image(self)"
},
{
"docstring": "Get standard shipping object available to to_location",
"name": "get_standard_shipping_method",
"signature": "def get_standard_shipping_method(self, to_location)"
... | 2 | stack_v2_sparse_classes_30k_test_000216 | Implement the Python class `Product` described below.
Class description:
Class to store Product information .. note:: Can not be deleted, use ``Product.is_active`` to make it unusable
Method signatures and docstrings:
- def image(self): Shortcut property to get first image.
- def get_standard_shipping_method(self, to... | Implement the Python class `Product` described below.
Class description:
Class to store Product information .. note:: Can not be deleted, use ``Product.is_active`` to make it unusable
Method signatures and docstrings:
- def image(self): Shortcut property to get first image.
- def get_standard_shipping_method(self, to... | 3129d0fc500b68e565d3f21b7878d70522829bf3 | <|skeleton|>
class Product:
"""Class to store Product information .. note:: Can not be deleted, use ``Product.is_active`` to make it unusable"""
def image(self):
"""Shortcut property to get first image."""
<|body_0|>
def get_standard_shipping_method(self, to_location):
"""Get stand... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Product:
"""Class to store Product information .. note:: Can not be deleted, use ``Product.is_active`` to make it unusable"""
def image(self):
"""Shortcut property to get first image."""
image = self.images.first()
if image:
return image.url
return image
d... | the_stack_v2_python_sparse | src/catalog/models.py | SIXBYSIX-LLC/bg-api | train | 1 |
e7aa0b6eb1d4a9a2d688527ad4fa9815442913db | [
"assert isinstance(action_space, gym_open_ai.spaces.Discrete), 'ShootingAgent only works with Discrete action spaces.'\nsuper().__init__(action_space)\nself._n_rollouts = n_rollouts\nself._rollout_time_limit = rollout_time_limit\nself._aggregate_fn = aggregate_fn\nself._batch_stepper_class = batch_stepper_class\nse... | <|body_start_0|>
assert isinstance(action_space, gym_open_ai.spaces.Discrete), 'ShootingAgent only works with Discrete action spaces.'
super().__init__(action_space)
self._n_rollouts = n_rollouts
self._rollout_time_limit = rollout_time_limit
self._aggregate_fn = aggregate_fn
... | Monte Carlo simulation agent. | ShootingAgent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShootingAgent:
"""Monte Carlo simulation agent."""
def __init__(self, action_space, n_rollouts=1000, rollout_time_limit=None, aggregate_fn=mean_aggregate, batch_stepper_class=batch_steppers.LocalBatchStepper, agent_class=core.RandomAgent, n_envs=10):
"""Initializes ShootingAgent. Arg... | stack_v2_sparse_classes_36k_train_031311 | 4,123 | permissive | [
{
"docstring": "Initializes ShootingAgent. Args: action_space (gym.Space): Action space. n_rollouts (int): Do at least this number of MC rollouts per act(). rollout_time_limit (int): Maximum number of timesteps for rollouts. aggregate_fn (callable): Aggregates simulated episodes. Signature: (n_act, episodes) ->... | 3 | null | Implement the Python class `ShootingAgent` described below.
Class description:
Monte Carlo simulation agent.
Method signatures and docstrings:
- def __init__(self, action_space, n_rollouts=1000, rollout_time_limit=None, aggregate_fn=mean_aggregate, batch_stepper_class=batch_steppers.LocalBatchStepper, agent_class=cor... | Implement the Python class `ShootingAgent` described below.
Class description:
Monte Carlo simulation agent.
Method signatures and docstrings:
- def __init__(self, action_space, n_rollouts=1000, rollout_time_limit=None, aggregate_fn=mean_aggregate, batch_stepper_class=batch_steppers.LocalBatchStepper, agent_class=cor... | aeb00605e105628188143a4bbd6280e9eb41c4f9 | <|skeleton|>
class ShootingAgent:
"""Monte Carlo simulation agent."""
def __init__(self, action_space, n_rollouts=1000, rollout_time_limit=None, aggregate_fn=mean_aggregate, batch_stepper_class=batch_steppers.LocalBatchStepper, agent_class=core.RandomAgent, n_envs=10):
"""Initializes ShootingAgent. Arg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShootingAgent:
"""Monte Carlo simulation agent."""
def __init__(self, action_space, n_rollouts=1000, rollout_time_limit=None, aggregate_fn=mean_aggregate, batch_stepper_class=batch_steppers.LocalBatchStepper, agent_class=core.RandomAgent, n_envs=10):
"""Initializes ShootingAgent. Args: action_spa... | the_stack_v2_python_sparse | alpaca/alpacka/agents/shooting.py | TomaszOdrzygozdz/gym-splendor | train | 1 |
cf39426be9c4b52c2142987285d1d0ced82e3753 | [
"self.fixed_threshold = fixed_threshold\nself.pattern_type = pattern_type\nself.throttling_windows = throttling_windows",
"if dictionary is None:\n return None\nfixed_threshold = dictionary.get('fixedThreshold')\npattern_type = dictionary.get('patternType')\nthrottling_windows = None\nif dictionary.get('thrott... | <|body_start_0|>
self.fixed_threshold = fixed_threshold
self.pattern_type = pattern_type
self.throttling_windows = throttling_windows
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
fixed_threshold = dictionary.get('fixedThreshold')
pattern... | Implementation of the 'ThrottlingConfiguration' model. TODO: type description here. Attributes: fixed_threshold (long|int): Fixed baseline threshold for throttling. This is mandatory for any other throttling type than kNoThrottling. pattern_type (int): Type of the throttling pattern. throttling_windows (list of Throttl... | ThrottlingConfiguration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThrottlingConfiguration:
"""Implementation of the 'ThrottlingConfiguration' model. TODO: type description here. Attributes: fixed_threshold (long|int): Fixed baseline threshold for throttling. This is mandatory for any other throttling type than kNoThrottling. pattern_type (int): Type of the thro... | stack_v2_sparse_classes_36k_train_031312 | 2,449 | permissive | [
{
"docstring": "Constructor for the ThrottlingConfiguration class",
"name": "__init__",
"signature": "def __init__(self, fixed_threshold=None, pattern_type=None, throttling_windows=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dict... | 2 | null | Implement the Python class `ThrottlingConfiguration` described below.
Class description:
Implementation of the 'ThrottlingConfiguration' model. TODO: type description here. Attributes: fixed_threshold (long|int): Fixed baseline threshold for throttling. This is mandatory for any other throttling type than kNoThrottlin... | Implement the Python class `ThrottlingConfiguration` described below.
Class description:
Implementation of the 'ThrottlingConfiguration' model. TODO: type description here. Attributes: fixed_threshold (long|int): Fixed baseline threshold for throttling. This is mandatory for any other throttling type than kNoThrottlin... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ThrottlingConfiguration:
"""Implementation of the 'ThrottlingConfiguration' model. TODO: type description here. Attributes: fixed_threshold (long|int): Fixed baseline threshold for throttling. This is mandatory for any other throttling type than kNoThrottling. pattern_type (int): Type of the thro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThrottlingConfiguration:
"""Implementation of the 'ThrottlingConfiguration' model. TODO: type description here. Attributes: fixed_threshold (long|int): Fixed baseline threshold for throttling. This is mandatory for any other throttling type than kNoThrottling. pattern_type (int): Type of the throttling patter... | the_stack_v2_python_sparse | cohesity_management_sdk/models/throttling_configuration.py | cohesity/management-sdk-python | train | 24 |
6a153b4f0ed1d50bede1bdc3be7752c7ee772ded | [
"try:\n if g.user is None or g.user.is_anonymous:\n return self.response_401()\nexcept NoAuthorizationError:\n return self.response_401()\nreturn self.response(200, result=user_response_schema.dump(g.user))",
"try:\n if g.user is None or g.user.is_anonymous:\n return self.response_401()\nex... | <|body_start_0|>
try:
if g.user is None or g.user.is_anonymous:
return self.response_401()
except NoAuthorizationError:
return self.response_401()
return self.response(200, result=user_response_schema.dump(g.user))
<|end_body_0|>
<|body_start_1|>
... | An api to get information about the current user | CurrentUserRestApi | [
"Apache-2.0",
"OFL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurrentUserRestApi:
"""An api to get information about the current user"""
def get_me(self) -> Response:
"""Get the user object corresponding to the agent making the request --- get: description: >- Returns the user object corresponding to the agent making the request, or returns a 4... | stack_v2_sparse_classes_36k_train_031313 | 3,395 | permissive | [
{
"docstring": "Get the user object corresponding to the agent making the request --- get: description: >- Returns the user object corresponding to the agent making the request, or returns a 401 error if the user is unauthenticated. responses: 200: description: The current user content: application/json: schema... | 2 | null | Implement the Python class `CurrentUserRestApi` described below.
Class description:
An api to get information about the current user
Method signatures and docstrings:
- def get_me(self) -> Response: Get the user object corresponding to the agent making the request --- get: description: >- Returns the user object corr... | Implement the Python class `CurrentUserRestApi` described below.
Class description:
An api to get information about the current user
Method signatures and docstrings:
- def get_me(self) -> Response: Get the user object corresponding to the agent making the request --- get: description: >- Returns the user object corr... | 0945d4a2f46667aebb9b93d0d7685215627ad237 | <|skeleton|>
class CurrentUserRestApi:
"""An api to get information about the current user"""
def get_me(self) -> Response:
"""Get the user object corresponding to the agent making the request --- get: description: >- Returns the user object corresponding to the agent making the request, or returns a 4... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CurrentUserRestApi:
"""An api to get information about the current user"""
def get_me(self) -> Response:
"""Get the user object corresponding to the agent making the request --- get: description: >- Returns the user object corresponding to the agent making the request, or returns a 401 error if t... | the_stack_v2_python_sparse | superset/views/users/api.py | apache-superset/incubator-superset | train | 21 |
7a495f97b15d3a5c9895fd3f8765b1eae6433ca2 | [
"super().__init__(parent)\nself._tree = parent\nself._lastRect = QRect()",
"super().paint(painter, option, index)\nif index.data(BookmarksModel.TypeRole) == BookmarkItem.Separator:\n opt = QStyleOption(option)\n opt.state &= ~QStyle.State_Horizontal\n if self._tree.model().columnCount(index) == 2:\n ... | <|body_start_0|>
super().__init__(parent)
self._tree = parent
self._lastRect = QRect()
<|end_body_0|>
<|body_start_1|>
super().paint(painter, option, index)
if index.data(BookmarksModel.TypeRole) == BookmarkItem.Separator:
opt = QStyleOption(option)
opt.s... | BookmarksItemDelegate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookmarksItemDelegate:
def __init__(self, parent=None):
"""@param: parent QTreeView"""
<|body_0|>
def paint(self, painter, option, index):
"""@param: painter QPainter @param: option QStyleOptionViewItem @param: index QModelIndex"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_031314 | 1,384 | permissive | [
{
"docstring": "@param: parent QTreeView",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "@param: painter QPainter @param: option QStyleOptionViewItem @param: index QModelIndex",
"name": "paint",
"signature": "def paint(self, painter, option, index)... | 2 | null | Implement the Python class `BookmarksItemDelegate` described below.
Class description:
Implement the BookmarksItemDelegate class.
Method signatures and docstrings:
- def __init__(self, parent=None): @param: parent QTreeView
- def paint(self, painter, option, index): @param: painter QPainter @param: option QStyleOptio... | Implement the Python class `BookmarksItemDelegate` described below.
Class description:
Implement the BookmarksItemDelegate class.
Method signatures and docstrings:
- def __init__(self, parent=None): @param: parent QTreeView
- def paint(self, painter, option, index): @param: painter QPainter @param: option QStyleOptio... | bc2b60aa21c9b136439bd57a11f391d68c736f99 | <|skeleton|>
class BookmarksItemDelegate:
def __init__(self, parent=None):
"""@param: parent QTreeView"""
<|body_0|>
def paint(self, painter, option, index):
"""@param: painter QPainter @param: option QStyleOptionViewItem @param: index QModelIndex"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookmarksItemDelegate:
def __init__(self, parent=None):
"""@param: parent QTreeView"""
super().__init__(parent)
self._tree = parent
self._lastRect = QRect()
def paint(self, painter, option, index):
"""@param: painter QPainter @param: option QStyleOptionViewItem @pa... | the_stack_v2_python_sparse | mc/bookmarks/BookmarksItemDelegate.py | zy-sunshine/falkon-pyqt5 | train | 1 | |
740a08a2d13f21b2d2207e5ba94cabce294b0b7c | [
"super(KernelFixed, self).__init__()\nself.embd_dim = embd_dim\nself.hidden_dim = hidden_dim\nself.kernel_dim = kernel_dim\nself.layer1 = nn.Linear(2 * embd_dim, hidden_dim)\nself.layer2 = nn.Linear(hidden_dim, hidden_dim)\nself.layer3 = nn.Linear(hidden_dim, kernel_dim)\nself.net = nn.Sequential(self.layer1, nn.Re... | <|body_start_0|>
super(KernelFixed, self).__init__()
self.embd_dim = embd_dim
self.hidden_dim = hidden_dim
self.kernel_dim = kernel_dim
self.layer1 = nn.Linear(2 * embd_dim, hidden_dim)
self.layer2 = nn.Linear(hidden_dim, hidden_dim)
self.layer3 = nn.Linear(hidden... | KernelFixed | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KernelFixed:
def __init__(self, embd_dim, hidden_dim, kernel_dim):
"""Currently, this creates a 2-hidden-layer network with ELU non-linearities."""
<|body_0|>
def forward(self, words):
"""Given words returns kernel of dimension [batch_size, set_size, kernel_dim]"""
... | stack_v2_sparse_classes_36k_train_031315 | 30,546 | permissive | [
{
"docstring": "Currently, this creates a 2-hidden-layer network with ELU non-linearities.",
"name": "__init__",
"signature": "def __init__(self, embd_dim, hidden_dim, kernel_dim)"
},
{
"docstring": "Given words returns kernel of dimension [batch_size, set_size, kernel_dim]",
"name": "forwar... | 2 | stack_v2_sparse_classes_30k_train_003828 | Implement the Python class `KernelFixed` described below.
Class description:
Implement the KernelFixed class.
Method signatures and docstrings:
- def __init__(self, embd_dim, hidden_dim, kernel_dim): Currently, this creates a 2-hidden-layer network with ELU non-linearities.
- def forward(self, words): Given words ret... | Implement the Python class `KernelFixed` described below.
Class description:
Implement the KernelFixed class.
Method signatures and docstrings:
- def __init__(self, embd_dim, hidden_dim, kernel_dim): Currently, this creates a 2-hidden-layer network with ELU non-linearities.
- def forward(self, words): Given words ret... | 86859b7612433cc6349b427b47c54986224e702a | <|skeleton|>
class KernelFixed:
def __init__(self, embd_dim, hidden_dim, kernel_dim):
"""Currently, this creates a 2-hidden-layer network with ELU non-linearities."""
<|body_0|>
def forward(self, words):
"""Given words returns kernel of dimension [batch_size, set_size, kernel_dim]"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KernelFixed:
def __init__(self, embd_dim, hidden_dim, kernel_dim):
"""Currently, this creates a 2-hidden-layer network with ELU non-linearities."""
super(KernelFixed, self).__init__()
self.embd_dim = embd_dim
self.hidden_dim = hidden_dim
self.kernel_dim = kernel_dim
... | the_stack_v2_python_sparse | dpp_nets/layers/layers.py | mbp28/dpp_nets | train | 1 | |
e0d76d8e7de4146209052d64f5327b3b8011f036 | [
"count = 0\nwhile n > 0:\n count += n & 1\n n >>= 1\nreturn count",
"bits = []\nwhile n > 0:\n bits.append(n % 2)\n n = n // 2\nreturn sum(bits)"
] | <|body_start_0|>
count = 0
while n > 0:
count += n & 1
n >>= 1
return count
<|end_body_0|>
<|body_start_1|>
bits = []
while n > 0:
bits.append(n % 2)
n = n // 2
return sum(bits)
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def hammingWeight_v2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = 0
while n > 0:
count += n & 1
... | stack_v2_sparse_classes_36k_train_031316 | 1,446 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "hammingWeight",
"signature": "def hammingWeight(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "hammingWeight_v2",
"signature": "def hammingWeight_v2(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019503 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n): :type n: int :rtype: int
- def hammingWeight_v2(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n): :type n: int :rtype: int
- def hammingWeight_v2(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def hammingWeight(self, n):
... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def hammingWeight_v2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
count = 0
while n > 0:
count += n & 1
n >>= 1
return count
def hammingWeight_v2(self, n):
""":type n: int :rtype: int"""
bits = []
while n > 0:
... | the_stack_v2_python_sparse | src/lt_191.py | oxhead/CodingYourWay | train | 0 | |
acd0bc0cc66c416df26241f5a8fd54ffbe0e8f9e | [
"t = parse_tree('((A,B),C);')\nadd_parent_links(t)\nself.assertEqual([str(l.parent) for l in t.leaves], [\"('A', 'B')\", \"('A', 'B')\", \"(('A', 'B'), 'C')\"])",
"t = parse_tree('((A,B),C);')\nadd_distance_from_root(t)\nself.assertEqual([l.distance_from_root for l in t.leaves], [0, 0, 0])\nt = parse_tree('((A:2,... | <|body_start_0|>
t = parse_tree('((A,B),C);')
add_parent_links(t)
self.assertEqual([str(l.parent) for l in t.leaves], ["('A', 'B')", "('A', 'B')", "(('A', 'B'), 'C')"])
<|end_body_0|>
<|body_start_1|>
t = parse_tree('((A,B),C);')
add_distance_from_root(t)
self.assertEqua... | Test of the module-level functions. | TestFunctions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFunctions:
"""Test of the module-level functions."""
def testAddParentLink(self):
"""Test the add_parent_links() function."""
<|body_0|>
def testAddDistanceFromRoot(self):
"""Test the add_distance_from_root() function."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_031317 | 4,457 | no_license | [
{
"docstring": "Test the add_parent_links() function.",
"name": "testAddParentLink",
"signature": "def testAddParentLink(self)"
},
{
"docstring": "Test the add_distance_from_root() function.",
"name": "testAddDistanceFromRoot",
"signature": "def testAddDistanceFromRoot(self)"
}
] | 2 | null | Implement the Python class `TestFunctions` described below.
Class description:
Test of the module-level functions.
Method signatures and docstrings:
- def testAddParentLink(self): Test the add_parent_links() function.
- def testAddDistanceFromRoot(self): Test the add_distance_from_root() function. | Implement the Python class `TestFunctions` described below.
Class description:
Test of the module-level functions.
Method signatures and docstrings:
- def testAddParentLink(self): Test the add_parent_links() function.
- def testAddDistanceFromRoot(self): Test the add_distance_from_root() function.
<|skeleton|>
class... | 40979405a43703506b84925b26bb9d2c7c9c021b | <|skeleton|>
class TestFunctions:
"""Test of the module-level functions."""
def testAddParentLink(self):
"""Test the add_parent_links() function."""
<|body_0|>
def testAddDistanceFromRoot(self):
"""Test the add_distance_from_root() function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFunctions:
"""Test of the module-level functions."""
def testAddParentLink(self):
"""Test the add_parent_links() function."""
t = parse_tree('((A,B),C);')
add_parent_links(t)
self.assertEqual([str(l.parent) for l in t.leaves], ["('A', 'B')", "('A', 'B')", "(('A', 'B'),... | the_stack_v2_python_sparse | newick_modified/treetest.py | dtneves/SuperFine | train | 7 |
1271fac631deb8d00397faaa6e38523d04a61435 | [
"super(AttConv, self).__init__()\nself._in_src_feats, self._in_dst_feats = (in_feats[0], in_feats[1])\nself._out_feats = out_feats\nself._num_heads = num_heads\nself.dropout = nn.Dropout(dropout)\nself.leaky_relu = nn.LeakyReLU(negative_slope)",
"with graph.local_scope():\n feat_src = self.dropout(feat[0])\n ... | <|body_start_0|>
super(AttConv, self).__init__()
self._in_src_feats, self._in_dst_feats = (in_feats[0], in_feats[1])
self._out_feats = out_feats
self._num_heads = num_heads
self.dropout = nn.Dropout(dropout)
self.leaky_relu = nn.LeakyReLU(negative_slope)
<|end_body_0|>
<... | Description ----------- Attention-based convolution was introduced in `Hybrid Micro/Macro Level Convolution for Heterogeneous Graph Learning <https://arxiv.org/abs/>`__ and mathematically is defined as follows: | AttConv | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttConv:
"""Description ----------- Attention-based convolution was introduced in `Hybrid Micro/Macro Level Convolution for Heterogeneous Graph Learning <https://arxiv.org/abs/>`__ and mathematically is defined as follows:"""
def __init__(self, in_feats: tuple, out_feats: int, num_heads: int... | stack_v2_sparse_classes_36k_train_031318 | 4,469 | permissive | [
{
"docstring": "Parameters ---------- in_feats : pair of ints Input feature size. out_feats : int Output feature size. num_heads : int Number of heads in Multi-Head Attention. dropout : float, optional Dropout rate, defaults: 0. negative_slope : float, optional Negative slope rate, defaults: 0.2.",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_012765 | Implement the Python class `AttConv` described below.
Class description:
Description ----------- Attention-based convolution was introduced in `Hybrid Micro/Macro Level Convolution for Heterogeneous Graph Learning <https://arxiv.org/abs/>`__ and mathematically is defined as follows:
Method signatures and docstrings:
... | Implement the Python class `AttConv` described below.
Class description:
Description ----------- Attention-based convolution was introduced in `Hybrid Micro/Macro Level Convolution for Heterogeneous Graph Learning <https://arxiv.org/abs/>`__ and mathematically is defined as follows:
Method signatures and docstrings:
... | f6038301c7d1f3a0cfa563264f14194c415330ea | <|skeleton|>
class AttConv:
"""Description ----------- Attention-based convolution was introduced in `Hybrid Micro/Macro Level Convolution for Heterogeneous Graph Learning <https://arxiv.org/abs/>`__ and mathematically is defined as follows:"""
def __init__(self, in_feats: tuple, out_feats: int, num_heads: int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttConv:
"""Description ----------- Attention-based convolution was introduced in `Hybrid Micro/Macro Level Convolution for Heterogeneous Graph Learning <https://arxiv.org/abs/>`__ and mathematically is defined as follows:"""
def __init__(self, in_feats: tuple, out_feats: int, num_heads: int, dropout: fl... | the_stack_v2_python_sparse | openhgnn/models/micro_layer/HGConv.py | liushiliushi/OpenHGNN | train | 1 |
a509ef89257a2bff137624e4ec93709c45c28f79 | [
"test_name = self._testMethodName\nalways_allow(driver=self.driver)\nmylogger.debug(test_name)\nself.driver.implicitly_wait(5)\nuserAvatar_element(self.driver)\nmylogger.info('进入我的页面')\nself.driver.implicitly_wait(5)\ndL_element(self.driver)\nmylogger.info('点击注册/登录 进入登录页面')\nself.driver.implicitly_wait(10)\nwX_elem... | <|body_start_0|>
test_name = self._testMethodName
always_allow(driver=self.driver)
mylogger.debug(test_name)
self.driver.implicitly_wait(5)
userAvatar_element(self.driver)
mylogger.info('进入我的页面')
self.driver.implicitly_wait(5)
dL_element(self.driver)
... | WX | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WX:
def test_1(self):
"""微信登录"""
<|body_0|>
def test_2(self):
"""当前用户退出"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test_name = self._testMethodName
always_allow(driver=self.driver)
mylogger.debug(test_name)
self.driver.i... | stack_v2_sparse_classes_36k_train_031319 | 1,793 | no_license | [
{
"docstring": "微信登录",
"name": "test_1",
"signature": "def test_1(self)"
},
{
"docstring": "当前用户退出",
"name": "test_2",
"signature": "def test_2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019847 | Implement the Python class `WX` described below.
Class description:
Implement the WX class.
Method signatures and docstrings:
- def test_1(self): 微信登录
- def test_2(self): 当前用户退出 | Implement the Python class `WX` described below.
Class description:
Implement the WX class.
Method signatures and docstrings:
- def test_1(self): 微信登录
- def test_2(self): 当前用户退出
<|skeleton|>
class WX:
def test_1(self):
"""微信登录"""
<|body_0|>
def test_2(self):
"""当前用户退出"""
<|b... | 5924b88c5bc2a41d62807cc665bb3a76dfe0f3d3 | <|skeleton|>
class WX:
def test_1(self):
"""微信登录"""
<|body_0|>
def test_2(self):
"""当前用户退出"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WX:
def test_1(self):
"""微信登录"""
test_name = self._testMethodName
always_allow(driver=self.driver)
mylogger.debug(test_name)
self.driver.implicitly_wait(5)
userAvatar_element(self.driver)
mylogger.info('进入我的页面')
self.driver.implicitly_wait(5)
... | the_stack_v2_python_sparse | testsuite/test1_wxdl.py | Lkamanda/LT | train | 2 | |
1b5caaf8edd93e3f28dbdee27db9e5d5714030ca | [
"super().__init__()\nself.dense_feature_extractor = dense_feature_extractor\nself.seg_classifier = seg_classifier\nself.changemixin = changemixin\nif inference_mode not in ['t1t2', 't2t1', 'mean']:\n raise ValueError(f'Unknown inference_mode: {inference_mode}')\nself.inference_mode = inference_mode",
"b, t, c,... | <|body_start_0|>
super().__init__()
self.dense_feature_extractor = dense_feature_extractor
self.seg_classifier = seg_classifier
self.changemixin = changemixin
if inference_mode not in ['t1t2', 't2t1', 'mean']:
raise ValueError(f'Unknown inference_mode: {inference_mode... | The base class of the network architecture of ChangeStar. ChangeStar is composed of an any segmentation model and a ChangeMixin module. This model is mainly used for binary/multi-class change detection under bitemporal supervision and single-temporal supervision. It features the property of segmentation architecture re... | ChangeStar | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeStar:
"""The base class of the network architecture of ChangeStar. ChangeStar is composed of an any segmentation model and a ChangeMixin module. This model is mainly used for binary/multi-class change detection under bitemporal supervision and single-temporal supervision. It features the pr... | stack_v2_sparse_classes_36k_train_031320 | 7,715 | permissive | [
{
"docstring": "Initializes a new ChangeStar model. Args: dense_feature_extractor: module for dense feature extraction, typically a semantic segmentation model without semantic segmentation head. seg_classifier: semantic segmentation head, typically a convolutional layer followed by an upsampling layer. changem... | 2 | stack_v2_sparse_classes_30k_train_018709 | Implement the Python class `ChangeStar` described below.
Class description:
The base class of the network architecture of ChangeStar. ChangeStar is composed of an any segmentation model and a ChangeMixin module. This model is mainly used for binary/multi-class change detection under bitemporal supervision and single-t... | Implement the Python class `ChangeStar` described below.
Class description:
The base class of the network architecture of ChangeStar. ChangeStar is composed of an any segmentation model and a ChangeMixin module. This model is mainly used for binary/multi-class change detection under bitemporal supervision and single-t... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class ChangeStar:
"""The base class of the network architecture of ChangeStar. ChangeStar is composed of an any segmentation model and a ChangeMixin module. This model is mainly used for binary/multi-class change detection under bitemporal supervision and single-temporal supervision. It features the pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChangeStar:
"""The base class of the network architecture of ChangeStar. ChangeStar is composed of an any segmentation model and a ChangeMixin module. This model is mainly used for binary/multi-class change detection under bitemporal supervision and single-temporal supervision. It features the property of seg... | the_stack_v2_python_sparse | torchgeo/models/changestar.py | microsoft/torchgeo | train | 1,724 |
ddc9d65b8f1788bca401da4bcb2654f85997f217 | [
"password1 = self.cleaned_data.get('password1')\npassword2 = self.cleaned_data.get('password2')\nif password1 and password2 and (password1 != password2):\n raise forms.ValidationError(PASSWORD_MISMATCH_ERROR)\nreturn password2",
"user = super(UserCreationForm, self).save(commit=False)\nuser.set_password(self.c... | <|body_start_0|>
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and (password1 != password2):
raise forms.ValidationError(PASSWORD_MISMATCH_ERROR)
return password2
<|end_body_0|>
<|body_start_1|>
... | A form for creating new users. Includes all the required fields, plus a repeated password. | UserCreationForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCreationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_password2(self):
"""Check that the two password entries match."""
<|body_0|>
def save(self, commit=True):
"""Save the provided password in... | stack_v2_sparse_classes_36k_train_031321 | 2,955 | permissive | [
{
"docstring": "Check that the two password entries match.",
"name": "clean_password2",
"signature": "def clean_password2(self)"
},
{
"docstring": "Save the provided password in hashed format.",
"name": "save",
"signature": "def save(self, commit=True)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005438 | Implement the Python class `UserCreationForm` described below.
Class description:
A form for creating new users. Includes all the required fields, plus a repeated password.
Method signatures and docstrings:
- def clean_password2(self): Check that the two password entries match.
- def save(self, commit=True): Save the... | Implement the Python class `UserCreationForm` described below.
Class description:
A form for creating new users. Includes all the required fields, plus a repeated password.
Method signatures and docstrings:
- def clean_password2(self): Check that the two password entries match.
- def save(self, commit=True): Save the... | 8982dc736261ab3cbe0f3e1d94da40bb03cd8ff3 | <|skeleton|>
class UserCreationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_password2(self):
"""Check that the two password entries match."""
<|body_0|>
def save(self, commit=True):
"""Save the provided password in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserCreationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_password2(self):
"""Check that the two password entries match."""
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password... | the_stack_v2_python_sparse | coffeestats/caffeine/admin.py | coffeestats/coffeestats-django | train | 6 |
3e58de25cf1e39d4309fdc673c8d3582a30291f8 | [
"super(LearningSchedule, self).__init__()\nself.dm = tf.cast(dm, tf.float32)\nself.warmup_steps = warmup_steps",
"rsqrt_dm = tf.math.rsqrt(self.dm)\nrsqrt_step_arg = tf.math.rsqrt(step)\nwarmup_step_arg = step * self.warmup_steps ** (-1.5)\nl_rate = rsqrt_dm * tf.math.minimum(rsqrt_step_arg, warmup_step_arg)\nret... | <|body_start_0|>
super(LearningSchedule, self).__init__()
self.dm = tf.cast(dm, tf.float32)
self.warmup_steps = warmup_steps
<|end_body_0|>
<|body_start_1|>
rsqrt_dm = tf.math.rsqrt(self.dm)
rsqrt_step_arg = tf.math.rsqrt(step)
warmup_step_arg = step * self.warmup_steps ... | Establishes learning rate schedule for training transformer model Utilizes given function for learning rate: l_rate = (dm ** -0.5) * min( (step_num ** -0.5), (step_num * warmup_steps ** -1.5)) | LearningSchedule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearningSchedule:
"""Establishes learning rate schedule for training transformer model Utilizes given function for learning rate: l_rate = (dm ** -0.5) * min( (step_num ** -0.5), (step_num * warmup_steps ** -1.5))"""
def __init__(self, dm, warmup_steps=4000):
"""Class constructor par... | stack_v2_sparse_classes_36k_train_031322 | 5,130 | no_license | [
{
"docstring": "Class constructor parameters: dm [int]: dimensionality of the model warmup_steps [int]: number of warmup steps, default=4000",
"name": "__init__",
"signature": "def __init__(self, dm, warmup_steps=4000)"
},
{
"docstring": "Evaluates the learning rate for the given step",
"nam... | 2 | null | Implement the Python class `LearningSchedule` described below.
Class description:
Establishes learning rate schedule for training transformer model Utilizes given function for learning rate: l_rate = (dm ** -0.5) * min( (step_num ** -0.5), (step_num * warmup_steps ** -1.5))
Method signatures and docstrings:
- def __i... | Implement the Python class `LearningSchedule` described below.
Class description:
Establishes learning rate schedule for training transformer model Utilizes given function for learning rate: l_rate = (dm ** -0.5) * min( (step_num ** -0.5), (step_num * warmup_steps ** -1.5))
Method signatures and docstrings:
- def __i... | 8834b201ca84937365e4dcc0fac978656cdf5293 | <|skeleton|>
class LearningSchedule:
"""Establishes learning rate schedule for training transformer model Utilizes given function for learning rate: l_rate = (dm ** -0.5) * min( (step_num ** -0.5), (step_num * warmup_steps ** -1.5))"""
def __init__(self, dm, warmup_steps=4000):
"""Class constructor par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LearningSchedule:
"""Establishes learning rate schedule for training transformer model Utilizes given function for learning rate: l_rate = (dm ** -0.5) * min( (step_num ** -0.5), (step_num * warmup_steps ** -1.5))"""
def __init__(self, dm, warmup_steps=4000):
"""Class constructor parameters: dm [... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-train.py | ejonakodra/holbertonschool-machine_learning-1 | train | 0 |
93b054b0c42ae4757f09c63efce071f1279a4e7f | [
"product_to_delete_id = self.cleaned_data['product_to_delete']\ntry:\n product_to_delete = Product.objects.get(id=product_to_delete_id)\nexcept Product.DoesNotExist:\n raise forms.ValidationError(\"Ce produit n'existe pas !\")\nreturn product_to_delete",
"group_id = self.cleaned_data['group']\ntry:\n gro... | <|body_start_0|>
product_to_delete_id = self.cleaned_data['product_to_delete']
try:
product_to_delete = Product.objects.get(id=product_to_delete_id)
except Product.DoesNotExist:
raise forms.ValidationError("Ce produit n'existe pas !")
return product_to_delete
<|en... | ProductSuppressionForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductSuppressionForm:
def clean_product_to_delete(self):
"""Return the Group object since the id input by user, if it exists"""
<|body_0|>
def clean_group(self):
"""Return the Group object since the id input by user, if it exists"""
<|body_1|>
def dele... | stack_v2_sparse_classes_36k_train_031323 | 1,863 | no_license | [
{
"docstring": "Return the Group object since the id input by user, if it exists",
"name": "clean_product_to_delete",
"signature": "def clean_product_to_delete(self)"
},
{
"docstring": "Return the Group object since the id input by user, if it exists",
"name": "clean_group",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_017507 | Implement the Python class `ProductSuppressionForm` described below.
Class description:
Implement the ProductSuppressionForm class.
Method signatures and docstrings:
- def clean_product_to_delete(self): Return the Group object since the id input by user, if it exists
- def clean_group(self): Return the Group object s... | Implement the Python class `ProductSuppressionForm` described below.
Class description:
Implement the ProductSuppressionForm class.
Method signatures and docstrings:
- def clean_product_to_delete(self): Return the Group object since the id input by user, if it exists
- def clean_group(self): Return the Group object s... | cf0b982a6df2b8b4318d12d344ef0827394eedfd | <|skeleton|>
class ProductSuppressionForm:
def clean_product_to_delete(self):
"""Return the Group object since the id input by user, if it exists"""
<|body_0|>
def clean_group(self):
"""Return the Group object since the id input by user, if it exists"""
<|body_1|>
def dele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductSuppressionForm:
def clean_product_to_delete(self):
"""Return the Group object since the id input by user, if it exists"""
product_to_delete_id = self.cleaned_data['product_to_delete']
try:
product_to_delete = Product.objects.get(id=product_to_delete_id)
exce... | the_stack_v2_python_sparse | product/forms.py | cleliofavoccia/Share | train | 0 | |
a11508cd7324225c094f1ce3e8107b6738c29731 | [
"self.data_dictionary = {year: pd.read_csv(self.data_path + data_type_string + f'Piped{year}.csv') for year in range(2015, 2020)}\nself.data_df = pd.concat(list(self.data_dictionary.values()))\nself.data_df = self.clean_correct_data(self.data_df)",
"data_df['SR CREATE DATE'] = data_df['SR CREATE DATE'].apply(lamb... | <|body_start_0|>
self.data_dictionary = {year: pd.read_csv(self.data_path + data_type_string + f'Piped{year}.csv') for year in range(2015, 2020)}
self.data_df = pd.concat(list(self.data_dictionary.values()))
self.data_df = self.clean_correct_data(self.data_df)
<|end_body_0|>
<|body_start_1|>
... | Container class for loading flooding data. | Houston311Data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Houston311Data:
"""Container class for loading flooding data."""
def __init__(self, data_type_string):
"""Loads dataframe and merge in the station data for each reading. :param data_type_string:"""
<|body_0|>
def clean_correct_data(self, data_df):
"""Clean origin... | stack_v2_sparse_classes_36k_train_031324 | 5,972 | no_license | [
{
"docstring": "Loads dataframe and merge in the station data for each reading. :param data_type_string:",
"name": "__init__",
"signature": "def __init__(self, data_type_string)"
},
{
"docstring": "Clean original df to have usable objects :param data_df: :return: cleaned DataFrame",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_020529 | Implement the Python class `Houston311Data` described below.
Class description:
Container class for loading flooding data.
Method signatures and docstrings:
- def __init__(self, data_type_string): Loads dataframe and merge in the station data for each reading. :param data_type_string:
- def clean_correct_data(self, d... | Implement the Python class `Houston311Data` described below.
Class description:
Container class for loading flooding data.
Method signatures and docstrings:
- def __init__(self, data_type_string): Loads dataframe and merge in the station data for each reading. :param data_type_string:
- def clean_correct_data(self, d... | 0edb39b017db858bad73aa018516fee51942f212 | <|skeleton|>
class Houston311Data:
"""Container class for loading flooding data."""
def __init__(self, data_type_string):
"""Loads dataframe and merge in the station data for each reading. :param data_type_string:"""
<|body_0|>
def clean_correct_data(self, data_df):
"""Clean origin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Houston311Data:
"""Container class for loading flooding data."""
def __init__(self, data_type_string):
"""Loads dataframe and merge in the station data for each reading. :param data_type_string:"""
self.data_dictionary = {year: pd.read_csv(self.data_path + data_type_string + f'Piped{year}... | the_stack_v2_python_sparse | runtime/dataloader/Houston311Data.py | Denizhan-Yigitbas/PotHoles_DSCI400 | train | 0 |
be2966afca7a5675553033b35d517fafff6304d0 | [
"self.manager = CacheDataManager()\nself.info = CacheManagerInfo(self.manager)\nself.dataset = CacheManagerDataset(self.manager)\nself.task = CacheManagerTask(self.manager)\nself.category = CacheManagerCategory(self.manager)",
"self.info.info()\nself.dataset.info()\nself.category.info()"
] | <|body_start_0|>
self.manager = CacheDataManager()
self.info = CacheManagerInfo(self.manager)
self.dataset = CacheManagerDataset(self.manager)
self.task = CacheManagerTask(self.manager)
self.category = CacheManagerCategory(self.manager)
<|end_body_0|>
<|body_start_1|>
se... | Manage dbcollection configurations and stores them inside a cache file stored in disk. Attributes ---------- cache_filename : str Cache file path + name. cache_dir : str Default directory to store all dataset's metadata files. download_dir : str Default save dir path for downloaded data. data : dict Cache contents. | CacheManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CacheManager:
"""Manage dbcollection configurations and stores them inside a cache file stored in disk. Attributes ---------- cache_filename : str Cache file path + name. cache_dir : str Default directory to store all dataset's metadata files. download_dir : str Default save dir path for download... | stack_v2_sparse_classes_36k_train_031325 | 33,479 | permissive | [
{
"docstring": "Initializes the class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Prints the information of the cache.",
"name": "info_cache",
"signature": "def info_cache(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012295 | Implement the Python class `CacheManager` described below.
Class description:
Manage dbcollection configurations and stores them inside a cache file stored in disk. Attributes ---------- cache_filename : str Cache file path + name. cache_dir : str Default directory to store all dataset's metadata files. download_dir :... | Implement the Python class `CacheManager` described below.
Class description:
Manage dbcollection configurations and stores them inside a cache file stored in disk. Attributes ---------- cache_filename : str Cache file path + name. cache_dir : str Default directory to store all dataset's metadata files. download_dir :... | e0be95d941b50a5b2e27ffa1c5be20dc6aa2d6a1 | <|skeleton|>
class CacheManager:
"""Manage dbcollection configurations and stores them inside a cache file stored in disk. Attributes ---------- cache_filename : str Cache file path + name. cache_dir : str Default directory to store all dataset's metadata files. download_dir : str Default save dir path for download... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CacheManager:
"""Manage dbcollection configurations and stores them inside a cache file stored in disk. Attributes ---------- cache_filename : str Cache file path + name. cache_dir : str Default directory to store all dataset's metadata files. download_dir : str Default save dir path for downloaded data. data... | the_stack_v2_python_sparse | dbcollection/core/manager.py | dbcollection/dbcollection | train | 25 |
8e5c5cb1b412103189f903cf48ba32ccdf9db1ad | [
"self.T = T\nself.height = height\nself.width = width\nself.depth = depth\nself.axis = T[0:3, 0]\nself.binormal = T[0:3, 1]\nself.approach = -T[0:3, 2]\nself.center = T[0:3, 3]\nself.bottom = self.center - 0.5 * self.depth * self.approach\nself.top = self.center + 0.5 * self.depth * self.approach",
"handClosingRe... | <|body_start_0|>
self.T = T
self.height = height
self.width = width
self.depth = depth
self.axis = T[0:3, 0]
self.binormal = T[0:3, 1]
self.approach = -T[0:3, 2]
self.center = T[0:3, 3]
self.bottom = self.center - 0.5 * self.depth * self.approach
... | HandDescriptor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HandDescriptor:
def __init__(self, T, height=0.01, width=0.085, depth=0.065):
"""Creates a HandDescriptor object with everything needed. - Input depth: For the Robotiq 85 gripper, we measured 0.070 when open and 0.075 when closed."""
<|body_0|>
def GetPointsInHandFrame(self,... | stack_v2_sparse_classes_36k_train_031326 | 2,454 | permissive | [
{
"docstring": "Creates a HandDescriptor object with everything needed. - Input depth: For the Robotiq 85 gripper, we measured 0.070 when open and 0.075 when closed.",
"name": "__init__",
"signature": "def __init__(self, T, height=0.01, width=0.085, depth=0.065)"
},
{
"docstring": "TODO",
"n... | 2 | null | Implement the Python class `HandDescriptor` described below.
Class description:
Implement the HandDescriptor class.
Method signatures and docstrings:
- def __init__(self, T, height=0.01, width=0.085, depth=0.065): Creates a HandDescriptor object with everything needed. - Input depth: For the Robotiq 85 gripper, we me... | Implement the Python class `HandDescriptor` described below.
Class description:
Implement the HandDescriptor class.
Method signatures and docstrings:
- def __init__(self, T, height=0.01, width=0.085, depth=0.065): Creates a HandDescriptor object with everything needed. - Input depth: For the Robotiq 85 gripper, we me... | 563cde0618349f0ef5c59a104fb1936bad46f845 | <|skeleton|>
class HandDescriptor:
def __init__(self, T, height=0.01, width=0.085, depth=0.065):
"""Creates a HandDescriptor object with everything needed. - Input depth: For the Robotiq 85 gripper, we measured 0.070 when open and 0.075 when closed."""
<|body_0|>
def GetPointsInHandFrame(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HandDescriptor:
def __init__(self, T, height=0.01, width=0.085, depth=0.065):
"""Creates a HandDescriptor object with everything needed. - Input depth: For the Robotiq 85 gripper, we measured 0.070 when open and 0.075 when closed."""
self.T = T
self.height = height
self.width =... | the_stack_v2_python_sparse | Robot/scripts/geom_pick_place/hand_descriptor.py | elegantprogrammer/GeomPickPlace | train | 0 | |
3255ee09722cf2e7a86a2b6b0373e85e4e4dc7da | [
"from spyder.utils import programs\nif not programs.is_module_installed('psutil', '>=0.2.0'):\n raise ImportError",
"import psutil\ntext = '%d%%' % psutil.cpu_percent(interval=0)\nreturn 'CPU ' + text.rjust(3)"
] | <|body_start_0|>
from spyder.utils import programs
if not programs.is_module_installed('psutil', '>=0.2.0'):
raise ImportError
<|end_body_0|>
<|body_start_1|>
import psutil
text = '%d%%' % psutil.cpu_percent(interval=0)
return 'CPU ' + text.rjust(3)
<|end_body_1|>
| Status bar widget for system cpu usage. | CPUStatus | [
"LGPL-3.0-only",
"LGPL-2.1-only",
"Python-2.0",
"LGPL-2.1-or-later",
"LGPL-2.0-or-later",
"CC-BY-2.5",
"OFL-1.1",
"LGPL-3.0-or-later",
"GPL-1.0-or-later",
"GPL-2.0-only",
"Apache-2.0",
"CC-BY-3.0",
"MIT",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CPUStatus:
"""Status bar widget for system cpu usage."""
def import_test(self):
"""Raise ImportError if feature is not supported."""
<|body_0|>
def get_value(self):
"""Return CPU usage."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from spyder... | stack_v2_sparse_classes_36k_train_031327 | 5,934 | permissive | [
{
"docstring": "Raise ImportError if feature is not supported.",
"name": "import_test",
"signature": "def import_test(self)"
},
{
"docstring": "Return CPU usage.",
"name": "get_value",
"signature": "def get_value(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001021 | Implement the Python class `CPUStatus` described below.
Class description:
Status bar widget for system cpu usage.
Method signatures and docstrings:
- def import_test(self): Raise ImportError if feature is not supported.
- def get_value(self): Return CPU usage. | Implement the Python class `CPUStatus` described below.
Class description:
Status bar widget for system cpu usage.
Method signatures and docstrings:
- def import_test(self): Raise ImportError if feature is not supported.
- def get_value(self): Return CPU usage.
<|skeleton|>
class CPUStatus:
"""Status bar widget ... | be98b086f95968fccc4e8dbe3f1140154c94a412 | <|skeleton|>
class CPUStatus:
"""Status bar widget for system cpu usage."""
def import_test(self):
"""Raise ImportError if feature is not supported."""
<|body_0|>
def get_value(self):
"""Return CPU usage."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CPUStatus:
"""Status bar widget for system cpu usage."""
def import_test(self):
"""Raise ImportError if feature is not supported."""
from spyder.utils import programs
if not programs.is_module_installed('psutil', '>=0.2.0'):
raise ImportError
def get_value(self):
... | the_stack_v2_python_sparse | spyder/widgets/status.py | zrlzwd/spyder | train | 2 |
b815d71043a889250f254485da6d8440a9605ffe | [
"if not os.path.isfile(testbed_file):\n raise ValueError('Testbed file {} does not exist.'.format(testbed_file))\nif testbed_pattern:\n testbed_pattern = re.compile(testbed_pattern)\nwith open(testbed_file, 'r') as f:\n raw_testbeds = yaml.safe_load(f)\ntestbeds = {}\nfor raw_testbed in raw_testbeds:\n ... | <|body_start_0|>
if not os.path.isfile(testbed_file):
raise ValueError('Testbed file {} does not exist.'.format(testbed_file))
if testbed_pattern:
testbed_pattern = re.compile(testbed_pattern)
with open(testbed_file, 'r') as f:
raw_testbeds = yaml.safe_load(f)... | Data model that represents a testbed object. | TestBed | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBed:
"""Data model that represents a testbed object."""
def from_file(cls, testbed_file='testbed.yaml', testbed_pattern=None, hosts=None):
"""Load all testbed objects from YAML file. Args: testbed_file (str): Path to testbed file. testbed_pattern (str): Regex pattern to filter te... | stack_v2_sparse_classes_36k_train_031328 | 3,400 | permissive | [
{
"docstring": "Load all testbed objects from YAML file. Args: testbed_file (str): Path to testbed file. testbed_pattern (str): Regex pattern to filter testbeds. hosts (AnsibleHosts): AnsibleHosts object that contains all hosts in the testbed. Returns: dict: Testbed name to testbed object mapping.",
"name":... | 2 | null | Implement the Python class `TestBed` described below.
Class description:
Data model that represents a testbed object.
Method signatures and docstrings:
- def from_file(cls, testbed_file='testbed.yaml', testbed_pattern=None, hosts=None): Load all testbed objects from YAML file. Args: testbed_file (str): Path to testbe... | Implement the Python class `TestBed` described below.
Class description:
Data model that represents a testbed object.
Method signatures and docstrings:
- def from_file(cls, testbed_file='testbed.yaml', testbed_pattern=None, hosts=None): Load all testbed objects from YAML file. Args: testbed_file (str): Path to testbe... | a86f0e5b1742d01b8d8a28a537f79bf608955695 | <|skeleton|>
class TestBed:
"""Data model that represents a testbed object."""
def from_file(cls, testbed_file='testbed.yaml', testbed_pattern=None, hosts=None):
"""Load all testbed objects from YAML file. Args: testbed_file (str): Path to testbed file. testbed_pattern (str): Regex pattern to filter te... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestBed:
"""Data model that represents a testbed object."""
def from_file(cls, testbed_file='testbed.yaml', testbed_pattern=None, hosts=None):
"""Load all testbed objects from YAML file. Args: testbed_file (str): Path to testbed file. testbed_pattern (str): Regex pattern to filter testbeds. hosts... | the_stack_v2_python_sparse | ansible/devutil/testbed.py | ramakristipati/sonic-mgmt | train | 2 |
41a1c1881303d0428174cc6def4c8f2c933de978 | [
"for i, num1 in enumerate(nums):\n for j, num2 in enumerate(nums[i + 1:]):\n if num1 + num2 == target:\n return [i, j + i + 1]",
"d = {}\nfor i, num in enumerate(nums):\n d[num] = i\nfor i, num in enumerate(nums):\n n = target - num\n if n in d and i is not d[n]:\n return [i, ... | <|body_start_0|>
for i, num1 in enumerate(nums):
for j, num2 in enumerate(nums[i + 1:]):
if num1 + num2 == target:
return [i, j + i + 1]
<|end_body_0|>
<|body_start_1|>
d = {}
for i, num in enumerate(nums):
d[num] = i
for i, nu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_1(self, nums, target):
"""Brute Force :type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_2(self, nums, target):
"""Two-pass Hash Table :type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_031329 | 1,556 | no_license | [
{
"docstring": "Brute Force :type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_1",
"signature": "def twoSum_1(self, nums, target)"
},
{
"docstring": "Two-pass Hash Table :type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_2",
"signature": ... | 4 | stack_v2_sparse_classes_30k_train_009190 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums, target): Brute Force :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum_2(self, nums, target): Two-pass Hash Table :type nums: List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums, target): Brute Force :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum_2(self, nums, target): Two-pass Hash Table :type nums: List[i... | 3ac66a1bf85a344234c746ebf3de30e643838e5f | <|skeleton|>
class Solution:
def twoSum_1(self, nums, target):
"""Brute Force :type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_2(self, nums, target):
"""Two-pass Hash Table :type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum_1(self, nums, target):
"""Brute Force :type nums: List[int] :type target: int :rtype: List[int]"""
for i, num1 in enumerate(nums):
for j, num2 in enumerate(nums[i + 1:]):
if num1 + num2 == target:
return [i, j + i + 1]
d... | the_stack_v2_python_sparse | 1. Two Sum/1.py | JohnHuiWB/leetcode | train | 0 | |
e74ea41b014a04f6fd35ccbe5f273f546b02318c | [
"L = [[0 for i in range(n + 1)] for i in range(m + 1)]\nfor i in range(1, n + 1):\n L[1][i] = 1\nfor i in range(1, m + 1):\n L[i][1] = 1\nfor i in range(2, m + 1):\n for j in range(2, n + 1):\n L[i][j] = L[i - 1][j] + L[i][j - 1]\nreturn L[m][n]",
"def f(i, j):\n if i == 0 and j == 0:\n ... | <|body_start_0|>
L = [[0 for i in range(n + 1)] for i in range(m + 1)]
for i in range(1, n + 1):
L[1][i] = 1
for i in range(1, m + 1):
L[i][1] = 1
for i in range(2, m + 1):
for j in range(2, n + 1):
L[i][j] = L[i - 1][j] + L[i][j - 1]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def uniquePaths_2(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
def uniquePaths_3(self, m, n):
""":type m: int :type n: int :rtype... | stack_v2_sparse_classes_36k_train_031330 | 1,233 | no_license | [
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m, n)"
},
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "uniquePaths_2",
"signature": "def uniquePaths_2(self, m, n)"
},
{
"docstring": ":type m: i... | 3 | stack_v2_sparse_classes_30k_train_004892 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths_2(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths_3(self, m, n): :type m... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths_2(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths_3(self, m, n): :type m... | bd8df12c0d4afd048cf1b58b04c27fa1f3622769 | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def uniquePaths_2(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
def uniquePaths_3(self, m, n):
""":type m: int :type n: int :rtype... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
L = [[0 for i in range(n + 1)] for i in range(m + 1)]
for i in range(1, n + 1):
L[1][i] = 1
for i in range(1, m + 1):
L[i][1] = 1
for i in range(2, m + 1):
... | the_stack_v2_python_sparse | 62_unique_paths.py | aojugg/leetcode | train | 0 | |
c8942d17899c6d3dc1e00fa743bb5ce8eb647bff | [
"super().__init__(n_assets, tickers)\nself.bounds = self._make_valid_bounds(weight_bounds)\nself.initial_guess = np.array([1 / self.n_assets] * self.n_assets)\nself.constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x) - 1}]",
"if len(test_bounds) != 2 or not isinstance(test_bounds, tuple):\n raise ValueErr... | <|body_start_0|>
super().__init__(n_assets, tickers)
self.bounds = self._make_valid_bounds(weight_bounds)
self.initial_guess = np.array([1 / self.n_assets] * self.n_assets)
self.constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x) - 1}]
<|end_body_0|>
<|body_start_1|>
if len... | BaseScipyOptimizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseScipyOptimizer:
def __init__(self, n_assets, tickers=None, weight_bounds=(0, 1)):
""":param weight_bounds: minimum and maximum weight of an asset, defaults to (0, 1). Must be changed to (-1, 1) for portfolios with shorting. :type weight_bounds: tuple, optional"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_031331 | 5,889 | permissive | [
{
"docstring": ":param weight_bounds: minimum and maximum weight of an asset, defaults to (0, 1). Must be changed to (-1, 1) for portfolios with shorting. :type weight_bounds: tuple, optional",
"name": "__init__",
"signature": "def __init__(self, n_assets, tickers=None, weight_bounds=(0, 1))"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_002169 | Implement the Python class `BaseScipyOptimizer` described below.
Class description:
Implement the BaseScipyOptimizer class.
Method signatures and docstrings:
- def __init__(self, n_assets, tickers=None, weight_bounds=(0, 1)): :param weight_bounds: minimum and maximum weight of an asset, defaults to (0, 1). Must be ch... | Implement the Python class `BaseScipyOptimizer` described below.
Class description:
Implement the BaseScipyOptimizer class.
Method signatures and docstrings:
- def __init__(self, n_assets, tickers=None, weight_bounds=(0, 1)): :param weight_bounds: minimum and maximum weight of an asset, defaults to (0, 1). Must be ch... | dfad1256cb6995c7fbd7a025eedb54b1ca04b2fc | <|skeleton|>
class BaseScipyOptimizer:
def __init__(self, n_assets, tickers=None, weight_bounds=(0, 1)):
""":param weight_bounds: minimum and maximum weight of an asset, defaults to (0, 1). Must be changed to (-1, 1) for portfolios with shorting. :type weight_bounds: tuple, optional"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseScipyOptimizer:
def __init__(self, n_assets, tickers=None, weight_bounds=(0, 1)):
""":param weight_bounds: minimum and maximum weight of an asset, defaults to (0, 1). Must be changed to (-1, 1) for portfolios with shorting. :type weight_bounds: tuple, optional"""
super().__init__(n_assets,... | the_stack_v2_python_sparse | pypfopt/base_optimizer.py | proskurin/PyPortfolioOpt | train | 4 | |
23b05c29e736b822f673b1dd5246ae11126df428 | [
"context = {}\ncontext['form'] = ClientForm()\nreturn render(self.request, self.template_name, context)",
"form = ClientForm(self.request.POST, self.request.FILES, company=self.request.user.company)\nif form.is_valid():\n client = form.save(commit=False)\n client.owner = self.request.user\n client.compan... | <|body_start_0|>
context = {}
context['form'] = ClientForm()
return render(self.request, self.template_name, context)
<|end_body_0|>
<|body_start_1|>
form = ClientForm(self.request.POST, self.request.FILES, company=self.request.user.company)
if form.is_valid():
clien... | Viewing for adding client | ClientAddView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientAddView:
"""Viewing for adding client"""
def get(self, *args, **kwargs):
"""Display the client form"""
<|body_0|>
def post(self, *args, **kwargs):
"""Getting the filled form of client"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
context... | stack_v2_sparse_classes_36k_train_031332 | 4,241 | no_license | [
{
"docstring": "Display the client form",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Getting the filled form of client",
"name": "post",
"signature": "def post(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011586 | Implement the Python class `ClientAddView` described below.
Class description:
Viewing for adding client
Method signatures and docstrings:
- def get(self, *args, **kwargs): Display the client form
- def post(self, *args, **kwargs): Getting the filled form of client | Implement the Python class `ClientAddView` described below.
Class description:
Viewing for adding client
Method signatures and docstrings:
- def get(self, *args, **kwargs): Display the client form
- def post(self, *args, **kwargs): Getting the filled form of client
<|skeleton|>
class ClientAddView:
"""Viewing fo... | 17615ea9bfb1edebe41d60dbf2e977f0018d5339 | <|skeleton|>
class ClientAddView:
"""Viewing for adding client"""
def get(self, *args, **kwargs):
"""Display the client form"""
<|body_0|>
def post(self, *args, **kwargs):
"""Getting the filled form of client"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClientAddView:
"""Viewing for adding client"""
def get(self, *args, **kwargs):
"""Display the client form"""
context = {}
context['form'] = ClientForm()
return render(self.request, self.template_name, context)
def post(self, *args, **kwargs):
"""Getting the fi... | the_stack_v2_python_sparse | clients/views.py | Swiftkind/invoice | train | 0 |
e37c7a2b403a5ea08a4c4dca7671bbb891921288 | [
"super(EncoderModule, self).__init__()\nmodule = Encoder(hidden_size, interm_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio)\nself.module = nn.LayerList([module for _ in range(layer_size)])",
"for layer_module in self.module:\n hidden_states = layer_module(hidden_states, attention_mas... | <|body_start_0|>
super(EncoderModule, self).__init__()
module = Encoder(hidden_size, interm_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio)
self.module = nn.LayerList([module for _ in range(layer_size)])
<|end_body_0|>
<|body_start_1|>
for layer_module in self.... | Encoder Module with multiple layers | EncoderModule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderModule:
"""Encoder Module with multiple layers"""
def __init__(self, layer_size, hidden_size, interm_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio):
"""Initialization"""
<|body_0|>
def forward(self, hidden_states, attention_mask, output_... | stack_v2_sparse_classes_36k_train_031333 | 12,741 | permissive | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, layer_size, hidden_size, interm_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio)"
},
{
"docstring": "Multiple encoders",
"name": "forward",
"signature": "def forward(self, hidde... | 2 | null | Implement the Python class `EncoderModule` described below.
Class description:
Encoder Module with multiple layers
Method signatures and docstrings:
- def __init__(self, layer_size, hidden_size, interm_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio): Initialization
- def forward(self, hidden... | Implement the Python class `EncoderModule` described below.
Class description:
Encoder Module with multiple layers
Method signatures and docstrings:
- def __init__(self, layer_size, hidden_size, interm_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio): Initialization
- def forward(self, hidden... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class EncoderModule:
"""Encoder Module with multiple layers"""
def __init__(self, layer_size, hidden_size, interm_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio):
"""Initialization"""
<|body_0|>
def forward(self, hidden_states, attention_mask, output_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderModule:
"""Encoder Module with multiple layers"""
def __init__(self, layer_size, hidden_size, interm_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio):
"""Initialization"""
super(EncoderModule, self).__init__()
module = Encoder(hidden_size, interm_si... | the_stack_v2_python_sparse | apps/drug_target_interaction/moltrans_dti/double_towers.py | PaddlePaddle/PaddleHelix | train | 771 |
edc06ce2aab9d882a9685ef01bbc52c50681b51b | [
"super().__init__(FILTER_NAME_OUTLIER, window_size, precision=precision, entity=entity)\nself._radius = radius\nself._stats_internal: Counter = Counter()\nself._store_raw = True",
"previous_state_values = [cast(float, s.state) for s in self.states]\nnew_state_value = cast(float, new_state.state)\nmedian = statist... | <|body_start_0|>
super().__init__(FILTER_NAME_OUTLIER, window_size, precision=precision, entity=entity)
self._radius = radius
self._stats_internal: Counter = Counter()
self._store_raw = True
<|end_body_0|>
<|body_start_1|>
previous_state_values = [cast(float, s.state) for s in s... | BASIC outlier filter. Determines if new state is in a band around the median. | OutlierFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutlierFilter:
"""BASIC outlier filter. Determines if new state is in a band around the median."""
def __init__(self, *, window_size: int, entity: str, radius: float, precision: int | None=None) -> None:
"""Initialize Filter. :param radius: band radius"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_031334 | 23,958 | permissive | [
{
"docstring": "Initialize Filter. :param radius: band radius",
"name": "__init__",
"signature": "def __init__(self, *, window_size: int, entity: str, radius: float, precision: int | None=None) -> None"
},
{
"docstring": "Implement the outlier filter.",
"name": "_filter_state",
"signatur... | 2 | null | Implement the Python class `OutlierFilter` described below.
Class description:
BASIC outlier filter. Determines if new state is in a band around the median.
Method signatures and docstrings:
- def __init__(self, *, window_size: int, entity: str, radius: float, precision: int | None=None) -> None: Initialize Filter. :... | Implement the Python class `OutlierFilter` described below.
Class description:
BASIC outlier filter. Determines if new state is in a band around the median.
Method signatures and docstrings:
- def __init__(self, *, window_size: int, entity: str, radius: float, precision: int | None=None) -> None: Initialize Filter. :... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OutlierFilter:
"""BASIC outlier filter. Determines if new state is in a band around the median."""
def __init__(self, *, window_size: int, entity: str, radius: float, precision: int | None=None) -> None:
"""Initialize Filter. :param radius: band radius"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutlierFilter:
"""BASIC outlier filter. Determines if new state is in a band around the median."""
def __init__(self, *, window_size: int, entity: str, radius: float, precision: int | None=None) -> None:
"""Initialize Filter. :param radius: band radius"""
super().__init__(FILTER_NAME_OUTL... | the_stack_v2_python_sparse | homeassistant/components/filter/sensor.py | home-assistant/core | train | 35,501 |
f56c18108a790befe169d114b1fc7588eda64022 | [
"self._observer = observer\nself._shouldLogEvent = partial(shouldLogEvent, list(predicates))\nself._negativeObserver = negativeObserver",
"if self._shouldLogEvent(event):\n if 'log_trace' in event:\n event['log_trace'].append((self, self.observer))\n self._observer(event)\nelse:\n self._negativeOb... | <|body_start_0|>
self._observer = observer
self._shouldLogEvent = partial(shouldLogEvent, list(predicates))
self._negativeObserver = negativeObserver
<|end_body_0|>
<|body_start_1|>
if self._shouldLogEvent(event):
if 'log_trace' in event:
event['log_trace'].a... | L{ILogObserver} that wraps another L{ILogObserver}, but filters out events based on applying a series of L{ILogFilterPredicate}s. | FilteringLogObserver | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilteringLogObserver:
"""L{ILogObserver} that wraps another L{ILogObserver}, but filters out events based on applying a series of L{ILogFilterPredicate}s."""
def __init__(self, observer, predicates, negativeObserver=lambda event: None):
"""@param observer: An observer to which this o... | stack_v2_sparse_classes_36k_train_031335 | 6,986 | permissive | [
{
"docstring": "@param observer: An observer to which this observer will forward events when C{predictates} yield a positive result. @type observer: L{ILogObserver} @param predicates: Predicates to apply to events before forwarding to the wrapped observer. @type predicates: ordered iterable of predicates @param... | 2 | null | Implement the Python class `FilteringLogObserver` described below.
Class description:
L{ILogObserver} that wraps another L{ILogObserver}, but filters out events based on applying a series of L{ILogFilterPredicate}s.
Method signatures and docstrings:
- def __init__(self, observer, predicates, negativeObserver=lambda e... | Implement the Python class `FilteringLogObserver` described below.
Class description:
L{ILogObserver} that wraps another L{ILogObserver}, but filters out events based on applying a series of L{ILogFilterPredicate}s.
Method signatures and docstrings:
- def __init__(self, observer, predicates, negativeObserver=lambda e... | 40861791ec4ed3bbd14b07875af25cc740f76920 | <|skeleton|>
class FilteringLogObserver:
"""L{ILogObserver} that wraps another L{ILogObserver}, but filters out events based on applying a series of L{ILogFilterPredicate}s."""
def __init__(self, observer, predicates, negativeObserver=lambda event: None):
"""@param observer: An observer to which this o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilteringLogObserver:
"""L{ILogObserver} that wraps another L{ILogObserver}, but filters out events based on applying a series of L{ILogFilterPredicate}s."""
def __init__(self, observer, predicates, negativeObserver=lambda event: None):
"""@param observer: An observer to which this observer will ... | the_stack_v2_python_sparse | stackoverflow/venv/lib/python3.6/site-packages/twisted/logger/_filter.py | wistbean/learn_python3_spider | train | 14,403 |
bd676a54dffc730115ebc9bc2698dc38034a50f2 | [
"ys = np.linspace(extent[2], extent[3], shape_native[1] + 1)\nxs = np.linspace(extent[0], extent[1], shape_native[0] + 1)\nfor x in xs:\n plt.plot([x, x], [ys[0], ys[-1]], **self.config_dict)\nfor y in ys:\n plt.plot([xs[0], xs[-1]], [y, y], **self.config_dict)",
"try:\n color = self.config_dict['c']\n ... | <|body_start_0|>
ys = np.linspace(extent[2], extent[3], shape_native[1] + 1)
xs = np.linspace(extent[0], extent[1], shape_native[0] + 1)
for x in xs:
plt.plot([x, x], [ys[0], ys[-1]], **self.config_dict)
for y in ys:
plt.plot([xs[0], xs[-1]], [y, y], **self.config... | Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). This object wraps the following Matplotlib methods: - plt.plot: https://matplo... | GridPlot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GridPlot:
"""Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). This object wraps the following Matplotlib... | stack_v2_sparse_classes_36k_train_031336 | 3,733 | permissive | [
{
"docstring": "Plots a rectangular grid of lines on a plot, using the coordinate system of the figure. The size and shape of the grid is specified by the `extent` and `shape_native` properties of a data structure which will provide the rectangaular grid lines on a suitable coordinate system for the plot. Param... | 3 | null | Implement the Python class `GridPlot` described below.
Class description:
Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). Thi... | Implement the Python class `GridPlot` described below.
Class description:
Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). Thi... | 6639dd86d21ea28e942155753ec556752735b4e4 | <|skeleton|>
class GridPlot:
"""Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). This object wraps the following Matplotlib... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GridPlot:
"""Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). This object wraps the following Matplotlib methods: - p... | the_stack_v2_python_sparse | autoarray/plot/wrap/two_d/grid_plot.py | Jammy2211/PyAutoArray | train | 6 |
3ac85c52648c16149df7cedc01d084d65c78f9eb | [
"if self.feature in self.FEATURES_MAPPING:\n self.feature = self.FEATURES_MAPPING[self.feature]\nif 'type' in additional_data:\n self.feature_type = additional_data['type']",
"name = self.function_name\nif self.feature_type:\n name = '%s for %s' % (name, self.feature_type)\nreturn name",
"features = se... | <|body_start_0|>
if self.feature in self.FEATURES_MAPPING:
self.feature = self.FEATURES_MAPPING[self.feature]
if 'type' in additional_data:
self.feature_type = additional_data['type']
<|end_body_0|>
<|body_start_1|>
name = self.function_name
if self.feature_type:... | AbstractOverpassInsightFunction | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractOverpassInsightFunction:
def initiate(self, additional_data):
"""Initiate function :param additional_data: additional data that needed :type additional_data:dict"""
<|body_0|>
def name(self):
"""Name of insight functions :return: string of name"""
<|b... | stack_v2_sparse_classes_36k_train_031337 | 2,354 | permissive | [
{
"docstring": "Initiate function :param additional_data: additional data that needed :type additional_data:dict",
"name": "initiate",
"signature": "def initiate(self, additional_data)"
},
{
"docstring": "Name of insight functions :return: string of name",
"name": "name",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_010869 | Implement the Python class `AbstractOverpassInsightFunction` described below.
Class description:
Implement the AbstractOverpassInsightFunction class.
Method signatures and docstrings:
- def initiate(self, additional_data): Initiate function :param additional_data: additional data that needed :type additional_data:dic... | Implement the Python class `AbstractOverpassInsightFunction` described below.
Class description:
Implement the AbstractOverpassInsightFunction class.
Method signatures and docstrings:
- def initiate(self, additional_data): Initiate function :param additional_data: additional data that needed :type additional_data:dic... | 53d448b8d558e88df5710a672a76ef1f9c983e57 | <|skeleton|>
class AbstractOverpassInsightFunction:
def initiate(self, additional_data):
"""Initiate function :param additional_data: additional data that needed :type additional_data:dict"""
<|body_0|>
def name(self):
"""Name of insight functions :return: string of name"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractOverpassInsightFunction:
def initiate(self, additional_data):
"""Initiate function :param additional_data: additional data that needed :type additional_data:dict"""
if self.feature in self.FEATURES_MAPPING:
self.feature = self.FEATURES_MAPPING[self.feature]
if 'type... | the_stack_v2_python_sparse | flask_project/campaign_manager/insights_functions/_abstract_overpass_insight_function.py | russbiggs/MapCampaigner | train | 0 | |
cc15e2111cd96a422debe0d6bf491ae7cdd6723a | [
"self.x = kwargs.get('x')\nself.y = kwargs.get('y')\nself.z = kwargs.get('z')",
"self.x = kwargs['x']\nself.y = kwargs['y']\nself.z = kwargs['z']",
"ret = {}\nret['x'] = sockutil.dump(self.x)\nret['y'] = sockutil.dump(self.y)\nret['z'] = sockutil.dump(self.z)\nreturn ret"
] | <|body_start_0|>
self.x = kwargs.get('x')
self.y = kwargs.get('y')
self.z = kwargs.get('z')
<|end_body_0|>
<|body_start_1|>
self.x = kwargs['x']
self.y = kwargs['y']
self.z = kwargs['z']
<|end_body_1|>
<|body_start_2|>
ret = {}
ret['x'] = sockutil.dump(s... | Vector3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector3:
def __init__(self, **kwargs):
"""Params: x: float y: float z: float"""
<|body_0|>
def load(self, **kwargs):
"""load from dict Exception: KeyError"""
<|body_1|>
def dump(self):
"""dump -> dict"""
<|body_2|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_031338 | 26,590 | no_license | [
{
"docstring": "Params: x: float y: float z: float",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "load from dict Exception: KeyError",
"name": "load",
"signature": "def load(self, **kwargs)"
},
{
"docstring": "dump -> dict",
"name": "dump... | 3 | stack_v2_sparse_classes_30k_val_000773 | Implement the Python class `Vector3` described below.
Class description:
Implement the Vector3 class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Params: x: float y: float z: float
- def load(self, **kwargs): load from dict Exception: KeyError
- def dump(self): dump -> dict | Implement the Python class `Vector3` described below.
Class description:
Implement the Vector3 class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Params: x: float y: float z: float
- def load(self, **kwargs): load from dict Exception: KeyError
- def dump(self): dump -> dict
<|skeleton|>
class V... | aa0b2697e295889e8c23a7104889ea95f2a4b6b1 | <|skeleton|>
class Vector3:
def __init__(self, **kwargs):
"""Params: x: float y: float z: float"""
<|body_0|>
def load(self, **kwargs):
"""load from dict Exception: KeyError"""
<|body_1|>
def dump(self):
"""dump -> dict"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vector3:
def __init__(self, **kwargs):
"""Params: x: float y: float z: float"""
self.x = kwargs.get('x')
self.y = kwargs.get('y')
self.z = kwargs.get('z')
def load(self, **kwargs):
"""load from dict Exception: KeyError"""
self.x = kwargs['x']
self.y... | the_stack_v2_python_sparse | message.py | songhui17/Server | train | 0 | |
50826f3b46679394d20b51871a15055e3995b33f | [
"self.team = team\nself.series = []\nself.upcoming_series = []",
"try:\n return self.upcoming_series[0]\nexcept IndexError:\n return None"
] | <|body_start_0|>
self.team = team
self.series = []
self.upcoming_series = []
<|end_body_0|>
<|body_start_1|>
try:
return self.upcoming_series[0]
except IndexError:
return None
<|end_body_1|>
| A schedule for a baseball team's season. | TeamSchedule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamSchedule:
"""A schedule for a baseball team's season."""
def __init__(self, team):
"""Initialize a TeamSchedule object."""
<|body_0|>
def next_series(self):
"""Return the date and location of the next scheduled game as a tuple (ordinal_date, timestep, city)."... | stack_v2_sparse_classes_36k_train_031339 | 17,124 | no_license | [
{
"docstring": "Initialize a TeamSchedule object.",
"name": "__init__",
"signature": "def __init__(self, team)"
},
{
"docstring": "Return the date and location of the next scheduled game as a tuple (ordinal_date, timestep, city).",
"name": "next_series",
"signature": "def next_series(sel... | 2 | stack_v2_sparse_classes_30k_train_018920 | Implement the Python class `TeamSchedule` described below.
Class description:
A schedule for a baseball team's season.
Method signatures and docstrings:
- def __init__(self, team): Initialize a TeamSchedule object.
- def next_series(self): Return the date and location of the next scheduled game as a tuple (ordinal_da... | Implement the Python class `TeamSchedule` described below.
Class description:
A schedule for a baseball team's season.
Method signatures and docstrings:
- def __init__(self, team): Initialize a TeamSchedule object.
- def next_series(self): Return the date and location of the next scheduled game as a tuple (ordinal_da... | 78a9df3ff66d4956f817397c82be0b4e4176e73d | <|skeleton|>
class TeamSchedule:
"""A schedule for a baseball team's season."""
def __init__(self, team):
"""Initialize a TeamSchedule object."""
<|body_0|>
def next_series(self):
"""Return the date and location of the next scheduled game as a tuple (ordinal_date, timestep, city)."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamSchedule:
"""A schedule for a baseball team's season."""
def __init__(self, team):
"""Initialize a TeamSchedule object."""
self.team = team
self.series = []
self.upcoming_series = []
def next_series(self):
"""Return the date and location of the next schedu... | the_stack_v2_python_sparse | baseball/schedule.py | hanok2/national_pastime | train | 1 |
4dd71521fc9f541fa996d6d0e45f2b1f4d3ca673 | [
"if not root:\n return ''\nreturn str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)",
"def dfs(data):\n if not data:\n return\n val = data.popleft()\n if not val:\n return\n root = TreeNode(int(val))\n root.left = dfs(data)\n root.right = dfs(dat... | <|body_start_0|>
if not root:
return ''
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)
<|end_body_0|>
<|body_start_1|>
def dfs(data):
if not data:
return
val = data.popleft()
if not val:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_031340 | 6,040 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_006824 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 0324d247a5567745cc1a48b215066d4aa796abd8 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)
def deserialize(self, data):
"""Decodes ... | the_stack_v2_python_sparse | Tree/Codec.py | BruceHi/leetcode | train | 1 | |
a7cf54c599fbd40891752889487664bc3c85c998 | [
"self.dp = [0 for i in range(len(nums) + 1)]\nfor i in range(1, len(nums) + 1):\n self.dp[i] = self.dp[i - 1] + nums[i - 1]\nprint(self.dp)",
"if i > j:\n return 0\nelse:\n return self.dp[j + 1] - self.dp[i]"
] | <|body_start_0|>
self.dp = [0 for i in range(len(nums) + 1)]
for i in range(1, len(nums) + 1):
self.dp[i] = self.dp[i - 1] + nums[i - 1]
print(self.dp)
<|end_body_0|>
<|body_start_1|>
if i > j:
return 0
else:
return self.dp[j + 1] - self.dp[i]... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dp = [0 for i in range(len(nums) + 1)]
for i i... | stack_v2_sparse_classes_36k_train_031341 | 847 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | a330e92191642e2965939a06b050ca84d4ed11a6 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.dp = [0 for i in range(len(nums) + 1)]
for i in range(1, len(nums) + 1):
self.dp[i] = self.dp[i - 1] + nums[i - 1]
print(self.dp)
def sumRange(self, i, j):
""":type i: int :type j: int... | the_stack_v2_python_sparse | src/dps/range-sum-query-immutable-303.py | monpro/algorithm | train | 102 | |
fdda61069f20db9251ada9d4cef33f36a90ca8a5 | [
"super(WordSegmentation, self).__init__()\n'变量说明\\n\\t\\tself.default_speech_tag_filter: 默认词性标注过滤器(只保留相应词性)\\n\\t\\tself.stop_tokens: 分词停止符号\\n\\t\\tself.stop_words; 停止词\\n\\t\\t'\nself.default_speech_tag_filter = ['an', 'i', 'j', 'l', 'n', 'nr', 'nrfg', 'ns', 'nt', 'nz', 't', 'v', 'vd', 'vn', 'eng']\nself.stop_t... | <|body_start_0|>
super(WordSegmentation, self).__init__()
'变量说明\n\t\tself.default_speech_tag_filter: 默认词性标注过滤器(只保留相应词性)\n\t\tself.stop_tokens: 分词停止符号\n\t\tself.stop_words; 停止词\n\t\t'
self.default_speech_tag_filter = ['an', 'i', 'j', 'l', 'n', 'nr', 'nrfg', 'ns', 'nt', 'nz', 't', 'v', 'vd', 'vn... | 分词 | WordSegmentation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordSegmentation:
"""分词"""
def __init__(self, stop_words_file=None):
"""函数功能:默认构造函数 stop_words_file: 保存停止词的文件路径"""
<|body_0|>
def segment_text(self, text, lower=True, with_stop_words=True, speech_tag_filter=False):
"""函数功能:对text进行分词处理 text: 待处理文本 lower = True: 是否... | stack_v2_sparse_classes_36k_train_031342 | 6,042 | no_license | [
{
"docstring": "函数功能:默认构造函数 stop_words_file: 保存停止词的文件路径",
"name": "__init__",
"signature": "def __init__(self, stop_words_file=None)"
},
{
"docstring": "函数功能:对text进行分词处理 text: 待处理文本 lower = True: 是否将英语单词转化为小写 with_stop_words: 若为True,则用停止词集合来过滤(去掉停止词),否则不过滤 speech_tag_filter: 若为True,则使用默认的self.de... | 3 | stack_v2_sparse_classes_30k_train_017559 | Implement the Python class `WordSegmentation` described below.
Class description:
分词
Method signatures and docstrings:
- def __init__(self, stop_words_file=None): 函数功能:默认构造函数 stop_words_file: 保存停止词的文件路径
- def segment_text(self, text, lower=True, with_stop_words=True, speech_tag_filter=False): 函数功能:对text进行分词处理 text: 待... | Implement the Python class `WordSegmentation` described below.
Class description:
分词
Method signatures and docstrings:
- def __init__(self, stop_words_file=None): 函数功能:默认构造函数 stop_words_file: 保存停止词的文件路径
- def segment_text(self, text, lower=True, with_stop_words=True, speech_tag_filter=False): 函数功能:对text进行分词处理 text: 待... | 9855d6e69598f9cbf1652c3bcea27133a755c03c | <|skeleton|>
class WordSegmentation:
"""分词"""
def __init__(self, stop_words_file=None):
"""函数功能:默认构造函数 stop_words_file: 保存停止词的文件路径"""
<|body_0|>
def segment_text(self, text, lower=True, with_stop_words=True, speech_tag_filter=False):
"""函数功能:对text进行分词处理 text: 待处理文本 lower = True: 是否... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordSegmentation:
"""分词"""
def __init__(self, stop_words_file=None):
"""函数功能:默认构造函数 stop_words_file: 保存停止词的文件路径"""
super(WordSegmentation, self).__init__()
'变量说明\n\t\tself.default_speech_tag_filter: 默认词性标注过滤器(只保留相应词性)\n\t\tself.stop_tokens: 分词停止符号\n\t\tself.stop_words; 停止词\n\t\t... | the_stack_v2_python_sparse | TextRank/Segmentation.py | xc15071347094/ASExtractor | train | 0 |
03df5800ab78ca54a7509432f1635a3e1a0f1e7a | [
"self.validate(locals())\nsuper().__init__()\nself._num_qubits = num_qubits\nself._feature_dimension = num_qubits\nsig = signature(constructor_function)\nif len(sig.parameters) != len(feature_param) + 3:\n raise ValueError(\"The constructor_function given don't match the parameters given.\\n\" + 'Make sure it ta... | <|body_start_0|>
self.validate(locals())
super().__init__()
self._num_qubits = num_qubits
self._feature_dimension = num_qubits
sig = signature(constructor_function)
if len(sig.parameters) != len(feature_param) + 3:
raise ValueError("The constructor_function gi... | Mapping data the way you want | CustomExpansion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomExpansion:
"""Mapping data the way you want"""
def __init__(self, num_qubits, constructor_function, feature_param):
"""Constructor. Args: num_qubits (int): number of qubits constructor_function (fun): a function that takes as parameters a datum x, a QuantumRegister qr, a boolea... | stack_v2_sparse_classes_36k_train_031343 | 3,269 | no_license | [
{
"docstring": "Constructor. Args: num_qubits (int): number of qubits constructor_function (fun): a function that takes as parameters a datum x, a QuantumRegister qr, a boolean inverse and all other parameters needed from feature_param feature_param (list): the list of parameters needed to generate the circuit,... | 2 | stack_v2_sparse_classes_30k_train_018192 | Implement the Python class `CustomExpansion` described below.
Class description:
Mapping data the way you want
Method signatures and docstrings:
- def __init__(self, num_qubits, constructor_function, feature_param): Constructor. Args: num_qubits (int): number of qubits constructor_function (fun): a function that take... | Implement the Python class `CustomExpansion` described below.
Class description:
Mapping data the way you want
Method signatures and docstrings:
- def __init__(self, num_qubits, constructor_function, feature_param): Constructor. Args: num_qubits (int): number of qubits constructor_function (fun): a function that take... | 1a0ede661d4f741126c7735fc730b7e9fa4cf764 | <|skeleton|>
class CustomExpansion:
"""Mapping data the way you want"""
def __init__(self, num_qubits, constructor_function, feature_param):
"""Constructor. Args: num_qubits (int): number of qubits constructor_function (fun): a function that takes as parameters a datum x, a QuantumRegister qr, a boolea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomExpansion:
"""Mapping data the way you want"""
def __init__(self, num_qubits, constructor_function, feature_param):
"""Constructor. Args: num_qubits (int): number of qubits constructor_function (fun): a function that takes as parameters a datum x, a QuantumRegister qr, a boolean inverse and... | the_stack_v2_python_sparse | TESTQ/src/custom_map.py | rfclambert/validation | train | 2 |
1d70cbcac712844be9c88be9c98e5dbcf59c33ac | [
"try:\n serializer = AccountRecordKeepingSerializer(AccountRecordKeeping.objects.all(), many=True)\n return JsonResponse({'message': 'list of comments', 'data': serializer.data}, status=200)\nexcept Exception as e:\n logger.error(e, exc_info=True)\n return JsonResponse({'message': 'Something went wrong,... | <|body_start_0|>
try:
serializer = AccountRecordKeepingSerializer(AccountRecordKeeping.objects.all(), many=True)
return JsonResponse({'message': 'list of comments', 'data': serializer.data}, status=200)
except Exception as e:
logger.error(e, exc_info=True)
... | AccountRecordDataView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountRecordDataView:
def get(self, request):
"""Get all comments"""
<|body_0|>
def post(self, request):
"""Add comment"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
serializer = AccountRecordKeepingSerializer(AccountRecordKeepin... | stack_v2_sparse_classes_36k_train_031344 | 2,908 | no_license | [
{
"docstring": "Get all comments",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Add comment",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `AccountRecordDataView` described below.
Class description:
Implement the AccountRecordDataView class.
Method signatures and docstrings:
- def get(self, request): Get all comments
- def post(self, request): Add comment | Implement the Python class `AccountRecordDataView` described below.
Class description:
Implement the AccountRecordDataView class.
Method signatures and docstrings:
- def get(self, request): Get all comments
- def post(self, request): Add comment
<|skeleton|>
class AccountRecordDataView:
def get(self, request):
... | 367cccca72f0eae6c3ccb70fabb371dc905f915e | <|skeleton|>
class AccountRecordDataView:
def get(self, request):
"""Get all comments"""
<|body_0|>
def post(self, request):
"""Add comment"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountRecordDataView:
def get(self, request):
"""Get all comments"""
try:
serializer = AccountRecordKeepingSerializer(AccountRecordKeeping.objects.all(), many=True)
return JsonResponse({'message': 'list of comments', 'data': serializer.data}, status=200)
except... | the_stack_v2_python_sparse | course/views/account_record_view.py | vshaladhav97/first_kick | train | 0 | |
69dabb5cae8f3acf96361909db046b93be96c126 | [
"self.digits = digits\nself.number_of_guesses = 0\nif guesser == 'human':\n self.chosen_number = self.create_num(digits)",
"final_number = []\nfirst_digit = randrange(1, 10)\nfinal_number.append(first_digit)\ninfinite_loop_prevention = 0\nwhile len(final_number) < digits:\n infinite_loop_prevention += 1\n ... | <|body_start_0|>
self.digits = digits
self.number_of_guesses = 0
if guesser == 'human':
self.chosen_number = self.create_num(digits)
<|end_body_0|>
<|body_start_1|>
final_number = []
first_digit = randrange(1, 10)
final_number.append(first_digit)
infi... | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
def __init__(self, guesser='human', digits=3):
"""Each game stores the number of guesses as an attribute. You will be able to choose whether the human player or the computer player will be the guesser and it will change how the game is played."""
<|body_0|>
def create_... | stack_v2_sparse_classes_36k_train_031345 | 9,238 | no_license | [
{
"docstring": "Each game stores the number of guesses as an attribute. You will be able to choose whether the human player or the computer player will be the guesser and it will change how the game is played.",
"name": "__init__",
"signature": "def __init__(self, guesser='human', digits=3)"
},
{
... | 3 | stack_v2_sparse_classes_30k_val_000534 | Implement the Python class `Game` described below.
Class description:
Implement the Game class.
Method signatures and docstrings:
- def __init__(self, guesser='human', digits=3): Each game stores the number of guesses as an attribute. You will be able to choose whether the human player or the computer player will be ... | Implement the Python class `Game` described below.
Class description:
Implement the Game class.
Method signatures and docstrings:
- def __init__(self, guesser='human', digits=3): Each game stores the number of guesses as an attribute. You will be able to choose whether the human player or the computer player will be ... | beadb0cd62c8f3b4fc1f47f2975e97e939e8419e | <|skeleton|>
class Game:
def __init__(self, guesser='human', digits=3):
"""Each game stores the number of guesses as an attribute. You will be able to choose whether the human player or the computer player will be the guesser and it will change how the game is played."""
<|body_0|>
def create_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Game:
def __init__(self, guesser='human', digits=3):
"""Each game stores the number of guesses as an attribute. You will be able to choose whether the human player or the computer player will be the guesser and it will change how the game is played."""
self.digits = digits
self.number_... | the_stack_v2_python_sparse | StudentWork/RachelKlein/bagels.py | kevinelong/PM_2015_SUMMER | train | 4 | |
8f5f8b22d8c33add339fb30b721e08604d818ecd | [
"nums.sort()\nn = len(nums)\ntmp = list()\nans = list()\nfor i in range(n - 1, 1, -1):\n a = nums[i]\n for k in range(i - 1, 0, -1):\n b = nums[k]\n for j in range(k - 1, -1, -1):\n c = nums[j]\n if a + b + c == 0:\n tmp.append([a, b, c])\nfor li in tmp:\n ... | <|body_start_0|>
nums.sort()
n = len(nums)
tmp = list()
ans = list()
for i in range(n - 1, 1, -1):
a = nums[i]
for k in range(i - 1, 0, -1):
b = nums[k]
for j in range(k - 1, -1, -1):
c = nums[j]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum_1(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
def threeSum2(self, nums):
""":type nums: List[int] :rty... | stack_v2_sparse_classes_36k_train_031346 | 5,602 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum_1",
"signature": "def threeSum_1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
},
{
"docstring": ":type ... | 3 | stack_v2_sparse_classes_30k_test_000861 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum_1(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum_1(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :... | 3f7b2ea959308eb80f4c65be35aaeed666570f80 | <|skeleton|>
class Solution:
def threeSum_1(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
def threeSum2(self, nums):
""":type nums: List[int] :rty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum_1(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
nums.sort()
n = len(nums)
tmp = list()
ans = list()
for i in range(n - 1, 1, -1):
a = nums[i]
for k in range(i - 1, 0, -1):
b = nums... | the_stack_v2_python_sparse | 15.三数之和.py | dxc19951001/Everyday_LeetCode | train | 1 | |
c434301b419622051811bac1f33eca3a15f58d69 | [
"super(PaintingGenreBot, self).__init__()\nself.use_from_page = False\nself.genres = {u'Q1400853': u'Q134307', u'Q2414609': u'Q2864737', u'Q214127': u'Q1047337', u'Q107425': u'Q191163', u'Q333357': u'Q128115', u'Q18535': u'Q2839016', u'Q11766730': u'Q2839016', u'Q11766734': u'Q158607', u'Q3368492': u'Q390001'}\nsel... | <|body_start_0|>
super(PaintingGenreBot, self).__init__()
self.use_from_page = False
self.genres = {u'Q1400853': u'Q134307', u'Q2414609': u'Q2864737', u'Q214127': u'Q1047337', u'Q107425': u'Q191163', u'Q333357': u'Q128115', u'Q18535': u'Q2839016', u'Q11766730': u'Q2839016', u'Q11766734': u'Q1586... | A bot to normalize painting genre. Uses the WikidataBot for the basics. | PaintingGenreBot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaintingGenreBot:
"""A bot to normalize painting genre. Uses the WikidataBot for the basics."""
def __init__(self):
"""No arguments, bot makes it's own generator based on the genres"""
<|body_0|>
def getGenerator(self):
"""Get a generator of paintings that have o... | stack_v2_sparse_classes_36k_train_031347 | 3,110 | no_license | [
{
"docstring": "No arguments, bot makes it's own generator based on the genres",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get a generator of paintings that have one of the replacable genres :return: A generator that yields ItemPages",
"name": "getGenerator",
... | 3 | stack_v2_sparse_classes_30k_train_018512 | Implement the Python class `PaintingGenreBot` described below.
Class description:
A bot to normalize painting genre. Uses the WikidataBot for the basics.
Method signatures and docstrings:
- def __init__(self): No arguments, bot makes it's own generator based on the genres
- def getGenerator(self): Get a generator of ... | Implement the Python class `PaintingGenreBot` described below.
Class description:
A bot to normalize painting genre. Uses the WikidataBot for the basics.
Method signatures and docstrings:
- def __init__(self): No arguments, bot makes it's own generator based on the genres
- def getGenerator(self): Get a generator of ... | b1786deb7f9d27107410290b0d759f8db6098dd9 | <|skeleton|>
class PaintingGenreBot:
"""A bot to normalize painting genre. Uses the WikidataBot for the basics."""
def __init__(self):
"""No arguments, bot makes it's own generator based on the genres"""
<|body_0|>
def getGenerator(self):
"""Get a generator of paintings that have o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaintingGenreBot:
"""A bot to normalize painting genre. Uses the WikidataBot for the basics."""
def __init__(self):
"""No arguments, bot makes it's own generator based on the genres"""
super(PaintingGenreBot, self).__init__()
self.use_from_page = False
self.genres = {u'Q14... | the_stack_v2_python_sparse | bot/wikidata/painting_genre_normalization.py | fuzheado/toollabs | train | 0 |
775d42f5074d4794b28dc3b49f640b100d36edf6 | [
"if not digits:\n return []\ndc_map = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\ncombinations = [[]]\nfor d in digits:\n self.append_comb(combinations, dc_map[d])\nreturn [''.join(comb) for comb in combinations]",
"len_chars = len(chars)\nnew_combinat... | <|body_start_0|>
if not digits:
return []
dc_map = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
combinations = [[]]
for d in digits:
self.append_comb(combinations, dc_map[d])
return [''.join(comb) for c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def append_comb(self, combinations, chars):
"""Assumes len(combinations) > 0 and len(chars) > 0."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if ... | stack_v2_sparse_classes_36k_train_031348 | 1,061 | no_license | [
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits)"
},
{
"docstring": "Assumes len(combinations) > 0 and len(chars) > 0.",
"name": "append_comb",
"signature": "def append_comb(self, combinations, chars)"
... | 2 | stack_v2_sparse_classes_30k_train_009808 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def append_comb(self, combinations, chars): Assumes len(combinations) > 0 and len(chars) > 0. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def append_comb(self, combinations, chars): Assumes len(combinations) > 0 and len(chars) > 0.
<|skele... | 9f4a6a2c301233eae64f450c1f7258733d3f9bbc | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def append_comb(self, combinations, chars):
"""Assumes len(combinations) > 0 and len(chars) > 0."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
if not digits:
return []
dc_map = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
combinations = [[]]
for d in digits... | the_stack_v2_python_sparse | leetcode/17-letter-combinations-of-a-phone-number.py | nickwu241/coding-problems | train | 0 | |
b38989d148a7bdbe085c2511acd1689c1b1fa96c | [
"if minfo is None:\n minfo = {}\nsuper(DumpNodeStatsMessage, self).__init__(minfo)\nself.IsSystemMessage = False\nself.IsForward = True\nself.IsReliable = True\nself.DomainList = minfo.get('DomainList', [])\nself.MetricList = minfo.get('MetricList', [])",
"result = super(DumpNodeStatsMessage, self).dump()\nres... | <|body_start_0|>
if minfo is None:
minfo = {}
super(DumpNodeStatsMessage, self).__init__(minfo)
self.IsSystemMessage = False
self.IsForward = True
self.IsReliable = True
self.DomainList = minfo.get('DomainList', [])
self.MetricList = minfo.get('MetricL... | Dump node stats messages are sent to a peer node to request it to dump statistics. Attributes: DumpNodeStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. System messages have special delivery priority rules. IsForward (bool): Whether the messa... | DumpNodeStatsMessage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DumpNodeStatsMessage:
"""Dump node stats messages are sent to a peer node to request it to dump statistics. Attributes: DumpNodeStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. System messages have special delivery pri... | stack_v2_sparse_classes_36k_train_031349 | 13,482 | permissive | [
{
"docstring": "Constructor for the DumpNodeStatsMessage class. Args: minfo (dict): Dictionary of values for message fields.",
"name": "__init__",
"signature": "def __init__(self, minfo=None)"
},
{
"docstring": "Dumps a dict containing object attributes. Returns: dict: A mapping of object attrib... | 2 | stack_v2_sparse_classes_30k_train_017074 | Implement the Python class `DumpNodeStatsMessage` described below.
Class description:
Dump node stats messages are sent to a peer node to request it to dump statistics. Attributes: DumpNodeStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. Sy... | Implement the Python class `DumpNodeStatsMessage` described below.
Class description:
Dump node stats messages are sent to a peer node to request it to dump statistics. Attributes: DumpNodeStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. Sy... | 8f4ca1aab54ef420a0db10c8ca822ec8686cd423 | <|skeleton|>
class DumpNodeStatsMessage:
"""Dump node stats messages are sent to a peer node to request it to dump statistics. Attributes: DumpNodeStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. System messages have special delivery pri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DumpNodeStatsMessage:
"""Dump node stats messages are sent to a peer node to request it to dump statistics. Attributes: DumpNodeStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. System messages have special delivery priority rules. ... | the_stack_v2_python_sparse | validator/gossip/messages/gossip_debug.py | aludvik/sawtooth-core | train | 0 |
95cb892b497977ac3d686e1675a875343199f525 | [
"try:\n import pyobo\nexcept ImportError:\n raise ImportError(f'Can not use {self.__class__.__name__} because pyobo is not installed.')\nelse:\n self._get_name = pyobo.get_name\nsuper().__init__(*args, **kwargs)",
"import bioregistry\nres: List[Optional[str]] = []\nfor curie in identifiers:\n try:\n ... | <|body_start_0|>
try:
import pyobo
except ImportError:
raise ImportError(f'Can not use {self.__class__.__name__} because pyobo is not installed.')
else:
self._get_name = pyobo.get_name
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
... | A cache that looks up labels of biomedical entities based on their CURIEs. | PyOBOCache | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyOBOCache:
"""A cache that looks up labels of biomedical entities based on their CURIEs."""
def __init__(self, *args, **kwargs):
"""Instantiate the PyOBO cache, ensuring PyOBO is installed."""
<|body_0|>
def get_texts(self, identifiers: Sequence[str]) -> Sequence[Option... | stack_v2_sparse_classes_36k_train_031350 | 21,962 | permissive | [
{
"docstring": "Instantiate the PyOBO cache, ensuring PyOBO is installed.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Get text for the given CURIEs. :param identifiers: The compact URIs for each entity (e.g., ``['doid:1234', ...]``) :return: the la... | 2 | null | Implement the Python class `PyOBOCache` described below.
Class description:
A cache that looks up labels of biomedical entities based on their CURIEs.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Instantiate the PyOBO cache, ensuring PyOBO is installed.
- def get_texts(self, identifiers: S... | Implement the Python class `PyOBOCache` described below.
Class description:
A cache that looks up labels of biomedical entities based on their CURIEs.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Instantiate the PyOBO cache, ensuring PyOBO is installed.
- def get_texts(self, identifiers: S... | 5ff3597b18ab9a220e34361d3c3f262060811df1 | <|skeleton|>
class PyOBOCache:
"""A cache that looks up labels of biomedical entities based on their CURIEs."""
def __init__(self, *args, **kwargs):
"""Instantiate the PyOBO cache, ensuring PyOBO is installed."""
<|body_0|>
def get_texts(self, identifiers: Sequence[str]) -> Sequence[Option... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyOBOCache:
"""A cache that looks up labels of biomedical entities based on their CURIEs."""
def __init__(self, *args, **kwargs):
"""Instantiate the PyOBO cache, ensuring PyOBO is installed."""
try:
import pyobo
except ImportError:
raise ImportError(f'Can n... | the_stack_v2_python_sparse | src/pykeen/nn/utils.py | pykeen/pykeen | train | 1,308 |
673fb4c9cd976fdcb419094b361f49c6b593bdf7 | [
"script = script if isinstance(script, (bytes, bytearray)) else script.to_script()\nscript = bytes(script) if isinstance(script, bytearray) else script\nself = super(__class__, cls).__new__(cls, script)\nself.message = cls._script_message_cache.get(self.script)\nif self.message is None:\n self.message = Message.... | <|body_start_0|>
script = script if isinstance(script, (bytes, bytearray)) else script.to_script()
script = bytes(script) if isinstance(script, bytearray) else script
self = super(__class__, cls).__new__(cls, script)
self.message = cls._script_message_cache.get(self.script)
if se... | Encapsulates a parsed, valid SLP OP_RETURN output script. NB: hash(self) just calls superclass hash -- which hashes the script bytes.. the .message object is ignored from the hash (it is always derived from the script bytes anyway in a well formed instance). self.message should *NOT* be written-to by outside code! It s... | ScriptOutput | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScriptOutput:
"""Encapsulates a parsed, valid SLP OP_RETURN output script. NB: hash(self) just calls superclass hash -- which hashes the script bytes.. the .message object is ignored from the hash (it is always derived from the script bytes anyway in a well formed instance). self.message should *... | stack_v2_sparse_classes_36k_train_031351 | 38,922 | permissive | [
{
"docstring": "Instantiate from a script (or address.ScriptOutput) you wish to parse.",
"name": "__new__",
"signature": "def __new__(cls, script)"
},
{
"docstring": "Returns True if the passed-in bytes are a valid OP_RETURN script for SLP.",
"name": "protocol_match",
"signature": "def p... | 2 | stack_v2_sparse_classes_30k_train_001835 | Implement the Python class `ScriptOutput` described below.
Class description:
Encapsulates a parsed, valid SLP OP_RETURN output script. NB: hash(self) just calls superclass hash -- which hashes the script bytes.. the .message object is ignored from the hash (it is always derived from the script bytes anyway in a well ... | Implement the Python class `ScriptOutput` described below.
Class description:
Encapsulates a parsed, valid SLP OP_RETURN output script. NB: hash(self) just calls superclass hash -- which hashes the script bytes.. the .message object is ignored from the hash (it is always derived from the script bytes anyway in a well ... | 57176a00e4d660487c41b92207da4bf27e5c0026 | <|skeleton|>
class ScriptOutput:
"""Encapsulates a parsed, valid SLP OP_RETURN output script. NB: hash(self) just calls superclass hash -- which hashes the script bytes.. the .message object is ignored from the hash (it is always derived from the script bytes anyway in a well formed instance). self.message should *... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScriptOutput:
"""Encapsulates a parsed, valid SLP OP_RETURN output script. NB: hash(self) just calls superclass hash -- which hashes the script bytes.. the .message object is ignored from the hash (it is always derived from the script bytes anyway in a well formed instance). self.message should *NOT* be writt... | the_stack_v2_python_sparse | electrum/electrumabc/slp/slp.py | Bitcoin-ABC/bitcoin-abc | train | 1,359 |
06bfe1e3051ddf851cce777e02ff4830c5d93536 | [
"assert not cls._is_initialized\nassert isinstance(filepaths, list)\nassert all((isinstance(filepath, str) for filepath in filepaths))\ncls._features = {}\nfor filepath in filepaths:\n with open(filepath, encoding='utf-8') as file_obj:\n datastore = json5.load(file_obj)\n for entry in datastore['data']... | <|body_start_0|>
assert not cls._is_initialized
assert isinstance(filepaths, list)
assert all((isinstance(filepath, str) for filepath in filepaths))
cls._features = {}
for filepath in filepaths:
with open(filepath, encoding='utf-8') as file_obj:
datast... | Represents a set of definitions of runtime enabled features. | RuntimeEnabledFeatures | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RuntimeEnabledFeatures:
"""Represents a set of definitions of runtime enabled features."""
def init(cls, filepaths):
"""Args: filepaths: Paths to the definition files of runtime-enabled features ("runtime_enabled_features.json5")."""
<|body_0|>
def is_context_dependent(c... | stack_v2_sparse_classes_36k_train_031352 | 1,596 | permissive | [
{
"docstring": "Args: filepaths: Paths to the definition files of runtime-enabled features (\"runtime_enabled_features.json5\").",
"name": "init",
"signature": "def init(cls, filepaths)"
},
{
"docstring": "Returns True if the feature may be enabled per-context.",
"name": "is_context_dependen... | 2 | null | Implement the Python class `RuntimeEnabledFeatures` described below.
Class description:
Represents a set of definitions of runtime enabled features.
Method signatures and docstrings:
- def init(cls, filepaths): Args: filepaths: Paths to the definition files of runtime-enabled features ("runtime_enabled_features.json5... | Implement the Python class `RuntimeEnabledFeatures` described below.
Class description:
Represents a set of definitions of runtime enabled features.
Method signatures and docstrings:
- def init(cls, filepaths): Args: filepaths: Paths to the definition files of runtime-enabled features ("runtime_enabled_features.json5... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class RuntimeEnabledFeatures:
"""Represents a set of definitions of runtime enabled features."""
def init(cls, filepaths):
"""Args: filepaths: Paths to the definition files of runtime-enabled features ("runtime_enabled_features.json5")."""
<|body_0|>
def is_context_dependent(c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RuntimeEnabledFeatures:
"""Represents a set of definitions of runtime enabled features."""
def init(cls, filepaths):
"""Args: filepaths: Paths to the definition files of runtime-enabled features ("runtime_enabled_features.json5")."""
assert not cls._is_initialized
assert isinstanc... | the_stack_v2_python_sparse | third_party/blink/renderer/bindings/scripts/web_idl/runtime_enabled_features.py | chromium/chromium | train | 17,408 |
e55f33c7b0f809e8883b0497f85c1d974b40bfb8 | [
"if not root:\n return True\n\ndef isBSTHelper(node, lower_limit, upper_limit):\n if lower_limit is not None and node.val <= lower_limit:\n return False\n if upper_limit is not None and upper_limit <= node.val:\n return False\n left = isBSTHelper(node.left, lower_limit, node.val) if node.l... | <|body_start_0|>
if not root:
return True
def isBSTHelper(node, lower_limit, upper_limit):
if lower_limit is not None and node.val <= lower_limit:
return False
if upper_limit is not None and upper_limit <= node.val:
return False
... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def isValidBST1(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isValidBST2(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
... | stack_v2_sparse_classes_36k_train_031353 | 4,580 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isValidBST1",
"signature": "def isValidBST1(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isValidBST2",
"signature": "def isValidBST2(self, root)"
},
{
"docstring": ":type root: TreeNode :... | 3 | null | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def isValidBST1(self, root): :type root: TreeNode :rtype: bool
- def isValidBST2(self, root): :type root: TreeNode :rtype: bool
- def isValidBST(self, root): :type root: TreeNo... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def isValidBST1(self, root): :type root: TreeNode :rtype: bool
- def isValidBST2(self, root): :type root: TreeNode :rtype: bool
- def isValidBST(self, root): :type root: TreeNo... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution1:
def isValidBST1(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isValidBST2(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def isValidBST1(self, root):
""":type root: TreeNode :rtype: bool"""
if not root:
return True
def isBSTHelper(node, lower_limit, upper_limit):
if lower_limit is not None and node.val <= lower_limit:
return False
if upper_l... | the_stack_v2_python_sparse | BST/q098_validate_binary_search_tree.py | sevenhe716/LeetCode | train | 0 | |
728950db8566de00e1ed17390c14d5bdabba0c12 | [
"super(CAServerCert, self).__init__(None, config.kubeconfig, verbose)\nself.config = config\nself.verbose = verbose",
"cert = self.config.config_options['cert']['value']\nif cert and os.path.exists(cert):\n return open(cert).read()\nreturn None",
"if self.config.config_options['backup']['value']:\n import... | <|body_start_0|>
super(CAServerCert, self).__init__(None, config.kubeconfig, verbose)
self.config = config
self.verbose = verbose
<|end_body_0|>
<|body_start_1|>
cert = self.config.config_options['cert']['value']
if cert and os.path.exists(cert):
return open(cert).re... | Class to wrap the oc adm ca create-server-cert command line | CAServerCert | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CAServerCert:
"""Class to wrap the oc adm ca create-server-cert command line"""
def __init__(self, config, verbose=False):
"""Constructor for oadm ca"""
<|body_0|>
def get(self):
"""get the current cert file If a file exists by the same name in the specified loca... | stack_v2_sparse_classes_36k_train_031354 | 6,137 | permissive | [
{
"docstring": "Constructor for oadm ca",
"name": "__init__",
"signature": "def __init__(self, config, verbose=False)"
},
{
"docstring": "get the current cert file If a file exists by the same name in the specified location then the cert exists",
"name": "get",
"signature": "def get(self... | 5 | stack_v2_sparse_classes_30k_train_013564 | Implement the Python class `CAServerCert` described below.
Class description:
Class to wrap the oc adm ca create-server-cert command line
Method signatures and docstrings:
- def __init__(self, config, verbose=False): Constructor for oadm ca
- def get(self): get the current cert file If a file exists by the same name ... | Implement the Python class `CAServerCert` described below.
Class description:
Class to wrap the oc adm ca create-server-cert command line
Method signatures and docstrings:
- def __init__(self, config, verbose=False): Constructor for oadm ca
- def get(self): get the current cert file If a file exists by the same name ... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class CAServerCert:
"""Class to wrap the oc adm ca create-server-cert command line"""
def __init__(self, config, verbose=False):
"""Constructor for oadm ca"""
<|body_0|>
def get(self):
"""get the current cert file If a file exists by the same name in the specified loca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CAServerCert:
"""Class to wrap the oc adm ca create-server-cert command line"""
def __init__(self, config, verbose=False):
"""Constructor for oadm ca"""
super(CAServerCert, self).__init__(None, config.kubeconfig, verbose)
self.config = config
self.verbose = verbose
de... | the_stack_v2_python_sparse | openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/src/class/oc_adm_ca_server_cert.py | openshift/openshift-tools | train | 170 |
00f121880a7a9d7cb86d44e8cbf79c34afeacd4c | [
"for key, value in named.items():\n setattr(self, key, value)\nsuper(_MouseChangeEvent, self).__init__()",
"base = event.__dict__.copy()\ntry:\n del base['visitedNodes']\nexcept KeyError:\n pass\nreturn cls(lastPath=lastPath, newPath=newPath, **base)"
] | <|body_start_0|>
for key, value in named.items():
setattr(self, key, value)
super(_MouseChangeEvent, self).__init__()
<|end_body_0|>
<|body_start_1|>
base = event.__dict__.copy()
try:
del base['visitedNodes']
except KeyError:
pass
retu... | Base class for mouse in/out events The mouse in/out event types are "synthetic", that is, they are generated by other events when certain conditions are true. The change events allow for easily constructing common interface elements such as mouse-overs. Attributes: lastPath -- previous value for target path, in essence... | _MouseChangeEvent | [
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _MouseChangeEvent:
"""Base class for mouse in/out events The mouse in/out event types are "synthetic", that is, they are generated by other events when certain conditions are true. The change events allow for easily constructing common interface elements such as mouse-overs. Attributes: lastPath ... | stack_v2_sparse_classes_36k_train_031355 | 16,446 | permissive | [
{
"docstring": "Initialise the event with named attributes",
"name": "__init__",
"signature": "def __init__(self, **named)"
},
{
"docstring": "Construct synthetic mouse event from a move event",
"name": "fromMoveEvent",
"signature": "def fromMoveEvent(cls, event, lastPath, newPath)"
}
... | 2 | null | Implement the Python class `_MouseChangeEvent` described below.
Class description:
Base class for mouse in/out events The mouse in/out event types are "synthetic", that is, they are generated by other events when certain conditions are true. The change events allow for easily constructing common interface elements suc... | Implement the Python class `_MouseChangeEvent` described below.
Class description:
Base class for mouse in/out events The mouse in/out event types are "synthetic", that is, they are generated by other events when certain conditions are true. The change events allow for easily constructing common interface elements suc... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class _MouseChangeEvent:
"""Base class for mouse in/out events The mouse in/out event types are "synthetic", that is, they are generated by other events when certain conditions are true. The change events allow for easily constructing common interface elements such as mouse-overs. Attributes: lastPath ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _MouseChangeEvent:
"""Base class for mouse in/out events The mouse in/out event types are "synthetic", that is, they are generated by other events when certain conditions are true. The change events allow for easily constructing common interface elements such as mouse-overs. Attributes: lastPath -- previous v... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/events/mouseevents.py | alexus37/AugmentedRealityChess | train | 1 |
dceca208eab9294cc8245a1c414a46b1e09a6f14 | [
"super(AuxiliaryHead, self).__init__()\nk = 4\nif large_images:\n k = 7\nself.features = nn.Sequential(nn.ReLU(inplace=True), nn.AvgPool2d(k, stride=k, padding=0), nn.Conv2d(C, 128, 1, bias=False), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.Conv2d(128, 768, 2, bias=False), nn.BatchNorm2d(768), nn.ReLU(inplac... | <|body_start_0|>
super(AuxiliaryHead, self).__init__()
k = 4
if large_images:
k = 7
self.features = nn.Sequential(nn.ReLU(inplace=True), nn.AvgPool2d(k, stride=k, padding=0), nn.Conv2d(C, 128, 1, bias=False), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.Conv2d(128, 768, 2, ... | Auxiliary head. | AuxiliaryHead | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuxiliaryHead:
"""Auxiliary head."""
def __init__(self, C, num_classes, large_images):
"""Assuming input size 8x8 if large_images then the input will be 14x14."""
<|body_0|>
def forward(self, x):
"""Forward method."""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_031356 | 1,451 | permissive | [
{
"docstring": "Assuming input size 8x8 if large_images then the input will be 14x14.",
"name": "__init__",
"signature": "def __init__(self, C, num_classes, large_images)"
},
{
"docstring": "Forward method.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | null | Implement the Python class `AuxiliaryHead` described below.
Class description:
Auxiliary head.
Method signatures and docstrings:
- def __init__(self, C, num_classes, large_images): Assuming input size 8x8 if large_images then the input will be 14x14.
- def forward(self, x): Forward method. | Implement the Python class `AuxiliaryHead` described below.
Class description:
Auxiliary head.
Method signatures and docstrings:
- def __init__(self, C, num_classes, large_images): Assuming input size 8x8 if large_images then the input will be 14x14.
- def forward(self, x): Forward method.
<|skeleton|>
class Auxilia... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class AuxiliaryHead:
"""Auxiliary head."""
def __init__(self, C, num_classes, large_images):
"""Assuming input size 8x8 if large_images then the input will be 14x14."""
<|body_0|>
def forward(self, x):
"""Forward method."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuxiliaryHead:
"""Auxiliary head."""
def __init__(self, C, num_classes, large_images):
"""Assuming input size 8x8 if large_images then the input will be 14x14."""
super(AuxiliaryHead, self).__init__()
k = 4
if large_images:
k = 7
self.features = nn.Sequ... | the_stack_v2_python_sparse | zeus/networks/pytorch/heads/auxiliary_head.py | huawei-noah/xingtian | train | 308 |
b410da82ce1241cf2323610802211b47a8d15870 | [
"average_fund = numpy.average(month_fund_yield)\nfund_difference_sum = 0\nfor i in range(len(month_fund_yield)):\n fund_difference_sum += pow(month_fund_yield[i] - average_fund, 3)\nstandard_deviation = StandardDeviation.standard_deviation(month_earning_list=month_fund_yield)\nskewness = len(month_fund_yield) / ... | <|body_start_0|>
average_fund = numpy.average(month_fund_yield)
fund_difference_sum = 0
for i in range(len(month_fund_yield)):
fund_difference_sum += pow(month_fund_yield[i] - average_fund, 3)
standard_deviation = StandardDeviation.standard_deviation(month_earning_list=month_... | Skewness | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Skewness:
def skewness(month_fund_yield: list):
"""计算偏度,需要对应的基金月度收益率和标准差"""
<|body_0|>
def skewness_pandas(month_fund_yield: list):
"""使用pandas函数计算偏度,需要对应的基金月度收益率和标准差"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
average_fund = numpy.average(month... | stack_v2_sparse_classes_36k_train_031357 | 1,893 | no_license | [
{
"docstring": "计算偏度,需要对应的基金月度收益率和标准差",
"name": "skewness",
"signature": "def skewness(month_fund_yield: list)"
},
{
"docstring": "使用pandas函数计算偏度,需要对应的基金月度收益率和标准差",
"name": "skewness_pandas",
"signature": "def skewness_pandas(month_fund_yield: list)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015154 | Implement the Python class `Skewness` described below.
Class description:
Implement the Skewness class.
Method signatures and docstrings:
- def skewness(month_fund_yield: list): 计算偏度,需要对应的基金月度收益率和标准差
- def skewness_pandas(month_fund_yield: list): 使用pandas函数计算偏度,需要对应的基金月度收益率和标准差 | Implement the Python class `Skewness` described below.
Class description:
Implement the Skewness class.
Method signatures and docstrings:
- def skewness(month_fund_yield: list): 计算偏度,需要对应的基金月度收益率和标准差
- def skewness_pandas(month_fund_yield: list): 使用pandas函数计算偏度,需要对应的基金月度收益率和标准差
<|skeleton|>
class Skewness:
def ... | eae782a78ffde1276a0812a43d7deefb0bdedeb4 | <|skeleton|>
class Skewness:
def skewness(month_fund_yield: list):
"""计算偏度,需要对应的基金月度收益率和标准差"""
<|body_0|>
def skewness_pandas(month_fund_yield: list):
"""使用pandas函数计算偏度,需要对应的基金月度收益率和标准差"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Skewness:
def skewness(month_fund_yield: list):
"""计算偏度,需要对应的基金月度收益率和标准差"""
average_fund = numpy.average(month_fund_yield)
fund_difference_sum = 0
for i in range(len(month_fund_yield)):
fund_difference_sum += pow(month_fund_yield[i] - average_fund, 3)
standa... | the_stack_v2_python_sparse | public_method/indicator_calculation_method/skewness.py | liufubin-git/python | train | 0 | |
70716cd42162faaa4fb32feda47f1aea36b63610 | [
"schema = getattr(cls, '__schema__')\nif schema is None:\n raise Exception(f'{cls.__name__}: not serializable; missing schema')\nreturn schema",
"d = self.schema().dump(self) if camel_case else {humps.decamelize(k): v for k, v in self.schema().dump(self).items()}\nif drop_nulls:\n d = _drop_nulls(d)\ns = js... | <|body_start_0|>
schema = getattr(cls, '__schema__')
if schema is None:
raise Exception(f'{cls.__name__}: not serializable; missing schema')
return schema
<|end_body_0|>
<|body_start_1|>
d = self.schema().dump(self) if camel_case else {humps.decamelize(k): v for k, v in self... | Marks that a class is serializeable to JSON. | Serializable | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Serializable:
"""Marks that a class is serializeable to JSON."""
def schema(cls):
"""Gets the marshmallow serializer for the implementing class."""
<|body_0|>
def to_json(self, camel_case: bool=True, pretty_print: bool=True, drop_nulls: bool=False) -> str:
"""Con... | stack_v2_sparse_classes_36k_train_031358 | 2,677 | permissive | [
{
"docstring": "Gets the marshmallow serializer for the implementing class.",
"name": "schema",
"signature": "def schema(cls)"
},
{
"docstring": "Convert an implementing instance to JSON. Parameters ---------- camel_case : bool (default True) If True, the keys of the returned dict will be camel-... | 3 | stack_v2_sparse_classes_30k_train_010980 | Implement the Python class `Serializable` described below.
Class description:
Marks that a class is serializeable to JSON.
Method signatures and docstrings:
- def schema(cls): Gets the marshmallow serializer for the implementing class.
- def to_json(self, camel_case: bool=True, pretty_print: bool=True, drop_nulls: bo... | Implement the Python class `Serializable` described below.
Class description:
Marks that a class is serializeable to JSON.
Method signatures and docstrings:
- def schema(cls): Gets the marshmallow serializer for the implementing class.
- def to_json(self, camel_case: bool=True, pretty_print: bool=True, drop_nulls: bo... | dca436188e062fd07dfe589ee61e8bb97aa3ea98 | <|skeleton|>
class Serializable:
"""Marks that a class is serializeable to JSON."""
def schema(cls):
"""Gets the marshmallow serializer for the implementing class."""
<|body_0|>
def to_json(self, camel_case: bool=True, pretty_print: bool=True, drop_nulls: bool=False) -> str:
"""Con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Serializable:
"""Marks that a class is serializeable to JSON."""
def schema(cls):
"""Gets the marshmallow serializer for the implementing class."""
schema = getattr(cls, '__schema__')
if schema is None:
raise Exception(f'{cls.__name__}: not serializable; missing schema... | the_stack_v2_python_sparse | core/json.py | clohr/model-service | train | 1 |
f7fd502b26252f96f3188a2afd10bc975f75ab9b | [
"parser.add_argument('config', metavar='INSTANCE_CONFIG', completer=flags.InstanceConfigCompleter, help=\"Cloud Spanner instance configuration. The 'custom-' prefix is required to avoid name conflicts with Google-managed configurations.\")\nparser.add_argument('--display-name', help='The name of this instance confi... | <|body_start_0|>
parser.add_argument('config', metavar='INSTANCE_CONFIG', completer=flags.InstanceConfigCompleter, help="Cloud Spanner instance configuration. The 'custom-' prefix is required to avoid name conflicts with Google-managed configurations.")
parser.add_argument('--display-name', help='The na... | Create a Cloud Spanner instance configuration. | Create | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Create:
"""Create a Cloud Spanner instance configuration."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments a... | stack_v2_sparse_classes_36k_train_031359 | 7,591 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring"... | 2 | null | Implement the Python class `Create` described below.
Class description:
Create a Cloud Spanner instance configuration.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on th... | Implement the Python class `Create` described below.
Class description:
Create a Cloud Spanner instance configuration.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on th... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Create:
"""Create a Cloud Spanner instance configuration."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Create:
"""Create a Cloud Spanner instance configuration."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.""... | the_stack_v2_python_sparse | lib/surface/spanner/instance_configs/create.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
9ab6630bfa52fae1c237f226a85986fcc9195da5 | [
"super().__init__(name=name)\nself._listen_ip = listen_ip\nself._listen_port = listen_port\nself.__listen_server = socket.socket()\nself.__listen_server.bind((listen_ip, listen_port))\nself.__can_run = False",
"while self.__can_run:\n conn, add = self.__listen_server.accept()\n analyze_msg_thread = Thread(t... | <|body_start_0|>
super().__init__(name=name)
self._listen_ip = listen_ip
self._listen_port = listen_port
self.__listen_server = socket.socket()
self.__listen_server.bind((listen_ip, listen_port))
self.__can_run = False
<|end_body_0|>
<|body_start_1|>
while self._... | 后台监听线程. 当代理服务器配置后,会启动线程,监听来自客户端的消息请求. 在监听线程中并不会对客户端请求直接处理,而是转交给单独的处理线程处理. | ListenThread | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListenThread:
"""后台监听线程. 当代理服务器配置后,会启动线程,监听来自客户端的消息请求. 在监听线程中并不会对客户端请求直接处理,而是转交给单独的处理线程处理."""
def __init__(self, listen_ip='', listen_port=8088, name=None):
"""对象初始化函数 :param listen_ip: 指定要监听的IP :param listen_port: 指定监听的端口 :param name: 指定线程的名称"""
<|body_0|>
def __run(sel... | stack_v2_sparse_classes_36k_train_031360 | 16,601 | permissive | [
{
"docstring": "对象初始化函数 :param listen_ip: 指定要监听的IP :param listen_port: 指定监听的端口 :param name: 指定线程的名称",
"name": "__init__",
"signature": "def __init__(self, listen_ip='', listen_port=8088, name=None)"
},
{
"docstring": "监听来自客户端发起的连接,和接收消息并启动新的线程处理消息.",
"name": "__run",
"signature": "def __... | 4 | stack_v2_sparse_classes_30k_train_017595 | Implement the Python class `ListenThread` described below.
Class description:
后台监听线程. 当代理服务器配置后,会启动线程,监听来自客户端的消息请求. 在监听线程中并不会对客户端请求直接处理,而是转交给单独的处理线程处理.
Method signatures and docstrings:
- def __init__(self, listen_ip='', listen_port=8088, name=None): 对象初始化函数 :param listen_ip: 指定要监听的IP :param listen_port: 指定监听的端口 :par... | Implement the Python class `ListenThread` described below.
Class description:
后台监听线程. 当代理服务器配置后,会启动线程,监听来自客户端的消息请求. 在监听线程中并不会对客户端请求直接处理,而是转交给单独的处理线程处理.
Method signatures and docstrings:
- def __init__(self, listen_ip='', listen_port=8088, name=None): 对象初始化函数 :param listen_ip: 指定要监听的IP :param listen_port: 指定监听的端口 :par... | 7ce2ca5183b222fe6cee0ba64171ea835fc62342 | <|skeleton|>
class ListenThread:
"""后台监听线程. 当代理服务器配置后,会启动线程,监听来自客户端的消息请求. 在监听线程中并不会对客户端请求直接处理,而是转交给单独的处理线程处理."""
def __init__(self, listen_ip='', listen_port=8088, name=None):
"""对象初始化函数 :param listen_ip: 指定要监听的IP :param listen_port: 指定监听的端口 :param name: 指定线程的名称"""
<|body_0|>
def __run(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListenThread:
"""后台监听线程. 当代理服务器配置后,会启动线程,监听来自客户端的消息请求. 在监听线程中并不会对客户端请求直接处理,而是转交给单独的处理线程处理."""
def __init__(self, listen_ip='', listen_port=8088, name=None):
"""对象初始化函数 :param listen_ip: 指定要监听的IP :param listen_port: 指定监听的端口 :param name: 指定线程的名称"""
super().__init__(name=name)
self._... | the_stack_v2_python_sparse | server/ProxyServer.py | Grant555/utilities-python | train | 0 |
3ab8fc3acac27e6c003f922041b5d329e33e1ff9 | [
"self.filename = filename\nself.compressed = compressed\nself.delimiter = delimiter\nself.quotechar = quotechar\nself.has_row_ids = has_row_ids\nself.is_open = False\nself.fh = None\nself.line_count = 0\nself.reader = None",
"if self.is_open:\n self.fh.close()\nself.fh = None\nself.reader = None\nself.line_cou... | <|body_start_0|>
self.filename = filename
self.compressed = compressed
self.delimiter = delimiter
self.quotechar = quotechar
self.has_row_ids = has_row_ids
self.is_open = False
self.fh = None
self.line_count = 0
self.reader = None
<|end_body_0|>
<... | Dataset reader for delimited files (CSV or TSV). | DelimitedFileReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelimitedFileReader:
"""Dataset reader for delimited files (CSV or TSV)."""
def __init__(self, filename, compressed=False, delimiter=',', quotechar='"', has_row_ids=False):
"""Initialize information about the delimited file and the file format. Parameters ---------- filename: string ... | stack_v2_sparse_classes_36k_train_031361 | 12,341 | permissive | [
{
"docstring": "Initialize information about the delimited file and the file format. Parameters ---------- filename: string Path to the file on disk compressed: bool, optional Flag indicating if the file is compressed (gzip) delimiter: string, optional The column delimiter used by the file quotechar: string, op... | 4 | null | Implement the Python class `DelimitedFileReader` described below.
Class description:
Dataset reader for delimited files (CSV or TSV).
Method signatures and docstrings:
- def __init__(self, filename, compressed=False, delimiter=',', quotechar='"', has_row_ids=False): Initialize information about the delimited file and... | Implement the Python class `DelimitedFileReader` described below.
Class description:
Dataset reader for delimited files (CSV or TSV).
Method signatures and docstrings:
- def __init__(self, filename, compressed=False, delimiter=',', quotechar='"', has_row_ids=False): Initialize information about the delimited file and... | e99f43df3df80ad5647f57d805c339257336ac73 | <|skeleton|>
class DelimitedFileReader:
"""Dataset reader for delimited files (CSV or TSV)."""
def __init__(self, filename, compressed=False, delimiter=',', quotechar='"', has_row_ids=False):
"""Initialize information about the delimited file and the file format. Parameters ---------- filename: string ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DelimitedFileReader:
"""Dataset reader for delimited files (CSV or TSV)."""
def __init__(self, filename, compressed=False, delimiter=',', quotechar='"', has_row_ids=False):
"""Initialize information about the delimited file and the file format. Parameters ---------- filename: string Path to the f... | the_stack_v2_python_sparse | vizier/datastore/reader.py | VizierDB/web-api-async | train | 2 |
9c3f389cccf24234ec3579b88b9e8820a005b766 | [
"if not matrix or not matrix[0]:\n return False\nm, n = (len(matrix), len(matrix[0]))\nl, r = (0, m * n - 1)\nwhile l < r:\n mid = (l + r - 1) // 2\n if matrix[mid // n][mid % n] < target:\n l = mid + 1\n else:\n r = mid\nreturn matrix[r // n][r % n] == target",
"if not matrix or not mat... | <|body_start_0|>
if not matrix or not matrix[0]:
return False
m, n = (len(matrix), len(matrix[0]))
l, r = (0, m * n - 1)
while l < r:
mid = (l + r - 1) // 2
if matrix[mid // n][mid % n] < target:
l = mid + 1
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix_orig(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_031362 | 1,407 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix_orig",
"signature": "def se... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix_orig(self, matrix, target): :type matrix: List[List[int]] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix_orig(self, matrix, target): :type matrix: List[List[int]] ... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix_orig(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if not matrix or not matrix[0]:
return False
m, n = (len(matrix), len(matrix[0]))
l, r = (0, m * n - 1)
while l < r:
mid = (l + r... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetcodePythonProject/leetcode_0051_0100/LeetCode074_SearchA2DMatrix.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
8b46f03c83f18b6af2245a1c216f57b4a8ce4a9b | [
"de = {'А': '•- ', 'Б': '-••• ', 'В': '•-- ', 'Г': '--• ', 'Д': '-•• ', 'Е': '• ', 'Ё': '• ', 'Ж': '•••- ', 'З': '--•• ', 'И': '•• ', 'Й': '•--- ', 'К': '-•- ', 'Л': '•-•• ', 'М': '-- ', 'Н': '-• ', 'О': '--- ', 'П': '•--• ', 'Р': '•-• ', 'С': '••• ', 'Т': '- ', 'У': '••- ', 'Ф': '••-• ', 'Х': '•••• ', 'Ц': '-•-• '... | <|body_start_0|>
de = {'А': '•- ', 'Б': '-••• ', 'В': '•-- ', 'Г': '--• ', 'Д': '-•• ', 'Е': '• ', 'Ё': '• ', 'Ж': '•••- ', 'З': '--•• ', 'И': '•• ', 'Й': '•--- ', 'К': '-•- ', 'Л': '•-•• ', 'М': '-- ', 'Н': '-• ', 'О': '--- ', 'П': '•--• ', 'Р': '•-• ', 'С': '••• ', 'Т': '- ', 'У': '••- ', 'Ф': '••-• ', 'Х': '... | Конвертация текста в шифр Морзе и наоборот. Символы использовать не советую, могут возникать ошибки!! | MorzeMod | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MorzeMod:
"""Конвертация текста в шифр Морзе и наоборот. Символы использовать не советую, могут возникать ошибки!!"""
async def tomrzcmd(self, message):
""".tomrz [реплай или текст]"""
<|body_0|>
async def toabccmd(self, message):
""".toabc [реплай или текст]"""
... | stack_v2_sparse_classes_36k_train_031363 | 3,830 | no_license | [
{
"docstring": ".tomrz [реплай или текст]",
"name": "tomrzcmd",
"signature": "async def tomrzcmd(self, message)"
},
{
"docstring": ".toabc [реплай или текст]",
"name": "toabccmd",
"signature": "async def toabccmd(self, message)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015093 | Implement the Python class `MorzeMod` described below.
Class description:
Конвертация текста в шифр Морзе и наоборот. Символы использовать не советую, могут возникать ошибки!!
Method signatures and docstrings:
- async def tomrzcmd(self, message): .tomrz [реплай или текст]
- async def toabccmd(self, message): .toabc [... | Implement the Python class `MorzeMod` described below.
Class description:
Конвертация текста в шифр Морзе и наоборот. Символы использовать не советую, могут возникать ошибки!!
Method signatures and docstrings:
- async def tomrzcmd(self, message): .tomrz [реплай или текст]
- async def toabccmd(self, message): .toabc [... | f70ed62e39470335aba81ce0e8cac4e3c71e1500 | <|skeleton|>
class MorzeMod:
"""Конвертация текста в шифр Морзе и наоборот. Символы использовать не советую, могут возникать ошибки!!"""
async def tomrzcmd(self, message):
""".tomrz [реплай или текст]"""
<|body_0|>
async def toabccmd(self, message):
""".toabc [реплай или текст]"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MorzeMod:
"""Конвертация текста в шифр Морзе и наоборот. Символы использовать не советую, могут возникать ошибки!!"""
async def tomrzcmd(self, message):
""".tomrz [реплай или текст]"""
de = {'А': '•- ', 'Б': '-••• ', 'В': '•-- ', 'Г': '--• ', 'Д': '-•• ', 'Е': '• ', 'Ё': '• ', 'Ж': '•••- ... | the_stack_v2_python_sparse | morze.py | SergaTV/FTG-Modules | train | 0 |
63a23d8ff4152990f79278eb7ba063800e1287cf | [
"filePath = File.getRealPath(callingFile) + '/data.txt'\nwith open(filePath, 'r') as file:\n data = file.readlines()\nreturn data",
"filePath = File.getRealPath(callingFile) + '/data.txt'\nwith open(filePath, 'r') as file:\n data = file.read()\nreturn data",
"path = os.path.realpath(file)\npathSections = ... | <|body_start_0|>
filePath = File.getRealPath(callingFile) + '/data.txt'
with open(filePath, 'r') as file:
data = file.readlines()
return data
<|end_body_0|>
<|body_start_1|>
filePath = File.getRealPath(callingFile) + '/data.txt'
with open(filePath, 'r') as file:
... | File | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class File:
def loadLines(callingFile):
"""Loads all data from file as a list of lines"""
<|body_0|>
def loadData(callingFile):
"""Loads all data from file as a single data chunk"""
<|body_1|>
def getRealPath(file):
"""Gets raw path of the current scri... | stack_v2_sparse_classes_36k_train_031364 | 26,157 | no_license | [
{
"docstring": "Loads all data from file as a list of lines",
"name": "loadLines",
"signature": "def loadLines(callingFile)"
},
{
"docstring": "Loads all data from file as a single data chunk",
"name": "loadData",
"signature": "def loadData(callingFile)"
},
{
"docstring": "Gets r... | 3 | null | Implement the Python class `File` described below.
Class description:
Implement the File class.
Method signatures and docstrings:
- def loadLines(callingFile): Loads all data from file as a list of lines
- def loadData(callingFile): Loads all data from file as a single data chunk
- def getRealPath(file): Gets raw pat... | Implement the Python class `File` described below.
Class description:
Implement the File class.
Method signatures and docstrings:
- def loadLines(callingFile): Loads all data from file as a list of lines
- def loadData(callingFile): Loads all data from file as a single data chunk
- def getRealPath(file): Gets raw pat... | 91610f384ccdb6065104d8ce5b3ac0f6d785d20a | <|skeleton|>
class File:
def loadLines(callingFile):
"""Loads all data from file as a list of lines"""
<|body_0|>
def loadData(callingFile):
"""Loads all data from file as a single data chunk"""
<|body_1|>
def getRealPath(file):
"""Gets raw path of the current scri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class File:
def loadLines(callingFile):
"""Loads all data from file as a list of lines"""
filePath = File.getRealPath(callingFile) + '/data.txt'
with open(filePath, 'r') as file:
data = file.readlines()
return data
def loadData(callingFile):
"""Loads all data... | the_stack_v2_python_sparse | SharedCode/Function.py | AidanFray/Cryptopals_Crypto_Challenges | train | 3 | |
19ad56f98e6e863da7e4252855204064da7d894d | [
"if self.name.startswith('WORD_'):\n return WordType.WORD\nreturn WordType.POS_TAG",
"if self.name.endswith('_TFIDF'):\n return VectorizerType.TFIDF\nreturn VectorizerType.COUNT"
] | <|body_start_0|>
if self.name.startswith('WORD_'):
return WordType.WORD
return WordType.POS_TAG
<|end_body_0|>
<|body_start_1|>
if self.name.endswith('_TFIDF'):
return VectorizerType.TFIDF
return VectorizerType.COUNT
<|end_body_1|>
| Combines both the Vectorizer and Word types into a single enumeration. | WordVectorizerType | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordVectorizerType:
"""Combines both the Vectorizer and Word types into a single enumeration."""
def word_type(self):
"""Gets the WordType associated with this class. :return: a WordType"""
<|body_0|>
def vectorizer_type(self):
"""Gets the VectorizerType associat... | stack_v2_sparse_classes_36k_train_031365 | 32,164 | no_license | [
{
"docstring": "Gets the WordType associated with this class. :return: a WordType",
"name": "word_type",
"signature": "def word_type(self)"
},
{
"docstring": "Gets the VectorizerType associated with this class. :return: a VectorizerType",
"name": "vectorizer_type",
"signature": "def vect... | 2 | stack_v2_sparse_classes_30k_train_005091 | Implement the Python class `WordVectorizerType` described below.
Class description:
Combines both the Vectorizer and Word types into a single enumeration.
Method signatures and docstrings:
- def word_type(self): Gets the WordType associated with this class. :return: a WordType
- def vectorizer_type(self): Gets the Ve... | Implement the Python class `WordVectorizerType` described below.
Class description:
Combines both the Vectorizer and Word types into a single enumeration.
Method signatures and docstrings:
- def word_type(self): Gets the WordType associated with this class. :return: a WordType
- def vectorizer_type(self): Gets the Ve... | 1e233487891d6ad7a66157ffcea48b6ffe5f422d | <|skeleton|>
class WordVectorizerType:
"""Combines both the Vectorizer and Word types into a single enumeration."""
def word_type(self):
"""Gets the WordType associated with this class. :return: a WordType"""
<|body_0|>
def vectorizer_type(self):
"""Gets the VectorizerType associat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordVectorizerType:
"""Combines both the Vectorizer and Word types into a single enumeration."""
def word_type(self):
"""Gets the WordType associated with this class. :return: a WordType"""
if self.name.startswith('WORD_'):
return WordType.WORD
return WordType.POS_TAG
... | the_stack_v2_python_sparse | NBandSVMTests.py | Geekiac/Masters-Dissertation-Code | train | 0 |
61ea60970f9ac454e652c8b6092c027e6e76996e | [
"super(DecoderBlock, self).__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.dropout1 = tf.keras.layers.Dropout(drop_rate)\nself.dropout2 = tf.keras.layer... | <|body_start_0|>
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.dropout1 = tf.keras.la... | Transformer Decoder Block | DecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""Transformer Decoder Block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[ Class constructor] Args: dm ([type]): [the dimensionality of the model] h ([type]): [the number of heads] hidden ([type]): [# of hidden units in the fully connected layer] drop_rate (... | stack_v2_sparse_classes_36k_train_031366 | 3,778 | no_license | [
{
"docstring": "[ Class constructor] Args: dm ([type]): [the dimensionality of the model] h ([type]): [the number of heads] hidden ([type]): [# of hidden units in the fully connected layer] drop_rate (float, optional): [dropout rate]. Defaults to 0.1. Public instance attributes: - mha1: the first MultiHeadAtten... | 2 | stack_v2_sparse_classes_30k_train_015777 | Implement the Python class `DecoderBlock` described below.
Class description:
Transformer Decoder Block
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [ Class constructor] Args: dm ([type]): [the dimensionality of the model] h ([type]): [the number of heads] hidden ([type]): [# ... | Implement the Python class `DecoderBlock` described below.
Class description:
Transformer Decoder Block
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [ Class constructor] Args: dm ([type]): [the dimensionality of the model] h ([type]): [the number of heads] hidden ([type]): [# ... | eb47cd4d12e2f0627bb5e5af28cc0802ff13d0d9 | <|skeleton|>
class DecoderBlock:
"""Transformer Decoder Block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[ Class constructor] Args: dm ([type]): [the dimensionality of the model] h ([type]): [the number of heads] hidden ([type]): [# of hidden units in the fully connected layer] drop_rate (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderBlock:
"""Transformer Decoder Block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[ Class constructor] Args: dm ([type]): [the dimensionality of the model] h ([type]): [the number of heads] hidden ([type]): [# of hidden units in the fully connected layer] drop_rate (float, option... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/8-transformer_decoder_block.py | rodrigocruz13/holbertonschool-machine_learning | train | 4 |
102943406712c71ca36bad8495ec6cfc2903fc2c | [
"if np.any(z < 0.0):\n print >> sys.stderr('z has negative values and thus is not a density!')\n return\nif not 0.0 < m < 1.0:\n print >> sys.stderr('m has to be in (0; 1)!')\n return\nmaxVal = np.max(z)\nz *= m / maxVal\nprint('Preparing interpolating function')\nself._interp = RectBivariateSpline(x, y... | <|body_start_0|>
if np.any(z < 0.0):
print >> sys.stderr('z has negative values and thus is not a density!')
return
if not 0.0 < m < 1.0:
print >> sys.stderr('m has to be in (0; 1)!')
return
maxVal = np.max(z)
z *= m / maxVal
print(... | Sampler object. To be instantiated with an (x,y) grid and a PDF function z = z(x,y). | sampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sampler:
"""Sampler object. To be instantiated with an (x,y) grid and a PDF function z = z(x,y)."""
def __init__(self, x, y, z, m=0.95, cond=None):
"""Create a sampler object from data. Parameters ---------- x,y : arrays 1d arrays for x and y data. z : array PDF of shape [len(x), len... | stack_v2_sparse_classes_36k_train_031367 | 5,426 | permissive | [
{
"docstring": "Create a sampler object from data. Parameters ---------- x,y : arrays 1d arrays for x and y data. z : array PDF of shape [len(x), len(y)]. Does not need to be normalized correctly. m : float, optional Number in [0; 1). Used as new maximum value in renormalization of the PDF. Random samples (x,y)... | 2 | stack_v2_sparse_classes_30k_train_004448 | Implement the Python class `sampler` described below.
Class description:
Sampler object. To be instantiated with an (x,y) grid and a PDF function z = z(x,y).
Method signatures and docstrings:
- def __init__(self, x, y, z, m=0.95, cond=None): Create a sampler object from data. Parameters ---------- x,y : arrays 1d arr... | Implement the Python class `sampler` described below.
Class description:
Sampler object. To be instantiated with an (x,y) grid and a PDF function z = z(x,y).
Method signatures and docstrings:
- def __init__(self, x, y, z, m=0.95, cond=None): Create a sampler object from data. Parameters ---------- x,y : arrays 1d arr... | bd784798b846f76e00a3bbb0fb1acf6a1317be12 | <|skeleton|>
class sampler:
"""Sampler object. To be instantiated with an (x,y) grid and a PDF function z = z(x,y)."""
def __init__(self, x, y, z, m=0.95, cond=None):
"""Create a sampler object from data. Parameters ---------- x,y : arrays 1d arrays for x and y data. z : array PDF of shape [len(x), len... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class sampler:
"""Sampler object. To be instantiated with an (x,y) grid and a PDF function z = z(x,y)."""
def __init__(self, x, y, z, m=0.95, cond=None):
"""Create a sampler object from data. Parameters ---------- x,y : arrays 1d arrays for x and y data. z : array PDF of shape [len(x), len(y)]. Does no... | the_stack_v2_python_sparse | learningml/GoF/data/accept_reject/sampler_example.py | weissercn/learningml | train | 1 |
02a1e8b6ec1c0c542df60f019bff255dba1309fa | [
"alipay = Alipay(pid=settings.ALIPAY_PID, key=settings.ALIPAY_KEY, seller_email=settings.ALIPAY_EMAIL)\nif not alipay.verify_notify(**request.GET.dict()):\n return HttpResponseForbidden()\ncode, payment_type = request.GET['out_trade_no'].split('_')\norder = Order.objects.get(code=code)\npayment = Payment()\npaym... | <|body_start_0|>
alipay = Alipay(pid=settings.ALIPAY_PID, key=settings.ALIPAY_KEY, seller_email=settings.ALIPAY_EMAIL)
if not alipay.verify_notify(**request.GET.dict()):
return HttpResponseForbidden()
code, payment_type = request.GET['out_trade_no'].split('_')
order = Order.o... | Payment success. return_url for Alipay. | SuccessView | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuccessView:
"""Payment success. return_url for Alipay."""
def get2(self, request, *args, **kwargs):
"""Verify notify"""
<|body_0|>
def get_context_data2(self, **kwargs):
"""Add extra data to the context"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_031368 | 8,035 | permissive | [
{
"docstring": "Verify notify",
"name": "get2",
"signature": "def get2(self, request, *args, **kwargs)"
},
{
"docstring": "Add extra data to the context",
"name": "get_context_data2",
"signature": "def get_context_data2(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021156 | Implement the Python class `SuccessView` described below.
Class description:
Payment success. return_url for Alipay.
Method signatures and docstrings:
- def get2(self, request, *args, **kwargs): Verify notify
- def get_context_data2(self, **kwargs): Add extra data to the context | Implement the Python class `SuccessView` described below.
Class description:
Payment success. return_url for Alipay.
Method signatures and docstrings:
- def get2(self, request, *args, **kwargs): Verify notify
- def get_context_data2(self, **kwargs): Add extra data to the context
<|skeleton|>
class SuccessView:
"... | 0ea016745d92054bd4df8d934c1b67fd61b6f845 | <|skeleton|>
class SuccessView:
"""Payment success. return_url for Alipay."""
def get2(self, request, *args, **kwargs):
"""Verify notify"""
<|body_0|>
def get_context_data2(self, **kwargs):
"""Add extra data to the context"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuccessView:
"""Payment success. return_url for Alipay."""
def get2(self, request, *args, **kwargs):
"""Verify notify"""
alipay = Alipay(pid=settings.ALIPAY_PID, key=settings.ALIPAY_KEY, seller_email=settings.ALIPAY_EMAIL)
if not alipay.verify_notify(**request.GET.dict()):
... | the_stack_v2_python_sparse | payments/views.py | ygrass/handsome | train | 0 |
54275db48d77510a160987b25bc6e9160ce5d95b | [
"super(TestAdmin, cls).setUpClass()\ncls.pagelogin = PageLogin(cls.browserclass.get_driver())\ncls.pageindex = PageIndex(cls.browserclass.get_driver())",
"self.log.info('--------- Start Login ---------')\nself.browserclass.get_driver().get(self.loginurl)\ncaptvalue = self.pagelogin.getcaptcha(self.loginurl, self.... | <|body_start_0|>
super(TestAdmin, cls).setUpClass()
cls.pagelogin = PageLogin(cls.browserclass.get_driver())
cls.pageindex = PageIndex(cls.browserclass.get_driver())
<|end_body_0|>
<|body_start_1|>
self.log.info('--------- Start Login ---------')
self.browserclass.get_driver().g... | TestAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAdmin:
def setUpClass(cls):
"""测试类中所有测试方法执行前执行的方法"""
<|body_0|>
def test_a_weblogin(self):
"""登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:"""
<|body_1|>
def test_b_pagecheck(self, menu1, menu2, menu3, check_a):
"""数据驱动,左侧菜单点击及页面显示check 三个参数依次是 一... | stack_v2_sparse_classes_36k_train_031369 | 10,521 | no_license | [
{
"docstring": "测试类中所有测试方法执行前执行的方法",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:",
"name": "test_a_weblogin",
"signature": "def test_a_weblogin(self)"
},
{
"docstring": "数据驱动,左侧菜单点击及页面显示check 三个参数依次是 一级菜单 二... | 3 | stack_v2_sparse_classes_30k_train_001165 | Implement the Python class `TestAdmin` described below.
Class description:
Implement the TestAdmin class.
Method signatures and docstrings:
- def setUpClass(cls): 测试类中所有测试方法执行前执行的方法
- def test_a_weblogin(self): 登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:
- def test_b_pagecheck(self, menu1, menu2, menu3, check_a): 数据驱动,... | Implement the Python class `TestAdmin` described below.
Class description:
Implement the TestAdmin class.
Method signatures and docstrings:
- def setUpClass(cls): 测试类中所有测试方法执行前执行的方法
- def test_a_weblogin(self): 登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:
- def test_b_pagecheck(self, menu1, menu2, menu3, check_a): 数据驱动,... | 08b98e08b76ed2a4984efb7f543ed63eabe30757 | <|skeleton|>
class TestAdmin:
def setUpClass(cls):
"""测试类中所有测试方法执行前执行的方法"""
<|body_0|>
def test_a_weblogin(self):
"""登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:"""
<|body_1|>
def test_b_pagecheck(self, menu1, menu2, menu3, check_a):
"""数据驱动,左侧菜单点击及页面显示check 三个参数依次是 一... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAdmin:
def setUpClass(cls):
"""测试类中所有测试方法执行前执行的方法"""
super(TestAdmin, cls).setUpClass()
cls.pagelogin = PageLogin(cls.browserclass.get_driver())
cls.pageindex = PageIndex(cls.browserclass.get_driver())
def test_a_weblogin(self):
"""登录测试,并为后面的菜单页面check测试,提供登录后的系... | the_stack_v2_python_sparse | Sys_Carloan/TestClass/TestAdmin.py | duozi/webUITestLight | train | 0 | |
5bff5aaf268c7e1892d0b27efcda77f5c4d348cf | [
"pStillNeed = collections.Counter()\ncounter = begin = end = length = 0\nwhile end < len(s):\n c = s[end]\n pStillNeed[c] += 1\n if pStillNeed[c] > 1:\n counter += 1\n end += 1\n while counter > 0:\n tempc = s[begin]\n pStillNeed[tempc] -= 1\n if pStillNeed[tempc] > 0:\n ... | <|body_start_0|>
pStillNeed = collections.Counter()
counter = begin = end = length = 0
while end < len(s):
c = s[end]
pStillNeed[c] += 1
if pStillNeed[c] > 1:
counter += 1
end += 1
while counter > 0:
temp... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstringDP(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pStillNeed = collections.Counter()
... | stack_v2_sparse_classes_36k_train_031370 | 2,267 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstringDP",
"signature": "def lengthOfLongestSubstringDP(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstringDP(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstringDP(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def lengthO... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstringDP(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
pStillNeed = collections.Counter()
counter = begin = end = length = 0
while end < len(s):
c = s[end]
pStillNeed[c] += 1
if pStillNeed[c] > 1:
coun... | the_stack_v2_python_sparse | substring/longest_substring_wo_repeating_char.py | gerrycfchang/leetcode-python | train | 2 | |
22dcf7c8eefd9ecd86e15c30d1b9418c43744b6c | [
"random_date = datetime.datetime(2019, 12, 4, 0, 0)\nresult = random_date + timedelta(days=30)\nself.assertEqual(result, datetime.datetime(2020, 1, 3, 0, 0))",
"random_date = datetime.datetime(2020, 1, 2, 0, 0)\nresult = random_date - timedelta(days=10)\nself.assertEqual(result, datetime.datetime(2019, 12, 23, 0,... | <|body_start_0|>
random_date = datetime.datetime(2019, 12, 4, 0, 0)
result = random_date + timedelta(days=30)
self.assertEqual(result, datetime.datetime(2020, 1, 3, 0, 0))
<|end_body_0|>
<|body_start_1|>
random_date = datetime.datetime(2020, 1, 2, 0, 0)
result = random_date - ti... | Test the add function from Python datetime library | TestAdd | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAdd:
"""Test the add function from Python datetime library"""
def test_date_add_timedelta(self):
"""Test date add timedelta"""
<|body_0|>
def test_date_substract_timedelta(self):
"""Test date substract timedelta"""
<|body_1|>
def test_date_substr... | stack_v2_sparse_classes_36k_train_031371 | 1,832 | no_license | [
{
"docstring": "Test date add timedelta",
"name": "test_date_add_timedelta",
"signature": "def test_date_add_timedelta(self)"
},
{
"docstring": "Test date substract timedelta",
"name": "test_date_substract_timedelta",
"signature": "def test_date_substract_timedelta(self)"
},
{
"d... | 5 | stack_v2_sparse_classes_30k_train_015548 | Implement the Python class `TestAdd` described below.
Class description:
Test the add function from Python datetime library
Method signatures and docstrings:
- def test_date_add_timedelta(self): Test date add timedelta
- def test_date_substract_timedelta(self): Test date substract timedelta
- def test_date_substract_... | Implement the Python class `TestAdd` described below.
Class description:
Test the add function from Python datetime library
Method signatures and docstrings:
- def test_date_add_timedelta(self): Test date add timedelta
- def test_date_substract_timedelta(self): Test date substract timedelta
- def test_date_substract_... | a816101f86c3e02134a37ea7617157de492b8c7a | <|skeleton|>
class TestAdd:
"""Test the add function from Python datetime library"""
def test_date_add_timedelta(self):
"""Test date add timedelta"""
<|body_0|>
def test_date_substract_timedelta(self):
"""Test date substract timedelta"""
<|body_1|>
def test_date_substr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAdd:
"""Test the add function from Python datetime library"""
def test_date_add_timedelta(self):
"""Test date add timedelta"""
random_date = datetime.datetime(2019, 12, 4, 0, 0)
result = random_date + timedelta(days=30)
self.assertEqual(result, datetime.datetime(2020, ... | the_stack_v2_python_sparse | homework/homework7/peer_review_hw7/tt.py | aaronweise1/ccsf_advanced_python_231 | train | 0 |
ce3a4430eea64981771268019c3ccb62efaccd17 | [
"self.rects = rects\nself.weight = [0]\nself.s = 0\nfor rect in rects:\n area = (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)\n self.s += area\n self.weight.append(self.s)",
"randomFromArea = randint(1, self.s)\nl = 0\nr = len(self.weight) - 1\nwhile l < r:\n mid = l + r >> 1\n if self.weight[m... | <|body_start_0|>
self.rects = rects
self.weight = [0]
self.s = 0
for rect in rects:
area = (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)
self.s += area
self.weight.append(self.s)
<|end_body_0|>
<|body_start_1|>
randomFromArea = randint(1, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rects = rects
self.weight = [0]
self.s = 0
for rect ... | stack_v2_sparse_classes_36k_train_031372 | 2,163 | no_license | [
{
"docstring": ":type rects: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: ... | 819fbc523f3b33742333b6b39b72337a24a26f7a | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.rects = rects
self.weight = [0]
self.s = 0
for rect in rects:
area = (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)
self.s += area
self.weight.append(self... | the_stack_v2_python_sparse | leetcode/Random/497m. 非重叠矩形中的随机点(合并随机,二分查找).py | Andrewlearning/Leetcoding | train | 1 | |
532d9299a3f8185a48be23a7104d3ab6ec0ee574 | [
"res = [0]\nfor i in range(1, num + 1):\n res.append((i & 1) + res[i >> 1])\nreturn res",
"s = [0]\nwhile len(s) <= num:\n s.extend([x + 1 for x in s])\nreturn s[:num + 1]"
] | <|body_start_0|>
res = [0]
for i in range(1, num + 1):
res.append((i & 1) + res[i >> 1])
return res
<|end_body_0|>
<|body_start_1|>
s = [0]
while len(s) <= num:
s.extend([x + 1 for x in s])
return s[:num + 1]
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countBits(self, num):
""":type num: int :rtype: List[int]"""
<|body_0|>
def countBits2(self, num):
""":type num: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = [0]
for i in range(1, num + 1):
... | stack_v2_sparse_classes_36k_train_031373 | 1,377 | no_license | [
{
"docstring": ":type num: int :rtype: List[int]",
"name": "countBits",
"signature": "def countBits(self, num)"
},
{
"docstring": ":type num: int :rtype: List[int]",
"name": "countBits2",
"signature": "def countBits2(self, num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015699 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countBits(self, num): :type num: int :rtype: List[int]
- def countBits2(self, num): :type num: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countBits(self, num): :type num: int :rtype: List[int]
- def countBits2(self, num): :type num: int :rtype: List[int]
<|skeleton|>
class Solution:
def countBits(self, nu... | 05e8f5a4e39d448eb333c813093fc7c1df4fc05e | <|skeleton|>
class Solution:
def countBits(self, num):
""":type num: int :rtype: List[int]"""
<|body_0|>
def countBits2(self, num):
""":type num: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countBits(self, num):
""":type num: int :rtype: List[int]"""
res = [0]
for i in range(1, num + 1):
res.append((i & 1) + res[i >> 1])
return res
def countBits2(self, num):
""":type num: int :rtype: List[int]"""
s = [0]
while... | the_stack_v2_python_sparse | leetcode_python/Math/counting-bits.py | DataEngDev/CS_basics | train | 0 | |
36094d92bf3dd0f31ab2867910a86c1b19cb6207 | [
"self.arc_map = arc_map\nsorted_sats = sorted(arc_map)\nself.flat_iters = [peekable(arc_map[x].flat) for x in sorted_sats]",
"front_entries = [x.peek(None) for x in self.flat_iters]\nif all([x is None for x in front_entries]):\n raise StopIteration\nI, _ = min(filter(lambda x: x[1] is not None, enumerate(front... | <|body_start_0|>
self.arc_map = arc_map
sorted_sats = sorted(arc_map)
self.flat_iters = [peekable(arc_map[x].flat) for x in sorted_sats]
<|end_body_0|>
<|body_start_1|>
front_entries = [x.peek(None) for x in self.flat_iters]
if all([x is None for x in front_entries]):
... | ArcMapFlatIterator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArcMapFlatIterator:
def __init__(self, arc_map):
"""???"""
<|body_0|>
def next(self):
"""???"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.arc_map = arc_map
sorted_sats = sorted(arc_map)
self.flat_iters = [peekable(arc_map[x].... | stack_v2_sparse_classes_36k_train_031374 | 16,515 | permissive | [
{
"docstring": "???",
"name": "__init__",
"signature": "def __init__(self, arc_map)"
},
{
"docstring": "???",
"name": "next",
"signature": "def next(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000346 | Implement the Python class `ArcMapFlatIterator` described below.
Class description:
Implement the ArcMapFlatIterator class.
Method signatures and docstrings:
- def __init__(self, arc_map): ???
- def next(self): ??? | Implement the Python class `ArcMapFlatIterator` described below.
Class description:
Implement the ArcMapFlatIterator class.
Method signatures and docstrings:
- def __init__(self, arc_map): ???
- def next(self): ???
<|skeleton|>
class ArcMapFlatIterator:
def __init__(self, arc_map):
"""???"""
<|b... | e364be68cb0cadbeea10ca569963b8f99aa7b05b | <|skeleton|>
class ArcMapFlatIterator:
def __init__(self, arc_map):
"""???"""
<|body_0|>
def next(self):
"""???"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArcMapFlatIterator:
def __init__(self, arc_map):
"""???"""
self.arc_map = arc_map
sorted_sats = sorted(arc_map)
self.flat_iters = [peekable(arc_map[x].flat) for x in sorted_sats]
def next(self):
"""???"""
front_entries = [x.peek(None) for x in self.flat_ite... | the_stack_v2_python_sparse | pyrsss/gnss/level.py | butala/pyrsss | train | 7 | |
b9e6c27878132fefac2a0eb865e4b85815d4b64d | [
"self.__coupons = {}\nself.__item_code = ''\nself.__item_data = []\nself.__item_value = 0.0\nself.__item_name = ''",
"input_file = open('list_coupon.txt', 'r')\nfor line in input_file:\n line = line.split(',')\n self.__item_code = line[0]\n self.__item_value = float(line[1])\n self.__item_name = line[... | <|body_start_0|>
self.__coupons = {}
self.__item_code = ''
self.__item_data = []
self.__item_value = 0.0
self.__item_name = ''
<|end_body_0|>
<|body_start_1|>
input_file = open('list_coupon.txt', 'r')
for line in input_file:
line = line.split(',')
... | Class reads coupon list file, displays full list and specific item | CouponList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CouponList:
"""Class reads coupon list file, displays full list and specific item"""
def __init__(self):
"""constructor"""
<|body_0|>
def GenerateCouponList(self):
"""Read data in for coupons and returns information as dictionary"""
<|body_1|>
def Sh... | stack_v2_sparse_classes_36k_train_031375 | 2,585 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Read data in for coupons and returns information as dictionary",
"name": "GenerateCouponList",
"signature": "def GenerateCouponList(self)"
},
{
"docstring": "Display full coupon... | 4 | null | Implement the Python class `CouponList` described below.
Class description:
Class reads coupon list file, displays full list and specific item
Method signatures and docstrings:
- def __init__(self): constructor
- def GenerateCouponList(self): Read data in for coupons and returns information as dictionary
- def ShowCo... | Implement the Python class `CouponList` described below.
Class description:
Class reads coupon list file, displays full list and specific item
Method signatures and docstrings:
- def __init__(self): constructor
- def GenerateCouponList(self): Read data in for coupons and returns information as dictionary
- def ShowCo... | 37d8f5ef954bf8717a7eb7fd58bfa5607e339265 | <|skeleton|>
class CouponList:
"""Class reads coupon list file, displays full list and specific item"""
def __init__(self):
"""constructor"""
<|body_0|>
def GenerateCouponList(self):
"""Read data in for coupons and returns information as dictionary"""
<|body_1|>
def Sh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CouponList:
"""Class reads coupon list file, displays full list and specific item"""
def __init__(self):
"""constructor"""
self.__coupons = {}
self.__item_code = ''
self.__item_data = []
self.__item_value = 0.0
self.__item_name = ''
def GenerateCouponL... | the_stack_v2_python_sparse | CSC121FinalProject_WakeMartUpgrade/show_list_coupons.py | mischelay2001/WTCSC121 | train | 1 |
d562a8066491cfe320c49abdc174169519227eb4 | [
"if where is not None:\n if type(where) is not dict:\n raise BadConfigError(['where'], 'should be a dict')\n try:\n self._condition = Condition(**where)\n except BadConfigError as e:\n raise BadConfigError(['where'] + e.path, e.msg)\n except TypeError as e:\n raise BadConfigE... | <|body_start_0|>
if where is not None:
if type(where) is not dict:
raise BadConfigError(['where'], 'should be a dict')
try:
self._condition = Condition(**where)
except BadConfigError as e:
raise BadConfigError(['where'] + e.path... | Filters data based on given condition grouped by given `group_by` | Filter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Filter:
"""Filters data based on given condition grouped by given `group_by`"""
def __init__(self, where: dict=None, group_by: str or List[str] or None=None) -> None:
"""Creates a new instance of Filter Args: where (dict): keyword arguments that will be passed to Condition(). This is... | stack_v2_sparse_classes_36k_train_031376 | 2,069 | permissive | [
{
"docstring": "Creates a new instance of Filter Args: where (dict): keyword arguments that will be passed to Condition(). This is the condition to filter with. If not set then the date will be unfiltered. group_by (str or list[str]): list of columns to group data with. If not given then data will be treated as... | 2 | stack_v2_sparse_classes_30k_train_011073 | Implement the Python class `Filter` described below.
Class description:
Filters data based on given condition grouped by given `group_by`
Method signatures and docstrings:
- def __init__(self, where: dict=None, group_by: str or List[str] or None=None) -> None: Creates a new instance of Filter Args: where (dict): keyw... | Implement the Python class `Filter` described below.
Class description:
Filters data based on given condition grouped by given `group_by`
Method signatures and docstrings:
- def __init__(self, where: dict=None, group_by: str or List[str] or None=None) -> None: Creates a new instance of Filter Args: where (dict): keyw... | fea40936261dcbcfd144a15a498abf0b556c64f1 | <|skeleton|>
class Filter:
"""Filters data based on given condition grouped by given `group_by`"""
def __init__(self, where: dict=None, group_by: str or List[str] or None=None) -> None:
"""Creates a new instance of Filter Args: where (dict): keyword arguments that will be passed to Condition(). This is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Filter:
"""Filters data based on given condition grouped by given `group_by`"""
def __init__(self, where: dict=None, group_by: str or List[str] or None=None) -> None:
"""Creates a new instance of Filter Args: where (dict): keyword arguments that will be passed to Condition(). This is the conditio... | the_stack_v2_python_sparse | datavalid/filter.py | pckhoi/datavalid | train | 5 |
a73fb36f7945463622b46b1a6d8a9458d4831625 | [
"def convert(p):\n return str(p.val) + '{' + convert(p.left) + '}{' + convert(p.right) + '}' if p else '$'\nreturn convert(root)",
"if data == '$':\n return None\ni = 0\nwhile i < len(data) and data[i] != '{':\n i += 1\nT = TreeNode(int(data[:i]))\nleft_start = i + 1\nleft_no, i = (1, i + 1)\nwhile i < l... | <|body_start_0|>
def convert(p):
return str(p.val) + '{' + convert(p.left) + '}{' + convert(p.right) + '}' if p else '$'
return convert(root)
<|end_body_0|>
<|body_start_1|>
if data == '$':
return None
i = 0
while i < len(data) and data[i] != '{':
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_031377 | 3,466 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 78d36486ad4ec2bfb88fd35a5fd7fd4f0003ee97 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def convert(p):
return str(p.val) + '{' + convert(p.left) + '}{' + convert(p.right) + '}' if p else '$'
return convert(root)
def deserialize(self, data):
... | the_stack_v2_python_sparse | 297_serialize&deserializeBT.py | YeahHuang/Leetcode | train | 1 | |
1be0bfa93c396c9765d0d6ec1fae7c58cdfc8007 | [
"try:\n key = ''.join([nnid, '_', ver, '_', node])\n return_data = ft_conf(key).set_conf_data(request.data)\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n key = ''.join([n... | <|body_start_0|>
try:
key = ''.join([nnid, '_', ver, '_', node])
return_data = ft_conf(key).set_conf_data(request.data)
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '404', 'result': str(e)}
return Res... | WorkFlowNetConfFastText | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkFlowNetConfFastText:
def post(self, request, nnid, ver, node):
"""- desc : insert configuration data"""
<|body_0|>
def get(self, request, nnid, ver, node):
"""- desc : get configuration data"""
<|body_1|>
def put(self, request, nnid, ver, node):
... | stack_v2_sparse_classes_36k_train_031378 | 2,262 | permissive | [
{
"docstring": "- desc : insert configuration data",
"name": "post",
"signature": "def post(self, request, nnid, ver, node)"
},
{
"docstring": "- desc : get configuration data",
"name": "get",
"signature": "def get(self, request, nnid, ver, node)"
},
{
"docstring": "- desc ; upda... | 4 | stack_v2_sparse_classes_30k_train_010830 | Implement the Python class `WorkFlowNetConfFastText` described below.
Class description:
Implement the WorkFlowNetConfFastText class.
Method signatures and docstrings:
- def post(self, request, nnid, ver, node): - desc : insert configuration data
- def get(self, request, nnid, ver, node): - desc : get configuration d... | Implement the Python class `WorkFlowNetConfFastText` described below.
Class description:
Implement the WorkFlowNetConfFastText class.
Method signatures and docstrings:
- def post(self, request, nnid, ver, node): - desc : insert configuration data
- def get(self, request, nnid, ver, node): - desc : get configuration d... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class WorkFlowNetConfFastText:
def post(self, request, nnid, ver, node):
"""- desc : insert configuration data"""
<|body_0|>
def get(self, request, nnid, ver, node):
"""- desc : get configuration data"""
<|body_1|>
def put(self, request, nnid, ver, node):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkFlowNetConfFastText:
def post(self, request, nnid, ver, node):
"""- desc : insert configuration data"""
try:
key = ''.join([nnid, '_', ver, '_', node])
return_data = ft_conf(key).set_conf_data(request.data)
return Response(json.dumps(return_data))
... | the_stack_v2_python_sparse | api/views/workflow_netconf_fasttext.py | yurimkoo/tensormsa | train | 1 | |
48165ed8ac03ed27d2a6ca76be28f6ab6314d1a7 | [
"citations.sort(reverse=True)\ni = 0\nwhile i < len(citations) and i + 1 <= citations[i]:\n i += 1\nreturn i",
"n = len(citations)\ncounter = defaultdict(int)\nacc = 0\nfor citation in citations:\n counter[citation] += 1\n if citation <= 0:\n acc += 1\ni = 1\nwhile i <= n:\n if n - acc < i:\n ... | <|body_start_0|>
citations.sort(reverse=True)
i = 0
while i < len(citations) and i + 1 <= citations[i]:
i += 1
return i
<|end_body_0|>
<|body_start_1|>
n = len(citations)
counter = defaultdict(int)
acc = 0
for citation in citations:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hIndexnlgn(self, citations):
"""O(nlgn) solution. :type citations: List[int] :rtype: int"""
<|body_0|>
def hIndex(self, citations):
"""O(n) solution. Most certainly you need to check the relationship: left: i right: num of var that is >= i. if left <= r... | stack_v2_sparse_classes_36k_train_031379 | 2,929 | no_license | [
{
"docstring": "O(nlgn) solution. :type citations: List[int] :rtype: int",
"name": "hIndexnlgn",
"signature": "def hIndexnlgn(self, citations)"
},
{
"docstring": "O(n) solution. Most certainly you need to check the relationship: left: i right: num of var that is >= i. if left <= right, i is a po... | 2 | stack_v2_sparse_classes_30k_train_006357 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hIndexnlgn(self, citations): O(nlgn) solution. :type citations: List[int] :rtype: int
- def hIndex(self, citations): O(n) solution. Most certainly you need to check the relat... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hIndexnlgn(self, citations): O(nlgn) solution. :type citations: List[int] :rtype: int
- def hIndex(self, citations): O(n) solution. Most certainly you need to check the relat... | 33c623f226981942780751554f0593f2c71cf458 | <|skeleton|>
class Solution:
def hIndexnlgn(self, citations):
"""O(nlgn) solution. :type citations: List[int] :rtype: int"""
<|body_0|>
def hIndex(self, citations):
"""O(n) solution. Most certainly you need to check the relationship: left: i right: num of var that is >= i. if left <= r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hIndexnlgn(self, citations):
"""O(nlgn) solution. :type citations: List[int] :rtype: int"""
citations.sort(reverse=True)
i = 0
while i < len(citations) and i + 1 <= citations[i]:
i += 1
return i
def hIndex(self, citations):
"""O(n)... | the_stack_v2_python_sparse | arr/leetcode_H_Index.py | monkeylyf/interviewjam | train | 59 | |
a73b0a9134980cf3a7d599181da459c570026ffc | [
"posting_1 = next(p1, None)\nposting_2 = next(p2, None)\nwhile posting_1 and posting_2:\n if posting_1.document_id == posting_2.document_id:\n yield posting_1\n posting_1 = next(p1, None)\n posting_2 = next(p2, None)\n elif posting_1.document_id < posting_2.document_id:\n posting_1... | <|body_start_0|>
posting_1 = next(p1, None)
posting_2 = next(p2, None)
while posting_1 and posting_2:
if posting_1.document_id == posting_2.document_id:
yield posting_1
posting_1 = next(p1, None)
posting_2 = next(p2, None)
e... | Utility class for merging posting lists. | PostingsMerger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostingsMerger:
"""Utility class for merging posting lists."""
def intersection(p1: Iterator[Posting], p2: Iterator[Posting]) -> Iterator[Posting]:
"""A generator that yields a simple AND of two posting lists, given iterators over these. The posting lists are assumed sorted in increa... | stack_v2_sparse_classes_36k_train_031380 | 2,191 | no_license | [
{
"docstring": "A generator that yields a simple AND of two posting lists, given iterators over these. The posting lists are assumed sorted in increasing order according to the document identifiers.",
"name": "intersection",
"signature": "def intersection(p1: Iterator[Posting], p2: Iterator[Posting]) ->... | 2 | stack_v2_sparse_classes_30k_train_005755 | Implement the Python class `PostingsMerger` described below.
Class description:
Utility class for merging posting lists.
Method signatures and docstrings:
- def intersection(p1: Iterator[Posting], p2: Iterator[Posting]) -> Iterator[Posting]: A generator that yields a simple AND of two posting lists, given iterators o... | Implement the Python class `PostingsMerger` described below.
Class description:
Utility class for merging posting lists.
Method signatures and docstrings:
- def intersection(p1: Iterator[Posting], p2: Iterator[Posting]) -> Iterator[Posting]: A generator that yields a simple AND of two posting lists, given iterators o... | 5681bef9d39b3987e4dbb9578a8e06c18c7b31b6 | <|skeleton|>
class PostingsMerger:
"""Utility class for merging posting lists."""
def intersection(p1: Iterator[Posting], p2: Iterator[Posting]) -> Iterator[Posting]:
"""A generator that yields a simple AND of two posting lists, given iterators over these. The posting lists are assumed sorted in increa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostingsMerger:
"""Utility class for merging posting lists."""
def intersection(p1: Iterator[Posting], p2: Iterator[Posting]) -> Iterator[Posting]:
"""A generator that yields a simple AND of two posting lists, given iterators over these. The posting lists are assumed sorted in increasing order ac... | the_stack_v2_python_sparse | in3120/assignment_a/traversal.py | hutor04/UiO | train | 0 |
c75452dacfa0f36640ada142f2c5dbd3511d53c5 | [
"physical_line = self.physical_line\nif disable_noqa:\n return False\nif physical_line is None:\n physical_line = linecache.getline(self.filename, self.line_number)\nnoqa_match = find_noqa(physical_line)\nif noqa_match is None:\n LOG.debug('%r is not inline ignored', self)\n return False\ncodes_str = no... | <|body_start_0|>
physical_line = self.physical_line
if disable_noqa:
return False
if physical_line is None:
physical_line = linecache.getline(self.filename, self.line_number)
noqa_match = find_noqa(physical_line)
if noqa_match is None:
LOG.debu... | Class representing a violation reported by Flake8. | Violation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Violation:
"""Class representing a violation reported by Flake8."""
def is_inline_ignored(self, disable_noqa):
"""Determine if an comment has been added to ignore this line. :param bool disable_noqa: Whether or not users have provided ``--disable-noqa``. :returns: True if error is ig... | stack_v2_sparse_classes_36k_train_031381 | 15,881 | permissive | [
{
"docstring": "Determine if an comment has been added to ignore this line. :param bool disable_noqa: Whether or not users have provided ``--disable-noqa``. :returns: True if error is ignored in-line, False otherwise. :rtype: bool",
"name": "is_inline_ignored",
"signature": "def is_inline_ignored(self, ... | 2 | null | Implement the Python class `Violation` described below.
Class description:
Class representing a violation reported by Flake8.
Method signatures and docstrings:
- def is_inline_ignored(self, disable_noqa): Determine if an comment has been added to ignore this line. :param bool disable_noqa: Whether or not users have p... | Implement the Python class `Violation` described below.
Class description:
Class representing a violation reported by Flake8.
Method signatures and docstrings:
- def is_inline_ignored(self, disable_noqa): Determine if an comment has been added to ignore this line. :param bool disable_noqa: Whether or not users have p... | b298bc5d59e5aea9d494282910faf522c08ebba9 | <|skeleton|>
class Violation:
"""Class representing a violation reported by Flake8."""
def is_inline_ignored(self, disable_noqa):
"""Determine if an comment has been added to ignore this line. :param bool disable_noqa: Whether or not users have provided ``--disable-noqa``. :returns: True if error is ig... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Violation:
"""Class representing a violation reported by Flake8."""
def is_inline_ignored(self, disable_noqa):
"""Determine if an comment has been added to ignore this line. :param bool disable_noqa: Whether or not users have provided ``--disable-noqa``. :returns: True if error is ignored in-line... | the_stack_v2_python_sparse | blackmamba/lib/flake8/style_guide.py | zrzka/blackmamba | train | 72 |
ced762aac0810fc6edb979ac9561c4dca30e2e9c | [
"var = torch.exp(logvar)\ntransformed_var = var * parameters.exp()\nsuper().__init__(loc, torch.sqrt(transformed_var), validate_args=False)",
"new = self._get_checked_instance(ScaledNormalLikelihood, _instance)\nbatch_shape = torch.Size(batch_shape)\nnew.loc = self.loc.expand(batch_shape)\nnew.scale = self.scale.... | <|body_start_0|>
var = torch.exp(logvar)
transformed_var = var * parameters.exp()
super().__init__(loc, torch.sqrt(transformed_var), validate_args=False)
<|end_body_0|>
<|body_start_1|>
new = self._get_checked_instance(ScaledNormalLikelihood, _instance)
batch_shape = torch.Size(... | Standard likelihood of a normal distribution used within :class:`netcal.regression.gp.GPNormal` with additional rescaling parameters for the variance. This method provides the likelihood for the :class:`netcal.regression.gp.GPNormal` by applying a rescaling of the uncalibrated input variance by a recalibration paramete... | ScaledNormalLikelihood | [
"MPL-2.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScaledNormalLikelihood:
"""Standard likelihood of a normal distribution used within :class:`netcal.regression.gp.GPNormal` with additional rescaling parameters for the variance. This method provides the likelihood for the :class:`netcal.regression.gp.GPNormal` by applying a rescaling of the uncal... | stack_v2_sparse_classes_36k_train_031382 | 3,083 | permissive | [
{
"docstring": "Constructor. For detailed parameter description, see class docs.",
"name": "__init__",
"signature": "def __init__(self, loc: torch.Tensor, logvar: torch.Tensor, parameters: torch.Tensor)"
},
{
"docstring": "Expand-method. Reimplementation required when sub-classing the Normal dis... | 2 | stack_v2_sparse_classes_30k_train_000954 | Implement the Python class `ScaledNormalLikelihood` described below.
Class description:
Standard likelihood of a normal distribution used within :class:`netcal.regression.gp.GPNormal` with additional rescaling parameters for the variance. This method provides the likelihood for the :class:`netcal.regression.gp.GPNorma... | Implement the Python class `ScaledNormalLikelihood` described below.
Class description:
Standard likelihood of a normal distribution used within :class:`netcal.regression.gp.GPNormal` with additional rescaling parameters for the variance. This method provides the likelihood for the :class:`netcal.regression.gp.GPNorma... | 45bebd15c873ae399348b8148eb2ea5c89254d27 | <|skeleton|>
class ScaledNormalLikelihood:
"""Standard likelihood of a normal distribution used within :class:`netcal.regression.gp.GPNormal` with additional rescaling parameters for the variance. This method provides the likelihood for the :class:`netcal.regression.gp.GPNormal` by applying a rescaling of the uncal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScaledNormalLikelihood:
"""Standard likelihood of a normal distribution used within :class:`netcal.regression.gp.GPNormal` with additional rescaling parameters for the variance. This method provides the likelihood for the :class:`netcal.regression.gp.GPNormal` by applying a rescaling of the uncalibrated input... | the_stack_v2_python_sparse | netcal/regression/gp/likelihood/ScaledNormalLikelihood.py | EFS-OpenSource/calibration-framework | train | 79 |
74d629a486134f5c5abd6ffe88af0e9d3812b812 | [
"super().__init__(viewParent)\nself.spot = spot\nself.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)\nself.update()",
"node = self.spot.nodeRef\nself.setText(node.title())\nif globalref.genOptions['ShowTreeIcons']:\n self.setIcon(globalref.treeIcons.getIcon(node.formatRef.iconName, True))... | <|body_start_0|>
super().__init__(viewParent)
self.spot = spot
self.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
self.update()
<|end_body_0|>
<|body_start_1|>
node = self.spot.nodeRef
self.setText(node.title())
if globalref.genOptions['Sho... | Item container for the flat list of filtered nodes. | TreeFilterViewItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeFilterViewItem:
"""Item container for the flat list of filtered nodes."""
def __init__(self, spot, viewParent=None):
"""Initialize the list view item. Arguments: spot -- the spot to reference for content viewParent -- the parent list view"""
<|body_0|>
def update(sel... | stack_v2_sparse_classes_36k_train_031383 | 32,204 | no_license | [
{
"docstring": "Initialize the list view item. Arguments: spot -- the spot to reference for content viewParent -- the parent list view",
"name": "__init__",
"signature": "def __init__(self, spot, viewParent=None)"
},
{
"docstring": "Update title and icon from the stored node.",
"name": "upda... | 2 | null | Implement the Python class `TreeFilterViewItem` described below.
Class description:
Item container for the flat list of filtered nodes.
Method signatures and docstrings:
- def __init__(self, spot, viewParent=None): Initialize the list view item. Arguments: spot -- the spot to reference for content viewParent -- the p... | Implement the Python class `TreeFilterViewItem` described below.
Class description:
Item container for the flat list of filtered nodes.
Method signatures and docstrings:
- def __init__(self, spot, viewParent=None): Initialize the list view item. Arguments: spot -- the spot to reference for content viewParent -- the p... | c9429496e8ed15116746a23f3a90f262cf54f755 | <|skeleton|>
class TreeFilterViewItem:
"""Item container for the flat list of filtered nodes."""
def __init__(self, spot, viewParent=None):
"""Initialize the list view item. Arguments: spot -- the spot to reference for content viewParent -- the parent list view"""
<|body_0|>
def update(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TreeFilterViewItem:
"""Item container for the flat list of filtered nodes."""
def __init__(self, spot, viewParent=None):
"""Initialize the list view item. Arguments: spot -- the spot to reference for content viewParent -- the parent list view"""
super().__init__(viewParent)
self.s... | the_stack_v2_python_sparse | source/treeview.py | doug-101/TreeLine | train | 121 |
441709b6af440a3c0c39b5e908e564251f4aa207 | [
"ans = []\n\ndef preorder(node):\n if node:\n ans.append(str(node.val))\n preorder(node.left)\n preorder(node.right)\npreorder(root)\nreturn ' '.join(ans)",
"if not data:\n return None\nvals = collections.deque([int(val) for val in data.split(' ')])\n\ndef helper(min_val, max_val):\n ... | <|body_start_0|>
ans = []
def preorder(node):
if node:
ans.append(str(node.val))
preorder(node.left)
preorder(node.right)
preorder(root)
return ' '.join(ans)
<|end_body_0|>
<|body_start_1|>
if not data:
ret... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = []
... | stack_v2_sparse_classes_36k_train_031384 | 1,556 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_018642 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 0bfae06b1e4538a65fe449e258116b9fcc04e538 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
ans = []
def preorder(node):
if node:
ans.append(str(node.val))
preorder(node.left)
preorder(node.right)
preorder(root)
... | the_stack_v2_python_sparse | Tree/449_Serialize_and_Deserialize_BST.py | r06921039/Leetcode | train | 0 | |
97c158f100d0c662d1e3079fe34af70c7a65d6df | [
"from grads import GrADS\nga = GrADS(Window=False, Echo=False)\nfh = ga.open(url)\nif Levels is not None:\n ga('set lev %s' % Levels)\nif Vars is None:\n Vars = ga.query('file').vars\nelif type(Vars) is StringType:\n Vars = [Vars]\nfor var in Vars:\n if Verbose:\n print(' Working on <%s>' % var)\... | <|body_start_0|>
from grads import GrADS
ga = GrADS(Window=False, Echo=False)
fh = ga.open(url)
if Levels is not None:
ga('set lev %s' % Levels)
if Vars is None:
Vars = ga.query('file').vars
elif type(Vars) is StringType:
Vars = [Vars]
... | Curtain | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Curtain:
def addVar(self, url, Vars=None, Verbose=True, Levels=None):
"""Sample variable along flight path."""
<|body_0|>
def sampleExt(self, asm_Np, asm_Nv, ext_Np, flx_Nx):
"""Sample GEOS-5 Variables at flight path."""
<|body_1|>
def sampleAer(self, as... | stack_v2_sparse_classes_36k_train_031385 | 7,746 | permissive | [
{
"docstring": "Sample variable along flight path.",
"name": "addVar",
"signature": "def addVar(self, url, Vars=None, Verbose=True, Levels=None)"
},
{
"docstring": "Sample GEOS-5 Variables at flight path.",
"name": "sampleExt",
"signature": "def sampleExt(self, asm_Np, asm_Nv, ext_Np, fl... | 3 | null | Implement the Python class `Curtain` described below.
Class description:
Implement the Curtain class.
Method signatures and docstrings:
- def addVar(self, url, Vars=None, Verbose=True, Levels=None): Sample variable along flight path.
- def sampleExt(self, asm_Np, asm_Nv, ext_Np, flx_Nx): Sample GEOS-5 Variables at fl... | Implement the Python class `Curtain` described below.
Class description:
Implement the Curtain class.
Method signatures and docstrings:
- def addVar(self, url, Vars=None, Verbose=True, Levels=None): Sample variable along flight path.
- def sampleExt(self, asm_Np, asm_Nv, ext_Np, flx_Nx): Sample GEOS-5 Variables at fl... | dff1f2ed36189f6879409375d241be40f18c5666 | <|skeleton|>
class Curtain:
def addVar(self, url, Vars=None, Verbose=True, Levels=None):
"""Sample variable along flight path."""
<|body_0|>
def sampleExt(self, asm_Np, asm_Nv, ext_Np, flx_Nx):
"""Sample GEOS-5 Variables at flight path."""
<|body_1|>
def sampleAer(self, as... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Curtain:
def addVar(self, url, Vars=None, Verbose=True, Levels=None):
"""Sample variable along flight path."""
from grads import GrADS
ga = GrADS(Window=False, Echo=False)
fh = ga.open(url)
if Levels is not None:
ga('set lev %s' % Levels)
if Vars is ... | the_stack_v2_python_sparse | src/Components/missions/SEAC4RS/Curtains/curtain.py | GEOS-ESM/AeroApps | train | 4 | |
c3e876561c8e5375d108e5ecc706a11f192da1c6 | [
"try:\n x = cls.get_list_val(x)\nexcept AssertionError:\n return False\nreturn x == cls.OK",
"try:\n x = cls.get_list_val(x)\nexcept AssertionError:\n return False\nreturn cls.has(x) and x != cls.OK",
"val1 = cls.get_list_val(val1)\nval2 = cls.get_list_val(val2)\nreturn cls.has(val1) and cls.has(val... | <|body_start_0|>
try:
x = cls.get_list_val(x)
except AssertionError:
return False
return x == cls.OK
<|end_body_0|>
<|body_start_1|>
try:
x = cls.get_list_val(x)
except AssertionError:
return False
return cls.has(x) and x !... | Error codes generated by instrument drivers and agents | InstErrorCode | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstErrorCode:
"""Error codes generated by instrument drivers and agents"""
def is_ok(cls, x):
"""Success test functional synonym. Will need iterable type checking if success codes get additional info in the future. @param x a str, tuple or list to match to an error code success valu... | stack_v2_sparse_classes_36k_train_031386 | 9,909 | permissive | [
{
"docstring": "Success test functional synonym. Will need iterable type checking if success codes get additional info in the future. @param x a str, tuple or list to match to an error code success value. @retval True if x is a success value, False otherwise.",
"name": "is_ok",
"signature": "def is_ok(c... | 5 | stack_v2_sparse_classes_30k_train_012977 | Implement the Python class `InstErrorCode` described below.
Class description:
Error codes generated by instrument drivers and agents
Method signatures and docstrings:
- def is_ok(cls, x): Success test functional synonym. Will need iterable type checking if success codes get additional info in the future. @param x a ... | Implement the Python class `InstErrorCode` described below.
Class description:
Error codes generated by instrument drivers and agents
Method signatures and docstrings:
- def is_ok(cls, x): Success test functional synonym. Will need iterable type checking if success codes get additional info in the future. @param x a ... | 122c629290d27f32f2f41dafd5c12469295e8acf | <|skeleton|>
class InstErrorCode:
"""Error codes generated by instrument drivers and agents"""
def is_ok(cls, x):
"""Success test functional synonym. Will need iterable type checking if success codes get additional info in the future. @param x a str, tuple or list to match to an error code success valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstErrorCode:
"""Error codes generated by instrument drivers and agents"""
def is_ok(cls, x):
"""Success test functional synonym. Will need iterable type checking if success codes get additional info in the future. @param x a str, tuple or list to match to an error code success value. @retval Tr... | the_stack_v2_python_sparse | pyon/agent/common.py | ooici/pyon | train | 9 |
fb320c59e5dce45a7f32046022ce81191d2abcce | [
"rand_seed = int(time.time())\nsr.seed(rand_seed)\nprint('seed for this test: ' + str(rand_seed))",
"generate = g.TEST_TYPE_TO_GENERATOR_BY_DEPTH[g.TEST_TYPES.RANDOM]\nL = 100\nD = 10\nW = 10\nnum_trials = 50\ngate_type_dist = dict(((gate_type, []) for gate_type in g.GATE_TYPES.values_generator()))\noutput_gate_t... | <|body_start_0|>
rand_seed = int(time.time())
sr.seed(rand_seed)
print('seed for this test: ' + str(rand_seed))
<|end_body_0|>
<|body_start_1|>
generate = g.TEST_TYPE_TO_GENERATOR_BY_DEPTH[g.TEST_TYPES.RANDOM]
L = 100
D = 10
W = 10
num_trials = 50
... | generation_functions_test | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class generation_functions_test:
def setUp(self):
"""Records the randomness used."""
<|body_0|>
def test_dist_gates(self):
"""tests that the distribution of gate types is not too skewed in circuit generation with random gate type. Specifically, tests that the fraction of g... | stack_v2_sparse_classes_36k_train_031387 | 6,269 | permissive | [
{
"docstring": "Records the randomness used.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "tests that the distribution of gate types is not too skewed in circuit generation with random gate type. Specifically, tests that the fraction of gates belonging to each gate type is... | 5 | stack_v2_sparse_classes_30k_train_011185 | Implement the Python class `generation_functions_test` described below.
Class description:
Implement the generation_functions_test class.
Method signatures and docstrings:
- def setUp(self): Records the randomness used.
- def test_dist_gates(self): tests that the distribution of gate types is not too skewed in circui... | Implement the Python class `generation_functions_test` described below.
Class description:
Implement the generation_functions_test class.
Method signatures and docstrings:
- def setUp(self): Records the randomness used.
- def test_dist_gates(self): tests that the distribution of gate types is not too skewed in circui... | 264459a8fa1480c7b65d946f88d94af1a038fbf1 | <|skeleton|>
class generation_functions_test:
def setUp(self):
"""Records the randomness used."""
<|body_0|>
def test_dist_gates(self):
"""tests that the distribution of gate types is not too skewed in circuit generation with random gate type. Specifically, tests that the fraction of g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class generation_functions_test:
def setUp(self):
"""Records the randomness used."""
rand_seed = int(time.time())
sr.seed(rand_seed)
print('seed for this test: ' + str(rand_seed))
def test_dist_gates(self):
"""tests that the distribution of gate types is not too skewed i... | the_stack_v2_python_sparse | hetest/python/circuit_generation/ibm/ibm_generation_functions_test.py | y4n9squared/HEtest | train | 7 | |
61b8194c8adf09745cfb8f24dfb02f155e6540b6 | [
"try:\n subscriber_lists = current_app.mailchimp_client.lists.all()\nexcept MailChimpError as api_error:\n response = {'errors': {}}\n error_details = api_error.args[0]\n response['errors']['title'] = error_details['title']\n response['errors']['detail'] = error_details['detail']\n return (respons... | <|body_start_0|>
try:
subscriber_lists = current_app.mailchimp_client.lists.all()
except MailChimpError as api_error:
response = {'errors': {}}
error_details = api_error.args[0]
response['errors']['title'] = error_details['title']
response['err... | Class-based view for creating a new subscriber list and getting all subscriber lists from the Mailchimp API. | SubscriberListsAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscriberListsAPI:
"""Class-based view for creating a new subscriber list and getting all subscriber lists from the Mailchimp API."""
def get(self):
"""Return all subscriber lists from the Mailchimp API."""
<|body_0|>
def post(self):
"""Create a new subscriber l... | stack_v2_sparse_classes_36k_train_031388 | 3,196 | no_license | [
{
"docstring": "Return all subscriber lists from the Mailchimp API.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a new subscriber list using the Mailchimp API.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `SubscriberListsAPI` described below.
Class description:
Class-based view for creating a new subscriber list and getting all subscriber lists from the Mailchimp API.
Method signatures and docstrings:
- def get(self): Return all subscriber lists from the Mailchimp API.
- def post(self): Crea... | Implement the Python class `SubscriberListsAPI` described below.
Class description:
Class-based view for creating a new subscriber list and getting all subscriber lists from the Mailchimp API.
Method signatures and docstrings:
- def get(self): Return all subscriber lists from the Mailchimp API.
- def post(self): Crea... | d5ae552d383f5f971e29a38055c518fc68172f32 | <|skeleton|>
class SubscriberListsAPI:
"""Class-based view for creating a new subscriber list and getting all subscriber lists from the Mailchimp API."""
def get(self):
"""Return all subscriber lists from the Mailchimp API."""
<|body_0|>
def post(self):
"""Create a new subscriber l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubscriberListsAPI:
"""Class-based view for creating a new subscriber list and getting all subscriber lists from the Mailchimp API."""
def get(self):
"""Return all subscriber lists from the Mailchimp API."""
try:
subscriber_lists = current_app.mailchimp_client.lists.all()
... | the_stack_v2_python_sparse | server/app/mailchimp/resources/subscriber_lists.py | EricMontague/MailChimp-Newsletter-Project | train | 0 |
8c8f3ed8ce213156793bd67e0cea6b37f5c0cbdd | [
"self.__pHardwareComm = pHardwareComm\nself.__nStartX = nStartX\nself.__nStartZ = nStartZ\nself.__nTargetX = nTargetX\nself.__nTargetZ = nTargetZ",
"x = self.__nStartX\nz = self.__nStartZ\nnStepX = (self.__nTargetX - self.__nStartX) / 10\nnStepZ = (self.__nTargetZ - self.__nStartZ) / 10\nfor nCount in range(1, 11... | <|body_start_0|>
self.__pHardwareComm = pHardwareComm
self.__nStartX = nStartX
self.__nStartZ = nStartZ
self.__nTargetX = nTargetX
self.__nTargetZ = nTargetZ
<|end_body_0|>
<|body_start_1|>
x = self.__nStartX
z = self.__nStartZ
nStepX = (self.__nTargetX -... | MoveReagentRobotThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoveReagentRobotThread:
def SetParameters(self, pHardwareComm, nStartX, nStartZ, nTargetX, nTargetZ):
"""Sets the pressure regulator thread parameters"""
<|body_0|>
def run(self):
"""Thread entry point"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_031389 | 1,394 | no_license | [
{
"docstring": "Sets the pressure regulator thread parameters",
"name": "SetParameters",
"signature": "def SetParameters(self, pHardwareComm, nStartX, nStartZ, nTargetX, nTargetZ)"
},
{
"docstring": "Thread entry point",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000784 | Implement the Python class `MoveReagentRobotThread` described below.
Class description:
Implement the MoveReagentRobotThread class.
Method signatures and docstrings:
- def SetParameters(self, pHardwareComm, nStartX, nStartZ, nTargetX, nTargetZ): Sets the pressure regulator thread parameters
- def run(self): Thread en... | Implement the Python class `MoveReagentRobotThread` described below.
Class description:
Implement the MoveReagentRobotThread class.
Method signatures and docstrings:
- def SetParameters(self, pHardwareComm, nStartX, nStartZ, nTargetX, nTargetZ): Sets the pressure regulator thread parameters
- def run(self): Thread en... | c6954ca0fff935ce1eb8154744f6307743765dc5 | <|skeleton|>
class MoveReagentRobotThread:
def SetParameters(self, pHardwareComm, nStartX, nStartZ, nTargetX, nTargetZ):
"""Sets the pressure regulator thread parameters"""
<|body_0|>
def run(self):
"""Thread entry point"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MoveReagentRobotThread:
def SetParameters(self, pHardwareComm, nStartX, nStartZ, nTargetX, nTargetZ):
"""Sets the pressure regulator thread parameters"""
self.__pHardwareComm = pHardwareComm
self.__nStartX = nStartX
self.__nStartZ = nStartZ
self.__nTargetX = nTargetX
... | the_stack_v2_python_sparse | server/hardware/fakeplc/MoveReagentRobotThread.py | henryeherman/elixys | train | 1 | |
ac3a7a66cc07453c364ad30a3ede2d9bbbebae4f | [
"self._strategy = strategy\nself._ssl_dataset_name = ssl_dataset_name\nself._ds_dataset_name = ds_dataset_name\nself._model_path = model_path\nself._experiment_id = experiment_id\nself._batch_size = batch_size\nself._epochs = epochs\nself._learning_rate = learning_rate\nself._temperature = temperature\nself._embedd... | <|body_start_0|>
self._strategy = strategy
self._ssl_dataset_name = ssl_dataset_name
self._ds_dataset_name = ds_dataset_name
self._model_path = model_path
self._experiment_id = experiment_id
self._batch_size = batch_size
self._epochs = epochs
self._learnin... | Provides functionality for self-supervised constrastive learning model. | ContrastiveModel | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContrastiveModel:
"""Provides functionality for self-supervised constrastive learning model."""
def __init__(self, strategy, ssl_dataset_name, ds_dataset_name, model_path, experiment_id, batch_size, epochs, learning_rate, embedding_dim, temperature, similarity_type, pooling_type, noise, step... | stack_v2_sparse_classes_36k_train_031390 | 4,801 | permissive | [
{
"docstring": "Initializes a contrastive model object.",
"name": "__init__",
"signature": "def __init__(self, strategy, ssl_dataset_name, ds_dataset_name, model_path, experiment_id, batch_size, epochs, learning_rate, embedding_dim, temperature, similarity_type, pooling_type, noise, steps_per_epoch=1000... | 4 | stack_v2_sparse_classes_30k_train_003730 | Implement the Python class `ContrastiveModel` described below.
Class description:
Provides functionality for self-supervised constrastive learning model.
Method signatures and docstrings:
- def __init__(self, strategy, ssl_dataset_name, ds_dataset_name, model_path, experiment_id, batch_size, epochs, learning_rate, em... | Implement the Python class `ContrastiveModel` described below.
Class description:
Provides functionality for self-supervised constrastive learning model.
Method signatures and docstrings:
- def __init__(self, strategy, ssl_dataset_name, ds_dataset_name, model_path, experiment_id, batch_size, epochs, learning_rate, em... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ContrastiveModel:
"""Provides functionality for self-supervised constrastive learning model."""
def __init__(self, strategy, ssl_dataset_name, ds_dataset_name, model_path, experiment_id, batch_size, epochs, learning_rate, embedding_dim, temperature, similarity_type, pooling_type, noise, step... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContrastiveModel:
"""Provides functionality for self-supervised constrastive learning model."""
def __init__(self, strategy, ssl_dataset_name, ds_dataset_name, model_path, experiment_id, batch_size, epochs, learning_rate, embedding_dim, temperature, similarity_type, pooling_type, noise, steps_per_epoch=1... | the_stack_v2_python_sparse | cola/contrastive.py | Jimmy-INL/google-research | train | 1 |
bb93d34dadc91e96859a45bfff6fd1feb9f2422f | [
"ls = os.listdir(path)\ntry:\n ls.remove('__init__.py')\nexcept ValueError:\n pass\nreturn ls",
"for class_ in AlgorithmRepository.__list_dir(ALGORITHM_ROOT_DIRECTORY):\n for item in AlgorithmRepository.__list_dir(ALGORITHM_ROOT_DIRECTORY + class_):\n if item.split('.')[0].upper().strip() == algor... | <|body_start_0|>
ls = os.listdir(path)
try:
ls.remove('__init__.py')
except ValueError:
pass
return ls
<|end_body_0|>
<|body_start_1|>
for class_ in AlgorithmRepository.__list_dir(ALGORITHM_ROOT_DIRECTORY):
for item in AlgorithmRepository.__li... | Algorithm repository class. | AlgorithmRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlgorithmRepository:
"""Algorithm repository class."""
def __list_dir(path: str) -> Iterable[str]:
"""Lists the content of a given path without the __init__.py file. :param path: :return:"""
<|body_0|>
def get_algorithm_path(algorithm_name: str) -> Tuple[str, str]:
... | stack_v2_sparse_classes_36k_train_031391 | 1,355 | no_license | [
{
"docstring": "Lists the content of a given path without the __init__.py file. :param path: :return:",
"name": "__list_dir",
"signature": "def __list_dir(path: str) -> Iterable[str]"
},
{
"docstring": "Returns the path to the source file of the algorithm by name. :param algorithm_name: the name... | 2 | stack_v2_sparse_classes_30k_train_000200 | Implement the Python class `AlgorithmRepository` described below.
Class description:
Algorithm repository class.
Method signatures and docstrings:
- def __list_dir(path: str) -> Iterable[str]: Lists the content of a given path without the __init__.py file. :param path: :return:
- def get_algorithm_path(algorithm_name... | Implement the Python class `AlgorithmRepository` described below.
Class description:
Algorithm repository class.
Method signatures and docstrings:
- def __list_dir(path: str) -> Iterable[str]: Lists the content of a given path without the __init__.py file. :param path: :return:
- def get_algorithm_path(algorithm_name... | a95fd2c4414c7f4fdaf6f8465dcaba311f6f70ce | <|skeleton|>
class AlgorithmRepository:
"""Algorithm repository class."""
def __list_dir(path: str) -> Iterable[str]:
"""Lists the content of a given path without the __init__.py file. :param path: :return:"""
<|body_0|>
def get_algorithm_path(algorithm_name: str) -> Tuple[str, str]:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlgorithmRepository:
"""Algorithm repository class."""
def __list_dir(path: str) -> Iterable[str]:
"""Lists the content of a given path without the __init__.py file. :param path: :return:"""
ls = os.listdir(path)
try:
ls.remove('__init__.py')
except ValueError:... | the_stack_v2_python_sparse | app/controllers/file_controller.py | imayer95/software_quality | train | 0 |
c5bb6caf9efa93ffa7617be294ee90b2978e3e49 | [
"Parametre.__init__(self, 'supprimer', 'del')\nself.schema = '<cle> <coords2d>'\nself.aide_courte = \"retire l'obstacle aux coordonnées\"\nself.aide_longue = \"Cette commande permet de suppriemr un obstacle de l'étendue. Vous devez préciser la clé de l'étendue et les coordonnées, en deux dimensions, du point à supp... | <|body_start_0|>
Parametre.__init__(self, 'supprimer', 'del')
self.schema = '<cle> <coords2d>'
self.aide_courte = "retire l'obstacle aux coordonnées"
self.aide_longue = "Cette commande permet de suppriemr un obstacle de l'étendue. Vous devez préciser la clé de l'étendue et les coordonnée... | Commande 'étendue obstacle supprimer'. | PrmObstacleSupprimer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmObstacleSupprimer:
"""Commande 'étendue obstacle supprimer'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_031392 | 3,314 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmObstacleSupprimer` described below.
Class description:
Commande 'étendue obstacle supprimer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmObstacleSupprimer` described below.
Class description:
Commande 'étendue obstacle supprimer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmObstacleSu... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmObstacleSupprimer:
"""Commande 'étendue obstacle supprimer'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmObstacleSupprimer:
"""Commande 'étendue obstacle supprimer'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'supprimer', 'del')
self.schema = '<cle> <coords2d>'
self.aide_courte = "retire l'obstacle aux coordonnées"
self.aide_lon... | the_stack_v2_python_sparse | src/primaires/salle/commandes/etendue/obstacle_supprimer.py | vincent-lg/tsunami | train | 5 |
4d57ea458e7058767f83e13ebfa47d99b5487a6d | [
"pids = data.get('pids', {})\nself.service.pids.pid_manager.validate(pids, record, errors)\nrecord.pids = pids",
"pids = data.get('pids', {})\nself.service.pids.pid_manager.validate(pids, record, errors)\nrecord.pids = pids",
"to_remove = copy(draft.get('pids', {}))\nrecord_pids = record.get('pids', {}).keys() ... | <|body_start_0|>
pids = data.get('pids', {})
self.service.pids.pid_manager.validate(pids, record, errors)
record.pids = pids
<|end_body_0|>
<|body_start_1|>
pids = data.get('pids', {})
self.service.pids.pid_manager.validate(pids, record, errors)
record.pids = pids
<|end_... | Service component for PIDs. | PIDsComponent | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PIDsComponent:
"""Service component for PIDs."""
def create(self, identity, data=None, record=None, errors=None):
"""This method is called on draft creation. It validates and add the pids to the draft."""
<|body_0|>
def update_draft(self, identity, data=None, record=None... | stack_v2_sparse_classes_36k_train_031393 | 4,943 | permissive | [
{
"docstring": "This method is called on draft creation. It validates and add the pids to the draft.",
"name": "create",
"signature": "def create(self, identity, data=None, record=None, errors=None)"
},
{
"docstring": "Update draft handler.",
"name": "update_draft",
"signature": "def upd... | 6 | null | Implement the Python class `PIDsComponent` described below.
Class description:
Service component for PIDs.
Method signatures and docstrings:
- def create(self, identity, data=None, record=None, errors=None): This method is called on draft creation. It validates and add the pids to the draft.
- def update_draft(self, ... | Implement the Python class `PIDsComponent` described below.
Class description:
Service component for PIDs.
Method signatures and docstrings:
- def create(self, identity, data=None, record=None, errors=None): This method is called on draft creation. It validates and add the pids to the draft.
- def update_draft(self, ... | b4bcc2e16df6048149177a6e1ebd514bdb6b0626 | <|skeleton|>
class PIDsComponent:
"""Service component for PIDs."""
def create(self, identity, data=None, record=None, errors=None):
"""This method is called on draft creation. It validates and add the pids to the draft."""
<|body_0|>
def update_draft(self, identity, data=None, record=None... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PIDsComponent:
"""Service component for PIDs."""
def create(self, identity, data=None, record=None, errors=None):
"""This method is called on draft creation. It validates and add the pids to the draft."""
pids = data.get('pids', {})
self.service.pids.pid_manager.validate(pids, rec... | the_stack_v2_python_sparse | invenio_rdm_records/services/components/pids.py | ppanero/invenio-rdm-records | train | 0 |
769cd701a24ecb352098ad2436cbdb4ea67f96f9 | [
"if not name:\n self.abort(400, 'Missing options')\nif not current_user.is_anonymous and (not current_user.acl.is_admin()) and (not current_user.acl.is_client_allowed(name, server)):\n self.abort(403, 'You are not allowed to access this client')\ntry:\n return {'is_server_backup': bui.client.is_server_back... | <|body_start_0|>
if not name:
self.abort(400, 'Missing options')
if not current_user.is_anonymous and (not current_user.acl.is_admin()) and (not current_user.acl.is_client_allowed(name, server)):
self.abort(403, 'You are not allowed to access this client')
try:
... | The :class:`burpui.api.backup.ServerBackup` resource allows you to prepare a server-initiated backup. This resource is part of the :mod:`burpui.api.backup` module. | ServerBackup | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerBackup:
"""The :class:`burpui.api.backup.ServerBackup` resource allows you to prepare a server-initiated backup. This resource is part of the :mod:`burpui.api.backup` module."""
def get(self, server=None, name=None):
"""Tells if a 'backup' file is present **GET** method provide... | stack_v2_sparse_classes_36k_train_031394 | 4,961 | permissive | [
{
"docstring": "Tells if a 'backup' file is present **GET** method provided by the webservice. :param server: Which server to collect data from when in multi-agent mode :type server: str :param name: The client we are working on :type name: str :returns: True if the file is found",
"name": "get",
"signa... | 3 | stack_v2_sparse_classes_30k_train_018022 | Implement the Python class `ServerBackup` described below.
Class description:
The :class:`burpui.api.backup.ServerBackup` resource allows you to prepare a server-initiated backup. This resource is part of the :mod:`burpui.api.backup` module.
Method signatures and docstrings:
- def get(self, server=None, name=None): T... | Implement the Python class `ServerBackup` described below.
Class description:
The :class:`burpui.api.backup.ServerBackup` resource allows you to prepare a server-initiated backup. This resource is part of the :mod:`burpui.api.backup` module.
Method signatures and docstrings:
- def get(self, server=None, name=None): T... | 2b8c6e09a4174f2ae3545fa048f59c55c4ae7dba | <|skeleton|>
class ServerBackup:
"""The :class:`burpui.api.backup.ServerBackup` resource allows you to prepare a server-initiated backup. This resource is part of the :mod:`burpui.api.backup` module."""
def get(self, server=None, name=None):
"""Tells if a 'backup' file is present **GET** method provide... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServerBackup:
"""The :class:`burpui.api.backup.ServerBackup` resource allows you to prepare a server-initiated backup. This resource is part of the :mod:`burpui.api.backup` module."""
def get(self, server=None, name=None):
"""Tells if a 'backup' file is present **GET** method provided by the webs... | the_stack_v2_python_sparse | burpui/api/backup.py | ziirish/burp-ui | train | 98 |
022513e06de38bc45441ce79e5269fa1cb3ce05e | [
"await data.check(user)\nasync with aiosqlite.connect('data\\\\economy.db') as conn:\n async with conn.execute('SELECT * from ECONOMY') as cursor:\n async for row in cursor:\n if row[0] == user:\n return row[2]",
"await data.check(user)\nasync with aiosqlite.connect('data\\\\ec... | <|body_start_0|>
await data.check(user)
async with aiosqlite.connect('data\\economy.db') as conn:
async with conn.execute('SELECT * from ECONOMY') as cursor:
async for row in cursor:
if row[0] == user:
return row[2]
<|end_body_0|>
... | Bank | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bank:
async def get(self, user):
"""Get someone's bank balance."""
<|body_0|>
async def add(self, user, add):
"""Adds money to someone's bank."""
<|body_1|>
async def remove(self, user, take):
"""Removes money from someone's bank."""
<|bo... | stack_v2_sparse_classes_36k_train_031395 | 5,807 | no_license | [
{
"docstring": "Get someone's bank balance.",
"name": "get",
"signature": "async def get(self, user)"
},
{
"docstring": "Adds money to someone's bank.",
"name": "add",
"signature": "async def add(self, user, add)"
},
{
"docstring": "Removes money from someone's bank.",
"name"... | 3 | stack_v2_sparse_classes_30k_train_016603 | Implement the Python class `Bank` described below.
Class description:
Implement the Bank class.
Method signatures and docstrings:
- async def get(self, user): Get someone's bank balance.
- async def add(self, user, add): Adds money to someone's bank.
- async def remove(self, user, take): Removes money from someone's ... | Implement the Python class `Bank` described below.
Class description:
Implement the Bank class.
Method signatures and docstrings:
- async def get(self, user): Get someone's bank balance.
- async def add(self, user, add): Adds money to someone's bank.
- async def remove(self, user, take): Removes money from someone's ... | 3d075c516124d3a25feebd584fdc351c3abc6613 | <|skeleton|>
class Bank:
async def get(self, user):
"""Get someone's bank balance."""
<|body_0|>
async def add(self, user, add):
"""Adds money to someone's bank."""
<|body_1|>
async def remove(self, user, take):
"""Removes money from someone's bank."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bank:
async def get(self, user):
"""Get someone's bank balance."""
await data.check(user)
async with aiosqlite.connect('data\\economy.db') as conn:
async with conn.execute('SELECT * from ECONOMY') as cursor:
async for row in cursor:
if ro... | the_stack_v2_python_sparse | core/EcoCore.py | Smudge-Studios/smudge | train | 0 | |
f9505cb6e584b53da247837e9d22c998696971b5 | [
"if tree:\n print(tree.get_root_val())\n Orders.preorder(tree.get_left_child())\n Orders.preorder(tree.get_right_child())",
"if tree != None:\n Orders.inorder(tree.get_left_child())\n print(tree.get_root_val())\n Orders.inorder(tree.get_right_child())",
"if tree != None:\n Orders.postorder(... | <|body_start_0|>
if tree:
print(tree.get_root_val())
Orders.preorder(tree.get_left_child())
Orders.preorder(tree.get_right_child())
<|end_body_0|>
<|body_start_1|>
if tree != None:
Orders.inorder(tree.get_left_child())
print(tree.get_root_val(... | Стат методы для обхода дерева | Orders | [
"WTFPL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Orders:
"""Стат методы для обхода дерева"""
def preorder(tree):
"""Прямой обход дерева"""
<|body_0|>
def inorder(tree):
"""Симметричный обход дерева"""
<|body_1|>
def postorder(tree):
"""Обратный обход"""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_031396 | 2,441 | permissive | [
{
"docstring": "Прямой обход дерева",
"name": "preorder",
"signature": "def preorder(tree)"
},
{
"docstring": "Симметричный обход дерева",
"name": "inorder",
"signature": "def inorder(tree)"
},
{
"docstring": "Обратный обход",
"name": "postorder",
"signature": "def postor... | 3 | stack_v2_sparse_classes_30k_train_009839 | Implement the Python class `Orders` described below.
Class description:
Стат методы для обхода дерева
Method signatures and docstrings:
- def preorder(tree): Прямой обход дерева
- def inorder(tree): Симметричный обход дерева
- def postorder(tree): Обратный обход | Implement the Python class `Orders` described below.
Class description:
Стат методы для обхода дерева
Method signatures and docstrings:
- def preorder(tree): Прямой обход дерева
- def inorder(tree): Симметричный обход дерева
- def postorder(tree): Обратный обход
<|skeleton|>
class Orders:
"""Стат методы для обхо... | 9575c43fa01c261ea1ed573df9b5686b5a6f4211 | <|skeleton|>
class Orders:
"""Стат методы для обхода дерева"""
def preorder(tree):
"""Прямой обход дерева"""
<|body_0|>
def inorder(tree):
"""Симметричный обход дерева"""
<|body_1|>
def postorder(tree):
"""Обратный обход"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Orders:
"""Стат методы для обхода дерева"""
def preorder(tree):
"""Прямой обход дерева"""
if tree:
print(tree.get_root_val())
Orders.preorder(tree.get_left_child())
Orders.preorder(tree.get_right_child())
def inorder(tree):
"""Симметричный ... | the_stack_v2_python_sparse | Course_I/Алгоритмы Python/Part2/семинары/pract6/task3/task.py | GeorgiyDemo/FA | train | 46 |
111064024e8fdf6df5e05a3001644f0f4bc6b798 | [
"super(MLP, self).__init__()\nself.regularizer = tf.contrib.layers.l2_regularizer(scale=wd)\nself.initializer = tf.contrib.layers.xavier_initializer()\nself.variance_initializer = tf.contrib.layers.variance_scaling_initializer(factor=0.1, mode='FAN_IN', uniform=False, seed=None, dtype=tf.dtypes.float32)\nself.drop_... | <|body_start_0|>
super(MLP, self).__init__()
self.regularizer = tf.contrib.layers.l2_regularizer(scale=wd)
self.initializer = tf.contrib.layers.xavier_initializer()
self.variance_initializer = tf.contrib.layers.variance_scaling_initializer(factor=0.1, mode='FAN_IN', uniform=False, seed=N... | Definition of MLP Networks. | MLP | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
"""Definition of MLP Networks."""
def __init__(self, keep_prob, wd, feature_dim):
"""Creates a model for classifying an image using VGG networks. Args: keep_prob: The rate of keeping one neuron in Dropout. wd: The co-efficient of weight decay. feature_dim: the dimension of the r... | stack_v2_sparse_classes_36k_train_031397 | 3,214 | permissive | [
{
"docstring": "Creates a model for classifying an image using VGG networks. Args: keep_prob: The rate of keeping one neuron in Dropout. wd: The co-efficient of weight decay. feature_dim: the dimension of the representation space.",
"name": "__init__",
"signature": "def __init__(self, keep_prob, wd, fea... | 3 | stack_v2_sparse_classes_30k_train_010085 | Implement the Python class `MLP` described below.
Class description:
Definition of MLP Networks.
Method signatures and docstrings:
- def __init__(self, keep_prob, wd, feature_dim): Creates a model for classifying an image using VGG networks. Args: keep_prob: The rate of keeping one neuron in Dropout. wd: The co-effic... | Implement the Python class `MLP` described below.
Class description:
Definition of MLP Networks.
Method signatures and docstrings:
- def __init__(self, keep_prob, wd, feature_dim): Creates a model for classifying an image using VGG networks. Args: keep_prob: The rate of keeping one neuron in Dropout. wd: The co-effic... | dea327aa9e7ef7f7bca5a6c225dbdca1077a06e9 | <|skeleton|>
class MLP:
"""Definition of MLP Networks."""
def __init__(self, keep_prob, wd, feature_dim):
"""Creates a model for classifying an image using VGG networks. Args: keep_prob: The rate of keeping one neuron in Dropout. wd: The co-efficient of weight decay. feature_dim: the dimension of the r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MLP:
"""Definition of MLP Networks."""
def __init__(self, keep_prob, wd, feature_dim):
"""Creates a model for classifying an image using VGG networks. Args: keep_prob: The rate of keeping one neuron in Dropout. wd: The co-efficient of weight decay. feature_dim: the dimension of the representation... | the_stack_v2_python_sparse | dble/mlp.py | Tarkiyah/googleResearch | train | 11 |
c4d1908e51b2e07f5c38c4fdc04fd30a6de237f6 | [
"import random\nself.array = []\nself.total = sum(w)\nprint(w)\nfor i, num in enumerate(w):\n self.array.append(num if i == 0 else self.array[-1] + num)\nprint(self.array)",
"i, j = (0, len(self.array) - 1)\nrand_num = random.randint(1, self.total)\nwhile i <= j:\n mid = (i + j) / 2\n if self.array[mid] ... | <|body_start_0|>
import random
self.array = []
self.total = sum(w)
print(w)
for i, num in enumerate(w):
self.array.append(num if i == 0 else self.array[-1] + num)
print(self.array)
<|end_body_0|>
<|body_start_1|>
i, j = (0, len(self.array) - 1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import random
self.array = []
self.total = sum(w)
print(w)
for i... | stack_v2_sparse_classes_36k_train_031398 | 776 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 801beb43235872b2419a92b11c4eb05f7ea2adab | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
import random
self.array = []
self.total = sum(w)
print(w)
for i, num in enumerate(w):
self.array.append(num if i == 0 else self.array[-1] + num)
print(self.array)
def pickIndex(s... | the_stack_v2_python_sparse | Python/528__Random_Pick_with_Weight.py | FIRESTROM/Leetcode | train | 2 | |
a18b9e34b72348f510e9bac436026852b5e4459b | [
"rev_total = self.score * self.count\nrev_total += review.score\nself.count += 1\nself.score = rev_total / self.count\nself.save()",
"reviews = Review.objects.filter(item=self.item).filter(color=self.color)\ncount = len(reviews)\nagg = sum((review.score for review in reviews))\nself.count = count\nself.score = ag... | <|body_start_0|>
rev_total = self.score * self.count
rev_total += review.score
self.count += 1
self.score = rev_total / self.count
self.save()
<|end_body_0|>
<|body_start_1|>
reviews = Review.objects.filter(item=self.item).filter(color=self.color)
count = len(rev... | ReviewAvg | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewAvg:
def add_review(self, review):
"""Adjust the score and the count based on a review"""
<|body_0|>
def reset_average(self):
"""Totally resets averages by looking at all reviews"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rev_total = self... | stack_v2_sparse_classes_36k_train_031399 | 1,555 | no_license | [
{
"docstring": "Adjust the score and the count based on a review",
"name": "add_review",
"signature": "def add_review(self, review)"
},
{
"docstring": "Totally resets averages by looking at all reviews",
"name": "reset_average",
"signature": "def reset_average(self)"
}
] | 2 | null | Implement the Python class `ReviewAvg` described below.
Class description:
Implement the ReviewAvg class.
Method signatures and docstrings:
- def add_review(self, review): Adjust the score and the count based on a review
- def reset_average(self): Totally resets averages by looking at all reviews | Implement the Python class `ReviewAvg` described below.
Class description:
Implement the ReviewAvg class.
Method signatures and docstrings:
- def add_review(self, review): Adjust the score and the count based on a review
- def reset_average(self): Totally resets averages by looking at all reviews
<|skeleton|>
class ... | 36e08862d1bbcc9a4b535d948199e569ecbdd115 | <|skeleton|>
class ReviewAvg:
def add_review(self, review):
"""Adjust the score and the count based on a review"""
<|body_0|>
def reset_average(self):
"""Totally resets averages by looking at all reviews"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReviewAvg:
def add_review(self, review):
"""Adjust the score and the count based on a review"""
rev_total = self.score * self.count
rev_total += review.score
self.count += 1
self.score = rev_total / self.count
self.save()
def reset_average(self):
""... | the_stack_v2_python_sparse | Assignments/Brea/Django Labs/color_review_base/colors/models.py | PdxCodeGuild/class_mudpuppy | train | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.