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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a7b8fd4e6774328310b57477e1679f2c9ad9b88c | [
"indices = [1, 2, 3]\nK = 2\nresult = k_folds(indices, K)\nexpected = [[2, 3], [1], [3], [1, 2]]\nself.assertEqual(result, expected)",
"indices = [1, 2, 3, 4, 5]\nK = 3\nresult = k_folds(indices, K)\nexpected = [[1, 2], [3, 4, 5], [3, 4], [1, 2, 5], [5], [1, 2, 3, 4]]\nself.assertEqual(result, expected)"
] | <|body_start_0|>
indices = [1, 2, 3]
K = 2
result = k_folds(indices, K)
expected = [[2, 3], [1], [3], [1, 2]]
self.assertEqual(result, expected)
<|end_body_0|>
<|body_start_1|>
indices = [1, 2, 3, 4, 5]
K = 3
result = k_folds(indices, K)
expected ... | Test cases that helped validating the solution. | TestSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSolution:
"""Test cases that helped validating the solution."""
def test_solution_k_2(self):
"""Simple test case K = 2."""
<|body_0|>
def test_solution_k_3(self):
"""Simple test case K = 3."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ind... | stack_v2_sparse_classes_36k_train_026600 | 1,472 | no_license | [
{
"docstring": "Simple test case K = 2.",
"name": "test_solution_k_2",
"signature": "def test_solution_k_2(self)"
},
{
"docstring": "Simple test case K = 3.",
"name": "test_solution_k_3",
"signature": "def test_solution_k_3(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009146 | Implement the Python class `TestSolution` described below.
Class description:
Test cases that helped validating the solution.
Method signatures and docstrings:
- def test_solution_k_2(self): Simple test case K = 2.
- def test_solution_k_3(self): Simple test case K = 3. | Implement the Python class `TestSolution` described below.
Class description:
Test cases that helped validating the solution.
Method signatures and docstrings:
- def test_solution_k_2(self): Simple test case K = 2.
- def test_solution_k_3(self): Simple test case K = 3.
<|skeleton|>
class TestSolution:
"""Test ca... | 712508a79f9620b7b9ab75ef51000efbad387e18 | <|skeleton|>
class TestSolution:
"""Test cases that helped validating the solution."""
def test_solution_k_2(self):
"""Simple test case K = 2."""
<|body_0|>
def test_solution_k_3(self):
"""Simple test case K = 3."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSolution:
"""Test cases that helped validating the solution."""
def test_solution_k_2(self):
"""Simple test case K = 2."""
indices = [1, 2, 3]
K = 2
result = k_folds(indices, K)
expected = [[2, 3], [1], [3], [1, 2]]
self.assertEqual(result, expected)
... | the_stack_v2_python_sparse | code-questions/kfolds.py | fberanizo/mle-interview | train | 1 |
162d0fdc1f6466634341acc039c5baca02ec03f3 | [
"self.prob = prob\nself.flip_axis = flip_axis\nsuper().__init__()",
"if isinstance(self.flip_axis, (tuple, list)):\n flip_axis = self.flip_axis[random.randint(0, len(self.flip_axis) - 1)]\nelse:\n flip_axis = self.flip_axis\nif random.random() < self.prob:\n img = F.flip_3d(img, axis=flip_axis)\n if l... | <|body_start_0|>
self.prob = prob
self.flip_axis = flip_axis
super().__init__()
<|end_body_0|>
<|body_start_1|>
if isinstance(self.flip_axis, (tuple, list)):
flip_axis = self.flip_axis[random.randint(0, len(self.flip_axis) - 1)]
else:
flip_axis = self.fli... | Flip an 4D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1. | RandomFlip4D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomFlip4D:
"""Flip an 4D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1."""
def __init__(self, prob=0.5, flip_axis=[0, 1, 2]):
"""init"""
<|body_0|>
def __call__(self, img, label=None):
"""Args:... | stack_v2_sparse_classes_36k_train_026601 | 34,927 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, prob=0.5, flip_axis=[0, 1, 2])"
},
{
"docstring": "Args: img (numpy ndarray): 4D Image to be flipped. label (numpy ndarray): 4D Label to be flipped. Returns: (np.array). Image after transformation.",
"name": "__call_... | 2 | stack_v2_sparse_classes_30k_train_015426 | Implement the Python class `RandomFlip4D` described below.
Class description:
Flip an 4D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1.
Method signatures and docstrings:
- def __init__(self, prob=0.5, flip_axis=[0, 1, 2]): init
- def __call__(self, im... | Implement the Python class `RandomFlip4D` described below.
Class description:
Flip an 4D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1.
Method signatures and docstrings:
- def __init__(self, prob=0.5, flip_axis=[0, 1, 2]): init
- def __call__(self, im... | 2c8c35a8949fef74599f5ec557d340a14415f20d | <|skeleton|>
class RandomFlip4D:
"""Flip an 4D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1."""
def __init__(self, prob=0.5, flip_axis=[0, 1, 2]):
"""init"""
<|body_0|>
def __call__(self, img, label=None):
"""Args:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomFlip4D:
"""Flip an 4D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1."""
def __init__(self, prob=0.5, flip_axis=[0, 1, 2]):
"""init"""
self.prob = prob
self.flip_axis = flip_axis
super().__init__()
... | the_stack_v2_python_sparse | contrib/MedicalSeg/medicalseg/transforms/transform.py | PaddlePaddle/PaddleSeg | train | 8,531 |
c8df972ee3f6167ef4a1a3ca7633505f33ae8580 | [
"prob_checker(t_prob)\nsuper(RandomInitializer, self).__init__(n_in=0, n_out=1, problem=problem)\nself.t_prob = t_prob\nself.max_depth = max_depth\nself.nonterminal_list = self._get_nonterminal_list()\nself.terminal_list = self._get_terminal_list()",
"def new_node(parent, depth):\n current_node = node.Node()\n... | <|body_start_0|>
prob_checker(t_prob)
super(RandomInitializer, self).__init__(n_in=0, n_out=1, problem=problem)
self.t_prob = t_prob
self.max_depth = max_depth
self.nonterminal_list = self._get_nonterminal_list()
self.terminal_list = self._get_terminal_list()
<|end_body_0... | Generate a new solution. | RandomInitializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomInitializer:
"""Generate a new solution."""
def __init__(self, t_prob, max_depth, problem):
""":param t_prob: float((0, 1]). probability of terminal node. :param max_depth: int. The limit of depth of the solution. :param problem: problem object. problem to solve"""
<|bo... | stack_v2_sparse_classes_36k_train_026602 | 5,247 | permissive | [
{
"docstring": ":param t_prob: float((0, 1]). probability of terminal node. :param max_depth: int. The limit of depth of the solution. :param problem: problem object. problem to solve",
"name": "__init__",
"signature": "def __init__(self, t_prob, max_depth, problem)"
},
{
"docstring": "Generate ... | 2 | stack_v2_sparse_classes_30k_train_004595 | Implement the Python class `RandomInitializer` described below.
Class description:
Generate a new solution.
Method signatures and docstrings:
- def __init__(self, t_prob, max_depth, problem): :param t_prob: float((0, 1]). probability of terminal node. :param max_depth: int. The limit of depth of the solution. :param ... | Implement the Python class `RandomInitializer` described below.
Class description:
Generate a new solution.
Method signatures and docstrings:
- def __init__(self, t_prob, max_depth, problem): :param t_prob: float((0, 1]). probability of terminal node. :param max_depth: int. The limit of depth of the solution. :param ... | 33a2b83bebc61f28449bffa28c87c9013e764ec7 | <|skeleton|>
class RandomInitializer:
"""Generate a new solution."""
def __init__(self, t_prob, max_depth, problem):
""":param t_prob: float((0, 1]). probability of terminal node. :param max_depth: int. The limit of depth of the solution. :param problem: problem object. problem to solve"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomInitializer:
"""Generate a new solution."""
def __init__(self, t_prob, max_depth, problem):
""":param t_prob: float((0, 1]). probability of terminal node. :param max_depth: int. The limit of depth of the solution. :param problem: problem object. problem to solve"""
prob_checker(t_pr... | the_stack_v2_python_sparse | onegpy/operators/initializer.py | hiro-o918/onegpy | train | 0 |
a79ed5614d02ec30f928951661849739a995f75b | [
"test_text = 'Mar#y wa$nted, to swim! However, she was afraid of sharks.'\nexpected_res = [['<s>', 'mary', 'wanted', 'to', 'swim', '</s>'], ['<s>', 'however', 'she', 'was', 'afraid', 'of', 'sharks', '</s>']]\nactual_res = split_by_sentence(test_text)\nself.assertEqual(actual_res, expected_res)",
"test_text = ''\n... | <|body_start_0|>
test_text = 'Mar#y wa$nted, to swim! However, she was afraid of sharks.'
expected_res = [['<s>', 'mary', 'wanted', 'to', 'swim', '</s>'], ['<s>', 'however', 'she', 'was', 'afraid', 'of', 'sharks', '</s>']]
actual_res = split_by_sentence(test_text)
self.assertEqual(actual... | Check splitting by sentences of given text | SplitBySentenceTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplitBySentenceTest:
"""Check splitting by sentences of given text"""
def test_ideal_splitting(self):
"""Ideal case"""
<|body_0|>
def test_empty_text_splitting(self):
"""empty text case"""
<|body_1|>
def test_none_text_splitting(self):
"""non... | stack_v2_sparse_classes_36k_train_026603 | 2,190 | no_license | [
{
"docstring": "Ideal case",
"name": "test_ideal_splitting",
"signature": "def test_ideal_splitting(self)"
},
{
"docstring": "empty text case",
"name": "test_empty_text_splitting",
"signature": "def test_empty_text_splitting(self)"
},
{
"docstring": "none text case",
"name": ... | 6 | stack_v2_sparse_classes_30k_train_014343 | Implement the Python class `SplitBySentenceTest` described below.
Class description:
Check splitting by sentences of given text
Method signatures and docstrings:
- def test_ideal_splitting(self): Ideal case
- def test_empty_text_splitting(self): empty text case
- def test_none_text_splitting(self): none text case
- d... | Implement the Python class `SplitBySentenceTest` described below.
Class description:
Check splitting by sentences of given text
Method signatures and docstrings:
- def test_ideal_splitting(self): Ideal case
- def test_empty_text_splitting(self): empty text case
- def test_none_text_splitting(self): none text case
- d... | b50968194c38b0b9884c134c30c60f01e3b927da | <|skeleton|>
class SplitBySentenceTest:
"""Check splitting by sentences of given text"""
def test_ideal_splitting(self):
"""Ideal case"""
<|body_0|>
def test_empty_text_splitting(self):
"""empty text case"""
<|body_1|>
def test_none_text_splitting(self):
"""non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SplitBySentenceTest:
"""Check splitting by sentences of given text"""
def test_ideal_splitting(self):
"""Ideal case"""
test_text = 'Mar#y wa$nted, to swim! However, she was afraid of sharks.'
expected_res = [['<s>', 'mary', 'wanted', 'to', 'swim', '</s>'], ['<s>', 'however', 'she'... | the_stack_v2_python_sparse | lab_3/split_by_sentence_test.py | KMalika/2018-2-level-labs | train | 1 |
edfdf7c6c38847e7d85bd939238a517409a1fe7f | [
"FeaturewiseDatasetMeasure.__init__(self, **kwargs)\nself.threshold = threshold\nif kernel == None:\n self.kernel = KernelExponential\nelse:\n self.kernel = kernel\nself.w_guess = w_guess\nself.w = None\nself.kernel_width = kernel_width",
"M = {}\nH = {}\nfor i in range(label.size):\n M[i] = N.where(labe... | <|body_start_0|>
FeaturewiseDatasetMeasure.__init__(self, **kwargs)
self.threshold = threshold
if kernel == None:
self.kernel = KernelExponential
else:
self.kernel = kernel
self.w_guess = w_guess
self.w = None
self.kernel_width = kernel_wid... | `FeaturewiseDatasetMeasure` that performs multivariate I-RELIEF algorithm. Batch version allowing various kernels. UNDER DEVELOPEMNT. Batch I-RELIEF-2 feature weighting algorithm. Works for binary or multiclass class-labels. Batch version with complexity O(T*N^2*I), where T is the number of iterations, N the number of ... | IterativeRelief_Devel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IterativeRelief_Devel:
"""`FeaturewiseDatasetMeasure` that performs multivariate I-RELIEF algorithm. Batch version allowing various kernels. UNDER DEVELOPEMNT. Batch I-RELIEF-2 feature weighting algorithm. Works for binary or multiclass class-labels. Batch version with complexity O(T*N^2*I), wher... | stack_v2_sparse_classes_36k_train_026604 | 16,907 | permissive | [
{
"docstring": "Constructor of the IRELIEF class.",
"name": "__init__",
"signature": "def __init__(self, threshold=0.01, kernel=None, kernel_width=1.0, w_guess=None, **kwargs)"
},
{
"docstring": "Compute hit/miss dictionaries. For each instance compute the set of indices having the same class la... | 3 | null | Implement the Python class `IterativeRelief_Devel` described below.
Class description:
`FeaturewiseDatasetMeasure` that performs multivariate I-RELIEF algorithm. Batch version allowing various kernels. UNDER DEVELOPEMNT. Batch I-RELIEF-2 feature weighting algorithm. Works for binary or multiclass class-labels. Batch v... | Implement the Python class `IterativeRelief_Devel` described below.
Class description:
`FeaturewiseDatasetMeasure` that performs multivariate I-RELIEF algorithm. Batch version allowing various kernels. UNDER DEVELOPEMNT. Batch I-RELIEF-2 feature weighting algorithm. Works for binary or multiclass class-labels. Batch v... | 2a8fcaa57457c8994455144e9e69494d167204c4 | <|skeleton|>
class IterativeRelief_Devel:
"""`FeaturewiseDatasetMeasure` that performs multivariate I-RELIEF algorithm. Batch version allowing various kernels. UNDER DEVELOPEMNT. Batch I-RELIEF-2 feature weighting algorithm. Works for binary or multiclass class-labels. Batch version with complexity O(T*N^2*I), wher... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IterativeRelief_Devel:
"""`FeaturewiseDatasetMeasure` that performs multivariate I-RELIEF algorithm. Batch version allowing various kernels. UNDER DEVELOPEMNT. Batch I-RELIEF-2 feature weighting algorithm. Works for binary or multiclass class-labels. Batch version with complexity O(T*N^2*I), where T is the nu... | the_stack_v2_python_sparse | mvpa/measures/irelief.py | gorlins/PyMVPA | train | 0 |
b4e0bf1f4f27cd4638cd77fd5aa0efdf7ace359f | [
"if not s:\n return True\nidx = t.find(s[0])\nt = t[idx:]\nm, n = (len(s), len(t))\ndp = [[False] * (n + 1) for _ in range(m + 1)]\ndp[0][0] = True\nfor i in range(1, m + 1):\n for j in range(1, n + 1):\n dp[i][j] = dp[i - 1][j - 1] or dp[i][j - 1] if s[i - 1] == t[j - 1] else dp[i][j - 1]\nreturn dp[-... | <|body_start_0|>
if not s:
return True
idx = t.find(s[0])
t = t[idx:]
m, n = (len(s), len(t))
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = dp[i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""先找出t中第一个s[0]出现的位置idx t=t[idx:] dp[i][j] 表示s前i个字符和t前j个字符是否匹配 abc ajhbdbc dp[i][j] =dp[i-1_最短回文串.py][j-1_最短回文串.py] or dp[i][j-1_最短回文串.py] if s[i-1_最短回文串.py]==t[j-1_最短回文串.py] =dp[i][j-1_最短回文串.py] dp[0][j] = False dp[i][0] = False... | stack_v2_sparse_classes_36k_train_026605 | 2,070 | no_license | [
{
"docstring": "先找出t中第一个s[0]出现的位置idx t=t[idx:] dp[i][j] 表示s前i个字符和t前j个字符是否匹配 abc ajhbdbc dp[i][j] =dp[i-1_最短回文串.py][j-1_最短回文串.py] or dp[i][j-1_最短回文串.py] if s[i-1_最短回文串.py]==t[j-1_最短回文串.py] =dp[i][j-1_最短回文串.py] dp[0][j] = False dp[i][0] = False dp[0][0] = True res = dp[-1_最短回文串.py][-1_最短回文串.py]",
"name": "isS... | 2 | stack_v2_sparse_classes_30k_train_007939 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s: str, t: str) -> bool: 先找出t中第一个s[0]出现的位置idx t=t[idx:] dp[i][j] 表示s前i个字符和t前j个字符是否匹配 abc ajhbdbc dp[i][j] =dp[i-1_最短回文串.py][j-1_最短回文串.py] or dp[i][j-1_最短回... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s: str, t: str) -> bool: 先找出t中第一个s[0]出现的位置idx t=t[idx:] dp[i][j] 表示s前i个字符和t前j个字符是否匹配 abc ajhbdbc dp[i][j] =dp[i-1_最短回文串.py][j-1_最短回文串.py] or dp[i][j-1_最短回... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""先找出t中第一个s[0]出现的位置idx t=t[idx:] dp[i][j] 表示s前i个字符和t前j个字符是否匹配 abc ajhbdbc dp[i][j] =dp[i-1_最短回文串.py][j-1_最短回文串.py] or dp[i][j-1_最短回文串.py] if s[i-1_最短回文串.py]==t[j-1_最短回文串.py] =dp[i][j-1_最短回文串.py] dp[0][j] = False dp[i][0] = False... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""先找出t中第一个s[0]出现的位置idx t=t[idx:] dp[i][j] 表示s前i个字符和t前j个字符是否匹配 abc ajhbdbc dp[i][j] =dp[i-1_最短回文串.py][j-1_最短回文串.py] or dp[i][j-1_最短回文串.py] if s[i-1_最短回文串.py]==t[j-1_最短回文串.py] =dp[i][j-1_最短回文串.py] dp[0][j] = False dp[i][0] = False dp[0][0] = Tr... | the_stack_v2_python_sparse | 4_LEETCODE/2_DP/字符串匹配问题/392_判断子序列.py | fzingithub/SwordRefers2Offer | train | 1 | |
95bae501300921e9a9ae6df7d07035f8d3031d69 | [
"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.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernor... | <|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.layernorm1 = tf.keras.... | create an encoder block for a transformer | DecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""create an encoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Class constructor"""
<|body_0|>
def call(self, x, encoder_output, training, look_ahead_mask, padding_mask):
"""Public instance method"""
<|b... | stack_v2_sparse_classes_36k_train_026606 | 2,127 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "Public instance method",
"name": "call",
"signature": "def call(self, x, encoder_output, training, look_ahead_mask, padding_mask)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021529 | Implement the Python class `DecoderBlock` described below.
Class description:
create an encoder block for a transformer
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): Class constructor
- def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): Public instance ... | Implement the Python class `DecoderBlock` described below.
Class description:
create an encoder block for a transformer
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): Class constructor
- def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): Public instance ... | c23deee331a71a089197547fcae4c1eefb8d24ef | <|skeleton|>
class DecoderBlock:
"""create an encoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Class constructor"""
<|body_0|>
def call(self, x, encoder_output, training, look_ahead_mask, padding_mask):
"""Public instance method"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderBlock:
"""create an encoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Class constructor"""
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidde... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/8-transformer_decoder_block.py | YosriGFX/holbertonschool-machine_learning | train | 0 |
bc6752bec93dd843ac212014583c02debf03f8bb | [
"super(STConvBlock, self).__init__()\nf_in, f_m, f_out = channels\nself.t_conv1 = TemporalConvLayer(f_in, f_m, t_cnv_krnl_sz)\nself.s_conv = SpatialConvLayer(f_m, f_m, k_hop)\nself.t_conv2 = TemporalConvLayer(f_m, f_out, t_cnv_krnl_sz)\nself.ln = nn.LayerNorm([n_node, f_out])\nself.dropout = nn.Dropout(dropout)",
... | <|body_start_0|>
super(STConvBlock, self).__init__()
f_in, f_m, f_out = channels
self.t_conv1 = TemporalConvLayer(f_in, f_m, t_cnv_krnl_sz)
self.s_conv = SpatialConvLayer(f_m, f_m, k_hop)
self.t_conv2 = TemporalConvLayer(f_m, f_out, t_cnv_krnl_sz)
self.ln = nn.LayerNorm([... | STConvBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class STConvBlock:
def __init__(self, k_hop: int, t_cnv_krnl_sz: int, n_node: int, channels: Tuple[int, int, int], dropout: float):
"""Spatio-temporal convolutional block, which contains two temporal gated convolution layers and one spatial graph convolution layer in the middle. :param k_hop: ... | stack_v2_sparse_classes_36k_train_026607 | 5,900 | no_license | [
{
"docstring": "Spatio-temporal convolutional block, which contains two temporal gated convolution layers and one spatial graph convolution layer in the middle. :param k_hop: length of Chebychev polynomial, i.e., kernel size of spatial convolution :param t_cnv_krnl_sz: kernel size of temporal convolution :param... | 2 | stack_v2_sparse_classes_30k_train_017970 | Implement the Python class `STConvBlock` described below.
Class description:
Implement the STConvBlock class.
Method signatures and docstrings:
- def __init__(self, k_hop: int, t_cnv_krnl_sz: int, n_node: int, channels: Tuple[int, int, int], dropout: float): Spatio-temporal convolutional block, which contains two tem... | Implement the Python class `STConvBlock` described below.
Class description:
Implement the STConvBlock class.
Method signatures and docstrings:
- def __init__(self, k_hop: int, t_cnv_krnl_sz: int, n_node: int, channels: Tuple[int, int, int], dropout: float): Spatio-temporal convolutional block, which contains two tem... | 4a9da6eedab6ef3d72492b9445d7a9923abc9833 | <|skeleton|>
class STConvBlock:
def __init__(self, k_hop: int, t_cnv_krnl_sz: int, n_node: int, channels: Tuple[int, int, int], dropout: float):
"""Spatio-temporal convolutional block, which contains two temporal gated convolution layers and one spatial graph convolution layer in the middle. :param k_hop: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class STConvBlock:
def __init__(self, k_hop: int, t_cnv_krnl_sz: int, n_node: int, channels: Tuple[int, int, int], dropout: float):
"""Spatio-temporal convolutional block, which contains two temporal gated convolution layers and one spatial graph convolution layer in the middle. :param k_hop: length of Cheb... | the_stack_v2_python_sparse | networks/stgcn.py | WfcCross/traffic-prediction | train | 0 | |
b8585b0067b376718c5c548295f84fb7a151a61a | [
"self.match_indicator = match_indicator\nself.title = title\nself.function = function\nself.comment = comment\nself.alias_list = alias_list\nself.address_list = address_list\nself.url_list = url_list\nself.provider = provider\nself.source = source\nself.external_id = external_id\nself.last_update = APIHelper.RFC333... | <|body_start_0|>
self.match_indicator = match_indicator
self.title = title
self.function = function
self.comment = comment
self.alias_list = alias_list
self.address_list = address_list
self.url_list = url_list
self.provider = provider
self.source =... | Implementation of the 'SanctionResult' model. List of all Sanction items with match for the input request. Attributes: match_indicator (int): Quality indicator of match. Higher number means better match. title (string): May be a text string denoting title of position, job title, etc function (string): Additional detail... | SanctionResult | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SanctionResult:
"""Implementation of the 'SanctionResult' model. List of all Sanction items with match for the input request. Attributes: match_indicator (int): Quality indicator of match. Higher number means better match. title (string): May be a text string denoting title of position, job title... | stack_v2_sparse_classes_36k_train_026608 | 6,637 | permissive | [
{
"docstring": "Constructor for the SanctionResult class",
"name": "__init__",
"signature": "def __init__(self, match_indicator=None, title=None, function=None, comment=None, alias_list=None, address_list=None, url_list=None, provider=None, source=None, external_id=None, last_update=None, first_update=N... | 2 | null | Implement the Python class `SanctionResult` described below.
Class description:
Implementation of the 'SanctionResult' model. List of all Sanction items with match for the input request. Attributes: match_indicator (int): Quality indicator of match. Higher number means better match. title (string): May be a text strin... | Implement the Python class `SanctionResult` described below.
Class description:
Implementation of the 'SanctionResult' model. List of all Sanction items with match for the input request. Attributes: match_indicator (int): Quality indicator of match. Higher number means better match. title (string): May be a text strin... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class SanctionResult:
"""Implementation of the 'SanctionResult' model. List of all Sanction items with match for the input request. Attributes: match_indicator (int): Quality indicator of match. Higher number means better match. title (string): May be a text string denoting title of position, job title... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SanctionResult:
"""Implementation of the 'SanctionResult' model. List of all Sanction items with match for the input request. Attributes: match_indicator (int): Quality indicator of match. Higher number means better match. title (string): May be a text string denoting title of position, job title, etc functio... | the_stack_v2_python_sparse | idfy_rest_client/models/sanction_result.py | dealflowteam/Idfy | train | 0 |
f8e56dcab782df4e870963fd31b2fc66de2f498c | [
"assert reason if should_skip else True, 'Condition that should be skipped, should have a reason.'\nself.should_skip = should_skip\nself.reason = reason\nself.conflicting_packs = conflicting_packs\nself.pack_new_rn_file = pack_new_rn_file\nself.pr_rn_version = pr_rn_version\nself.update_type = update_type",
"shou... | <|body_start_0|>
assert reason if should_skip else True, 'Condition that should be skipped, should have a reason.'
self.should_skip = should_skip
self.reason = reason
self.conflicting_packs = conflicting_packs
self.pack_new_rn_file = pack_new_rn_file
self.pr_rn_version = ... | Result artifacts of the condition that was checked | ConditionResult | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionResult:
"""Result artifacts of the condition that was checked"""
def __init__(self, should_skip: bool, reason: Optional[str]='', conflicting_packs: Optional[Set]=None, pack_new_rn_file: Path=None, pr_rn_version: Version=None, update_type: UpdateType=None):
"""Args: should_sk... | stack_v2_sparse_classes_36k_train_026609 | 29,534 | permissive | [
{
"docstring": "Args: should_skip(bool): Whether to stop the checks. reason(SkipReason): Why to skip this condition. conflicting_packs(set): Result artifact: Packs that has conflicts with base branch. pack_new_rn_file(Path): Result artifact: Path to pack's new release notes. pr_rn_version(Version): Result artif... | 2 | null | Implement the Python class `ConditionResult` described below.
Class description:
Result artifacts of the condition that was checked
Method signatures and docstrings:
- def __init__(self, should_skip: bool, reason: Optional[str]='', conflicting_packs: Optional[Set]=None, pack_new_rn_file: Path=None, pr_rn_version: Ver... | Implement the Python class `ConditionResult` described below.
Class description:
Result artifacts of the condition that was checked
Method signatures and docstrings:
- def __init__(self, should_skip: bool, reason: Optional[str]='', conflicting_packs: Optional[Set]=None, pack_new_rn_file: Path=None, pr_rn_version: Ver... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class ConditionResult:
"""Result artifacts of the condition that was checked"""
def __init__(self, should_skip: bool, reason: Optional[str]='', conflicting_packs: Optional[Set]=None, pack_new_rn_file: Path=None, pr_rn_version: Version=None, update_type: UpdateType=None):
"""Args: should_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionResult:
"""Result artifacts of the condition that was checked"""
def __init__(self, should_skip: bool, reason: Optional[str]='', conflicting_packs: Optional[Set]=None, pack_new_rn_file: Path=None, pr_rn_version: Version=None, update_type: UpdateType=None):
"""Args: should_skip(bool): Whe... | the_stack_v2_python_sparse | Utils/github_workflow_scripts/autobump_release_notes/skip_conditions.py | demisto/content | train | 1,023 |
9aac3f9e15d04d21001cfcf25b61b9058b719cee | [
"super().__init__()\nself.WRD_EMB_DIM = WRD_EMB_DIM\nself.ENC_DIM = ENC_DIM\nself.bilstm = torch.nn.LSTM(input_size=self.WRD_EMB_DIM, hidden_size=self.ENC_DIM // 2, num_layers=1, batch_first=True, bidirectional=True)\nd = self.ENC_DIM // 2\nfan_avg = (d * 4 + (d + self.WRD_EMB_DIM)) / 2.0\nbound = np.sqrt(3.0 / fan... | <|body_start_0|>
super().__init__()
self.WRD_EMB_DIM = WRD_EMB_DIM
self.ENC_DIM = ENC_DIM
self.bilstm = torch.nn.LSTM(input_size=self.WRD_EMB_DIM, hidden_size=self.ENC_DIM // 2, num_layers=1, batch_first=True, bidirectional=True)
d = self.ENC_DIM // 2
fan_avg = (d * 4 + (... | BiLSTM | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiLSTM:
def __init__(self, WRD_EMB_DIM: int, ENC_DIM: int, forget_gate_bias: float=1.0) -> None:
"""Initialization of BiLSTM. Args: WRD_EMB_DIM: the word embedding dimension ENC_DIM: the dimension of the encoder for BiLSTM, which is twice of the hidden state dimension forget_gate_bias:(o... | stack_v2_sparse_classes_36k_train_026610 | 5,915 | permissive | [
{
"docstring": "Initialization of BiLSTM. Args: WRD_EMB_DIM: the word embedding dimension ENC_DIM: the dimension of the encoder for BiLSTM, which is twice of the hidden state dimension forget_gate_bias:(optional):the initialization of the forget-gate bias",
"name": "__init__",
"signature": "def __init__... | 2 | null | Implement the Python class `BiLSTM` described below.
Class description:
Implement the BiLSTM class.
Method signatures and docstrings:
- def __init__(self, WRD_EMB_DIM: int, ENC_DIM: int, forget_gate_bias: float=1.0) -> None: Initialization of BiLSTM. Args: WRD_EMB_DIM: the word embedding dimension ENC_DIM: the dimens... | Implement the Python class `BiLSTM` described below.
Class description:
Implement the BiLSTM class.
Method signatures and docstrings:
- def __init__(self, WRD_EMB_DIM: int, ENC_DIM: int, forget_gate_bias: float=1.0) -> None: Initialization of BiLSTM. Args: WRD_EMB_DIM: the word embedding dimension ENC_DIM: the dimens... | af87a17275f02c94932bb2e29f132a84db812002 | <|skeleton|>
class BiLSTM:
def __init__(self, WRD_EMB_DIM: int, ENC_DIM: int, forget_gate_bias: float=1.0) -> None:
"""Initialization of BiLSTM. Args: WRD_EMB_DIM: the word embedding dimension ENC_DIM: the dimension of the encoder for BiLSTM, which is twice of the hidden state dimension forget_gate_bias:(o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BiLSTM:
def __init__(self, WRD_EMB_DIM: int, ENC_DIM: int, forget_gate_bias: float=1.0) -> None:
"""Initialization of BiLSTM. Args: WRD_EMB_DIM: the word embedding dimension ENC_DIM: the dimension of the encoder for BiLSTM, which is twice of the hidden state dimension forget_gate_bias:(optional):the i... | the_stack_v2_python_sparse | imix/models/encoder/lcgnencoder.py | linxi1158/iMIX | train | 0 | |
dc6ca4fb9e8460f6f5626474b85857feac1b8340 | [
"try:\n User.objects.get(username=value)\n raise serializers.ValidationError('Email Already In Use')\nexcept User.DoesNotExist:\n pass\nreturn value",
"if not self.context.get('request').organization:\n raise serializers.ValidationError(detail='Cannot create invites without an organization')\nattrs['o... | <|body_start_0|>
try:
User.objects.get(username=value)
raise serializers.ValidationError('Email Already In Use')
except User.DoesNotExist:
pass
return value
<|end_body_0|>
<|body_start_1|>
if not self.context.get('request').organization:
r... | OrganizationInviteSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationInviteSerializer:
def validate_username(self, value):
"""Check if email is currently in use :return:"""
<|body_0|>
def validate(self, attrs):
"""We don't allow the frontend to dictate the invite's organization. :param attrs: :return:"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_026611 | 2,944 | no_license | [
{
"docstring": "Check if email is currently in use :return:",
"name": "validate_username",
"signature": "def validate_username(self, value)"
},
{
"docstring": "We don't allow the frontend to dictate the invite's organization. :param attrs: :return:",
"name": "validate",
"signature": "def... | 2 | null | Implement the Python class `OrganizationInviteSerializer` described below.
Class description:
Implement the OrganizationInviteSerializer class.
Method signatures and docstrings:
- def validate_username(self, value): Check if email is currently in use :return:
- def validate(self, attrs): We don't allow the frontend t... | Implement the Python class `OrganizationInviteSerializer` described below.
Class description:
Implement the OrganizationInviteSerializer class.
Method signatures and docstrings:
- def validate_username(self, value): Check if email is currently in use :return:
- def validate(self, attrs): We don't allow the frontend t... | 604a5c5d933815ab4b51b3f24b1cbd0b71c18133 | <|skeleton|>
class OrganizationInviteSerializer:
def validate_username(self, value):
"""Check if email is currently in use :return:"""
<|body_0|>
def validate(self, attrs):
"""We don't allow the frontend to dictate the invite's organization. :param attrs: :return:"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrganizationInviteSerializer:
def validate_username(self, value):
"""Check if email is currently in use :return:"""
try:
User.objects.get(username=value)
raise serializers.ValidationError('Email Already In Use')
except User.DoesNotExist:
pass
... | the_stack_v2_python_sparse | capitolzen/organizations/api/app/serializers.py | CapitolZen/CapitolZen-Backend | train | 0 | |
fad122f85e9dd22a456ec50e7b0ac3ca091d6ae2 | [
"if matrix is None or not matrix:\n return\nrows = len(matrix)\ncolumns = len(matrix[0])\nself.dp = [[0 for _ in range(columns)] for _ in range(rows)]\nself.dp[0][0] = matrix[0][0]\nfor _column in range(1, columns):\n self.dp[0][_column] = self.dp[0][_column - 1] + matrix[0][_column]\nfor _row in range(1, row... | <|body_start_0|>
if matrix is None or not matrix:
return
rows = len(matrix)
columns = len(matrix[0])
self.dp = [[0 for _ in range(columns)] for _ in range(rows)]
self.dp[0][0] = matrix[0][0]
for _column in range(1, columns):
self.dp[0][_column] = s... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_026612 | 4,418 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_015212 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 5f98270fbcd2d28d0f2abd344c3348255a12882a | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
if matrix is None or not matrix:
return
rows = len(matrix)
columns = len(matrix[0])
self.dp = [[0 for _ in range(columns)] for _ in range(rows)]
self.dp[0][0] = matrix[0][0]
... | the_stack_v2_python_sparse | 304. Range Sum Query 2D - Immutable.py | lxyshuai/leetcode | train | 0 | |
1f37a2580fc6594e1fa21204155b3f9a5671d676 | [
"self.backup_script = backup_script\nself.full_backup_script = full_backup_script\nself.log_backup_script = log_backup_script\nself.remote_host_params = remote_host_params",
"if dictionary is None:\n return None\nbackup_script = cohesity_management_sdk.models.script_path_and_params.ScriptPathAndParams.from_dic... | <|body_start_0|>
self.backup_script = backup_script
self.full_backup_script = full_backup_script
self.log_backup_script = log_backup_script
self.remote_host_params = remote_host_params
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
backup_... | Implementation of the 'BackupJobPreOrPostScript' model. A message to encapsulate the pre and post scripts associated with a backup job. Pre script is executed before backup run of a job starts. Post script is executed after backup run of a job finishes. Currently, pre and post script is only supported for backup job of... | BackupJobPreOrPostScript | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackupJobPreOrPostScript:
"""Implementation of the 'BackupJobPreOrPostScript' model. A message to encapsulate the pre and post scripts associated with a backup job. Pre script is executed before backup run of a job starts. Post script is executed after backup run of a job finishes. Currently, pre... | stack_v2_sparse_classes_36k_train_026613 | 4,033 | permissive | [
{
"docstring": "Constructor for the BackupJobPreOrPostScript class",
"name": "__init__",
"signature": "def __init__(self, backup_script=None, full_backup_script=None, log_backup_script=None, remote_host_params=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: di... | 2 | null | Implement the Python class `BackupJobPreOrPostScript` described below.
Class description:
Implementation of the 'BackupJobPreOrPostScript' model. A message to encapsulate the pre and post scripts associated with a backup job. Pre script is executed before backup run of a job starts. Post script is executed after backu... | Implement the Python class `BackupJobPreOrPostScript` described below.
Class description:
Implementation of the 'BackupJobPreOrPostScript' model. A message to encapsulate the pre and post scripts associated with a backup job. Pre script is executed before backup run of a job starts. Post script is executed after backu... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class BackupJobPreOrPostScript:
"""Implementation of the 'BackupJobPreOrPostScript' model. A message to encapsulate the pre and post scripts associated with a backup job. Pre script is executed before backup run of a job starts. Post script is executed after backup run of a job finishes. Currently, pre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BackupJobPreOrPostScript:
"""Implementation of the 'BackupJobPreOrPostScript' model. A message to encapsulate the pre and post scripts associated with a backup job. Pre script is executed before backup run of a job starts. Post script is executed after backup run of a job finishes. Currently, pre and post scr... | the_stack_v2_python_sparse | cohesity_management_sdk/models/backup_job_pre_or_post_script.py | cohesity/management-sdk-python | train | 24 |
ab055e3c903c0a1c51ea4e8407d5df8c4b964dc7 | [
"try:\n http_method = self._resolve_method(request)\n http_headers = self._convert_list_tuples_to_dict(headers_list=request.headers)\n parsed_url = parse_url(request.url)\n if parsed_url.scheme is None or parsed_url.scheme != 'https':\n raise ApiClientException('Requests against non-HTTPS endpoin... | <|body_start_0|>
try:
http_method = self._resolve_method(request)
http_headers = self._convert_list_tuples_to_dict(headers_list=request.headers)
parsed_url = parse_url(request.url)
if parsed_url.scheme is None or parsed_url.scheme != 'https':
raise... | Default ApiClient implementation of :py:class:`ask_sdk_model.services.api_client.ApiClient` using the `requests` library. | DefaultApiClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultApiClient:
"""Default ApiClient implementation of :py:class:`ask_sdk_model.services.api_client.ApiClient` using the `requests` library."""
def invoke(self, request):
"""Dispatches a request to an API endpoint described in the request. Resolves the method from input request obj... | stack_v2_sparse_classes_36k_train_026614 | 6,077 | permissive | [
{
"docstring": "Dispatches a request to an API endpoint described in the request. Resolves the method from input request object, converts the list of header tuples to the required format (dict) for the `requests` lib call and invokes the method with corresponding parameters on `requests` library. The response f... | 4 | stack_v2_sparse_classes_30k_val_000275 | Implement the Python class `DefaultApiClient` described below.
Class description:
Default ApiClient implementation of :py:class:`ask_sdk_model.services.api_client.ApiClient` using the `requests` library.
Method signatures and docstrings:
- def invoke(self, request): Dispatches a request to an API endpoint described i... | Implement the Python class `DefaultApiClient` described below.
Class description:
Default ApiClient implementation of :py:class:`ask_sdk_model.services.api_client.ApiClient` using the `requests` library.
Method signatures and docstrings:
- def invoke(self, request): Dispatches a request to an API endpoint described i... | 7e13ca69b240985584dff6ec633a27598a154ca1 | <|skeleton|>
class DefaultApiClient:
"""Default ApiClient implementation of :py:class:`ask_sdk_model.services.api_client.ApiClient` using the `requests` library."""
def invoke(self, request):
"""Dispatches a request to an API endpoint described in the request. Resolves the method from input request obj... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefaultApiClient:
"""Default ApiClient implementation of :py:class:`ask_sdk_model.services.api_client.ApiClient` using the `requests` library."""
def invoke(self, request):
"""Dispatches a request to an API endpoint described in the request. Resolves the method from input request object, converts... | the_stack_v2_python_sparse | ask-sdk-core/ask_sdk_core/api_client.py | alexa/alexa-skills-kit-sdk-for-python | train | 560 |
63bb73a8defaccea5b30bc05794977232b553b6a | [
"if self.search is None:\n return\nself.view.set_viewport_position(self.viewport)\nself.search.reset()\nmatches = self.search.find(text, self.autocorrect)\nself.search.add_matches(matches)\nrelevant_matches = self.search.forwards(update_cursors=False, viewport=self.visible_region, next_only=self.jump_only)\nif s... | <|body_start_0|>
if self.search is None:
return
self.view.set_viewport_position(self.viewport)
self.search.reset()
matches = self.search.find(text, self.autocorrect)
self.search.add_matches(matches)
relevant_matches = self.search.forwards(update_cursors=False,... | Creates the Search Input Panel VisualMode: This would stretch each cursor to the matched word Doesn't perform highlighting MultiSelect: This shows only the relevant words (ones cursors could go to) Doesn't perform highlighting = args append: reset highlights first? or add to them jump_only: doesn't mess with highlighti... | HighlightPanelCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HighlightPanelCommand:
"""Creates the Search Input Panel VisualMode: This would stretch each cursor to the matched word Doesn't perform highlighting MultiSelect: This shows only the relevant words (ones cursors could go to) Doesn't perform highlighting = args append: reset highlights first? or ad... | stack_v2_sparse_classes_36k_train_026615 | 31,297 | permissive | [
{
"docstring": "Event: User typing",
"name": "_on_change",
"signature": "def _on_change(self, text)"
},
{
"docstring": "Event: user Input",
"name": "_on_done",
"signature": "def _on_done(self, text)"
},
{
"docstring": "Event: user abort",
"name": "_on_cancel",
"signature"... | 4 | stack_v2_sparse_classes_30k_train_010718 | Implement the Python class `HighlightPanelCommand` described below.
Class description:
Creates the Search Input Panel VisualMode: This would stretch each cursor to the matched word Doesn't perform highlighting MultiSelect: This shows only the relevant words (ones cursors could go to) Doesn't perform highlighting = arg... | Implement the Python class `HighlightPanelCommand` described below.
Class description:
Creates the Search Input Panel VisualMode: This would stretch each cursor to the matched word Doesn't perform highlighting MultiSelect: This shows only the relevant words (ones cursors could go to) Doesn't perform highlighting = arg... | 91417d02554b89cd322d16940f59d0dd781c8001 | <|skeleton|>
class HighlightPanelCommand:
"""Creates the Search Input Panel VisualMode: This would stretch each cursor to the matched word Doesn't perform highlighting MultiSelect: This shows only the relevant words (ones cursors could go to) Doesn't perform highlighting = args append: reset highlights first? or ad... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HighlightPanelCommand:
"""Creates the Search Input Panel VisualMode: This would stretch each cursor to the matched word Doesn't perform highlighting MultiSelect: This shows only the relevant words (ones cursors could go to) Doesn't perform highlighting = args append: reset highlights first? or add to them jum... | the_stack_v2_python_sparse | highlight.py | Saevon/config-sublime | train | 0 |
44e699bf7cf2d1615e6615bb2de0252db460a5bf | [
"tree_string = '(((a:0.05, b:0.05):0.15, c:0.2):0.8, x:1.0, (((m:0.05, n:0.05):0.15, p:0.2):0.8, y:1.0):1.0);'\ntree = NewickIO.parse(tree_string, FelTree.NewickTree)\nordered_names = list((node.name for node in tree.gen_tips()))\nsequence_length = 10\nsampler = DMSampler(tree, ordered_names, sequence_length)\nresu... | <|body_start_0|>
tree_string = '(((a:0.05, b:0.05):0.15, c:0.2):0.8, x:1.0, (((m:0.05, n:0.05):0.15, p:0.2):0.8, y:1.0):1.0);'
tree = NewickIO.parse(tree_string, FelTree.NewickTree)
ordered_names = list((node.name for node in tree.gen_tips()))
sequence_length = 10
sampler = DMSam... | TestDMSampler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDMSampler:
def test_finite_sequence_length(self):
"""Run the distance matrix sampler using a finite sequence length."""
<|body_0|>
def test_modify(self):
"""Run the distance matrix sampler, modifying extreme distance estimates."""
<|body_1|>
def test... | stack_v2_sparse_classes_36k_train_026616 | 14,737 | no_license | [
{
"docstring": "Run the distance matrix sampler using a finite sequence length.",
"name": "test_finite_sequence_length",
"signature": "def test_finite_sequence_length(self)"
},
{
"docstring": "Run the distance matrix sampler, modifying extreme distance estimates.",
"name": "test_modify",
... | 4 | null | Implement the Python class `TestDMSampler` described below.
Class description:
Implement the TestDMSampler class.
Method signatures and docstrings:
- def test_finite_sequence_length(self): Run the distance matrix sampler using a finite sequence length.
- def test_modify(self): Run the distance matrix sampler, modifyi... | Implement the Python class `TestDMSampler` described below.
Class description:
Implement the TestDMSampler class.
Method signatures and docstrings:
- def test_finite_sequence_length(self): Run the distance matrix sampler using a finite sequence length.
- def test_modify(self): Run the distance matrix sampler, modifyi... | 91c6f8331f18c914eb3dfc51bc166915998c5081 | <|skeleton|>
class TestDMSampler:
def test_finite_sequence_length(self):
"""Run the distance matrix sampler using a finite sequence length."""
<|body_0|>
def test_modify(self):
"""Run the distance matrix sampler, modifying extreme distance estimates."""
<|body_1|>
def test... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDMSampler:
def test_finite_sequence_length(self):
"""Run the distance matrix sampler using a finite sequence length."""
tree_string = '(((a:0.05, b:0.05):0.15, c:0.2):0.8, x:1.0, (((m:0.05, n:0.05):0.15, p:0.2):0.8, y:1.0):1.0);'
tree = NewickIO.parse(tree_string, FelTree.NewickTre... | the_stack_v2_python_sparse | DMSampler.py | argriffing/xgcode | train | 1 | |
c5afd837def6a6ec93ab77a5746a49b3d3ffd86d | [
"assert padding in ['SAME'], 'Error: unsupported padding for transposed conv'\nif isinstance(stride, int):\n stride = [1, stride, stride, 1]\nelse:\n assert len(stride) == 2, 'stride is either an int or a 2-tuple'\n stride = [1, stride[0], stride[1], 1]\nif isinstance(w, int):\n w = [w, w]\nself.padding... | <|body_start_0|>
assert padding in ['SAME'], 'Error: unsupported padding for transposed conv'
if isinstance(stride, int):
stride = [1, stride, stride, 1]
else:
assert len(stride) == 2, 'stride is either an int or a 2-tuple'
stride = [1, stride[0], stride[1], 1... | Convolution layer with support for equalized learning. | LayerTransposedConv | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerTransposedConv:
"""Convolution layer with support for equalized learning."""
def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.0):
"""Layer constructor. Args: name: string, layer name. stride: int or 2-tuple, stride for the convolution kernel... | stack_v2_sparse_classes_36k_train_026617 | 13,442 | permissive | [
{
"docstring": "Layer constructor. Args: name: string, layer name. stride: int or 2-tuple, stride for the convolution kernel. w: int or 2-tuple, width of the convolution kernel. n: 2-tuple int, [n_in_channels, n_out_channels] padding: string, the padding method {SAME, VALID, REFLECT}. use_scaling: bool, whether... | 2 | stack_v2_sparse_classes_30k_test_000341 | Implement the Python class `LayerTransposedConv` described below.
Class description:
Convolution layer with support for equalized learning.
Method signatures and docstrings:
- def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.0): Layer constructor. Args: name: string, layer name. ... | Implement the Python class `LayerTransposedConv` described below.
Class description:
Convolution layer with support for equalized learning.
Method signatures and docstrings:
- def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.0): Layer constructor. Args: name: string, layer name. ... | 091d6ae9e087cf5a6e18b00bce7d8f7ede9d9d08 | <|skeleton|>
class LayerTransposedConv:
"""Convolution layer with support for equalized learning."""
def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.0):
"""Layer constructor. Args: name: string, layer name. stride: int or 2-tuple, stride for the convolution kernel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LayerTransposedConv:
"""Convolution layer with support for equalized learning."""
def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.0):
"""Layer constructor. Args: name: string, layer name. stride: int or 2-tuple, stride for the convolution kernel. w: int or 2... | the_stack_v2_python_sparse | layers.py | MoustafaMeshry/StEP | train | 6 |
82589894bc21b5b625f212a845d33d0848d905da | [
"first_class = m_obj.__class__\nsubclass_ls = first_class.__subclasses__()\nif subclass_ls:\n for subcls in subclass_ls:\n try:\n m_obj = subcls(ls_entries)\n except MatrixError:\n pass\nif first_class == m_obj.__class__:\n return m_obj\nelse:\n return self.get_matrix_cl... | <|body_start_0|>
first_class = m_obj.__class__
subclass_ls = first_class.__subclasses__()
if subclass_ls:
for subcls in subclass_ls:
try:
m_obj = subcls(ls_entries)
except MatrixError:
pass
if first_class... | MatrixFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatrixFactory:
def get_matrix_class(self, m_obj, ls_entries):
"""recursively loop through the subclasses to get the most relevant type"""
<|body_0|>
def __call__(self, ls_entries=None):
"""Returns the most relevant matrix type that exists."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_026618 | 992 | no_license | [
{
"docstring": "recursively loop through the subclasses to get the most relevant type",
"name": "get_matrix_class",
"signature": "def get_matrix_class(self, m_obj, ls_entries)"
},
{
"docstring": "Returns the most relevant matrix type that exists.",
"name": "__call__",
"signature": "def _... | 2 | stack_v2_sparse_classes_30k_train_003757 | Implement the Python class `MatrixFactory` described below.
Class description:
Implement the MatrixFactory class.
Method signatures and docstrings:
- def get_matrix_class(self, m_obj, ls_entries): recursively loop through the subclasses to get the most relevant type
- def __call__(self, ls_entries=None): Returns the ... | Implement the Python class `MatrixFactory` described below.
Class description:
Implement the MatrixFactory class.
Method signatures and docstrings:
- def get_matrix_class(self, m_obj, ls_entries): recursively loop through the subclasses to get the most relevant type
- def __call__(self, ls_entries=None): Returns the ... | 339567a672e12ebc4847dfd97e9d1a2a7d45f655 | <|skeleton|>
class MatrixFactory:
def get_matrix_class(self, m_obj, ls_entries):
"""recursively loop through the subclasses to get the most relevant type"""
<|body_0|>
def __call__(self, ls_entries=None):
"""Returns the most relevant matrix type that exists."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MatrixFactory:
def get_matrix_class(self, m_obj, ls_entries):
"""recursively loop through the subclasses to get the most relevant type"""
first_class = m_obj.__class__
subclass_ls = first_class.__subclasses__()
if subclass_ls:
for subcls in subclass_ls:
... | the_stack_v2_python_sparse | matrix/choose_matrix_type.py | KerimovEmil/HigherMathInvestigations | train | 2 | |
becf8d30099996c7a411b84b24305189cced5ec9 | [
"bin_data = []\nfor i in data:\n bin_data.append('{0:0>8}'.format(bin(i)[2:]))\nprint(bin_data)\nl = len(data)\nif l <= 0:\n return False\ncount = 0\nwhile count < l:\n if bin_data[count][0] == '0':\n count += 1\n else:\n count_bin = 0\n while count_bin < 8 and bin_data[count][count... | <|body_start_0|>
bin_data = []
for i in data:
bin_data.append('{0:0>8}'.format(bin(i)[2:]))
print(bin_data)
l = len(data)
if l <= 0:
return False
count = 0
while count < l:
if bin_data[count][0] == '0':
count += ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validUtf8(self, data):
""":type data: List[int] :rtype: bool 85ms"""
<|body_0|>
def validUtf8_1(self, data):
""":type data: List[int] :rtype: bool 42ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
bin_data = []
for i in data... | stack_v2_sparse_classes_36k_train_026619 | 3,271 | no_license | [
{
"docstring": ":type data: List[int] :rtype: bool 85ms",
"name": "validUtf8",
"signature": "def validUtf8(self, data)"
},
{
"docstring": ":type data: List[int] :rtype: bool 42ms",
"name": "validUtf8_1",
"signature": "def validUtf8_1(self, data)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validUtf8(self, data): :type data: List[int] :rtype: bool 85ms
- def validUtf8_1(self, data): :type data: List[int] :rtype: bool 42ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validUtf8(self, data): :type data: List[int] :rtype: bool 85ms
- def validUtf8_1(self, data): :type data: List[int] :rtype: bool 42ms
<|skeleton|>
class Solution:
def v... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def validUtf8(self, data):
""":type data: List[int] :rtype: bool 85ms"""
<|body_0|>
def validUtf8_1(self, data):
""":type data: List[int] :rtype: bool 42ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validUtf8(self, data):
""":type data: List[int] :rtype: bool 85ms"""
bin_data = []
for i in data:
bin_data.append('{0:0>8}'.format(bin(i)[2:]))
print(bin_data)
l = len(data)
if l <= 0:
return False
count = 0
... | the_stack_v2_python_sparse | UTF8Validation_MID_393.py | 953250587/leetcode-python | train | 2 | |
98a07a9309a5ca6b46c287f31e80e3c4adf35aa4 | [
"_sync_couch()\ntable_names = _get_all_table_names()\nnum_tables = len(table_names)\nlogger.info('Start adding inserted_at column to %s existing UCR datasource tables', num_tables)\nfor table_name in table_names:\n try:\n logger.info('Adding inserted_at column to %s', table_name)\n db.start_transac... | <|body_start_0|>
_sync_couch()
table_names = _get_all_table_names()
num_tables = len(table_names)
logger.info('Start adding inserted_at column to %s existing UCR datasource tables', num_tables)
for table_name in table_names:
try:
logger.info('Adding in... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Adds an 'inserted_at' column to each existing data source table"""
<|body_0|>
def backwards(self, orm):
"""Removes 'inserted_at' column from each data source table"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_026620 | 1,943 | no_license | [
{
"docstring": "Adds an 'inserted_at' column to each existing data source table",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Removes 'inserted_at' column from each data source table",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000351 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Adds an 'inserted_at' column to each existing data source table
- def backwards(self, orm): Removes 'inserted_at' column from each data source table | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Adds an 'inserted_at' column to each existing data source table
- def backwards(self, orm): Removes 'inserted_at' column from each data source table
<... | 97a1f55f24f79224724b2ecdc7d5cea87d42f65b | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Adds an 'inserted_at' column to each existing data source table"""
<|body_0|>
def backwards(self, orm):
"""Removes 'inserted_at' column from each data source table"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Migration:
def forwards(self, orm):
"""Adds an 'inserted_at' column to each existing data source table"""
_sync_couch()
table_names = _get_all_table_names()
num_tables = len(table_names)
logger.info('Start adding inserted_at column to %s existing UCR datasource tables',... | the_stack_v2_python_sparse | corehq/apps/userreports/south_migrations/0001_add_inserted_at_timestamp.py | ekush/commcare-hq | train | 0 | |
ecbde05a244375c231cf86db7fa2c6744efdcef8 | [
"strflag = ''\nfor ibit, name in enumerate(self.name):\n if np.uint64(val) & np.uint64(2 ** ibit) > 0 and (level == 0 or self.level == level):\n strflag = strflag + name + ','\nif strip:\n return strflag.strip(',')\nelse:\n return strflag",
"if type(name) is str:\n name = [name]\nbitval = np.ui... | <|body_start_0|>
strflag = ''
for ibit, name in enumerate(self.name):
if np.uint64(val) & np.uint64(2 ** ibit) > 0 and (level == 0 or self.level == level):
strflag = strflag + name + ','
if strip:
return strflag.strip(',')
else:
return ... | Base class for bitmasks. | BitMask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BitMask:
"""Base class for bitmasks."""
def get_name(self, val, level=0, strip=True):
"""Given input value, returns names of all set bits, optionally of a given level"""
<|body_0|>
def get_value(self, name):
"""Get the numerical bit value of a given character nam... | stack_v2_sparse_classes_36k_train_026621 | 1,714 | permissive | [
{
"docstring": "Given input value, returns names of all set bits, optionally of a given level",
"name": "get_name",
"signature": "def get_name(self, val, level=0, strip=True)"
},
{
"docstring": "Get the numerical bit value of a given character name(s)",
"name": "get_value",
"signature": ... | 4 | stack_v2_sparse_classes_30k_train_001237 | Implement the Python class `BitMask` described below.
Class description:
Base class for bitmasks.
Method signatures and docstrings:
- def get_name(self, val, level=0, strip=True): Given input value, returns names of all set bits, optionally of a given level
- def get_value(self, name): Get the numerical bit value of ... | Implement the Python class `BitMask` described below.
Class description:
Base class for bitmasks.
Method signatures and docstrings:
- def get_name(self, val, level=0, strip=True): Given input value, returns names of all set bits, optionally of a given level
- def get_value(self, name): Get the numerical bit value of ... | 3efe111c80d95b46e2f07288e98e6ee10cbcac9b | <|skeleton|>
class BitMask:
"""Base class for bitmasks."""
def get_name(self, val, level=0, strip=True):
"""Given input value, returns names of all set bits, optionally of a given level"""
<|body_0|>
def get_value(self, name):
"""Get the numerical bit value of a given character nam... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BitMask:
"""Base class for bitmasks."""
def get_name(self, val, level=0, strip=True):
"""Given input value, returns names of all set bits, optionally of a given level"""
strflag = ''
for ibit, name in enumerate(self.name):
if np.uint64(val) & np.uint64(2 ** ibit) > 0 a... | the_stack_v2_python_sparse | python/astra/tools/bitmask.py | sdss/astra | train | 8 |
d01d2d37164921bb9c2e22372dc99fc5dfb2f1d5 | [
"lru = LRUCache(4)\nself.assertIsInstance(lru, LRUCache)\nself.assertEqual(lru.capacity, 4)\nself.assertEqual(lru.length, 0)\nself.assertIsNone(lru.head)\nself.assertIsNone(lru.tail)\nself.assertEqual(lru.cache, {})",
"lru = LRUCache(2)\nlru.put('3', 3)\nlru.put('2', 2)\nlru.get('3')\nlru.put('1', 1)\nself.assert... | <|body_start_0|>
lru = LRUCache(4)
self.assertIsInstance(lru, LRUCache)
self.assertEqual(lru.capacity, 4)
self.assertEqual(lru.length, 0)
self.assertIsNone(lru.head)
self.assertIsNone(lru.tail)
self.assertEqual(lru.cache, {})
<|end_body_0|>
<|body_start_1|>
... | TestLRUCache | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLRUCache:
def test_instantiates_new_lru_cache(self):
"""Instantiates a new LRU Cache"""
<|body_0|>
def test_removes_old_cached_values(self):
"""Does not contain old nodes if removed from cache"""
<|body_1|>
def test_moves_accessed_values_to_head(self... | stack_v2_sparse_classes_36k_train_026622 | 1,542 | permissive | [
{
"docstring": "Instantiates a new LRU Cache",
"name": "test_instantiates_new_lru_cache",
"signature": "def test_instantiates_new_lru_cache(self)"
},
{
"docstring": "Does not contain old nodes if removed from cache",
"name": "test_removes_old_cached_values",
"signature": "def test_remove... | 4 | stack_v2_sparse_classes_30k_train_012998 | Implement the Python class `TestLRUCache` described below.
Class description:
Implement the TestLRUCache class.
Method signatures and docstrings:
- def test_instantiates_new_lru_cache(self): Instantiates a new LRU Cache
- def test_removes_old_cached_values(self): Does not contain old nodes if removed from cache
- def... | Implement the Python class `TestLRUCache` described below.
Class description:
Implement the TestLRUCache class.
Method signatures and docstrings:
- def test_instantiates_new_lru_cache(self): Instantiates a new LRU Cache
- def test_removes_old_cached_values(self): Does not contain old nodes if removed from cache
- def... | 27ffb6b32d6d18d279c51cfa45bf305a409be5c2 | <|skeleton|>
class TestLRUCache:
def test_instantiates_new_lru_cache(self):
"""Instantiates a new LRU Cache"""
<|body_0|>
def test_removes_old_cached_values(self):
"""Does not contain old nodes if removed from cache"""
<|body_1|>
def test_moves_accessed_values_to_head(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLRUCache:
def test_instantiates_new_lru_cache(self):
"""Instantiates a new LRU Cache"""
lru = LRUCache(4)
self.assertIsInstance(lru, LRUCache)
self.assertEqual(lru.capacity, 4)
self.assertEqual(lru.length, 0)
self.assertIsNone(lru.head)
self.assertIs... | the_stack_v2_python_sparse | src/leetcode/medium/lru-cache/test_lru_cache.py | nwthomas/code-challenges | train | 2 | |
2f5c8ea61cdf70eb942da4f54d8eedb7afe83fe8 | [
"player = GamePlayer.random(side_color=mycolors.BLUE)\nbases = [SpiderBase.random(color=mycolors.RED) for i in range(nb)]\nfor base in bases:\n base.spread(10)\nhunters = [GameHunter.random(target=player, side_color=mycolors.YELLOW) for i in range(nh)]\nreturn cls(player, *bases, *hunters, **kwargs)",
"shooted... | <|body_start_0|>
player = GamePlayer.random(side_color=mycolors.BLUE)
bases = [SpiderBase.random(color=mycolors.RED) for i in range(nb)]
for base in bases:
base.spread(10)
hunters = [GameHunter.random(target=player, side_color=mycolors.YELLOW) for i in range(nh)]
retu... | GameSpaceShipGroup | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameSpaceShipGroup:
def random(cls, nh=10, nb=2, **kwargs):
"""Create a random spaceship group."""
<|body_0|>
def shoot(self):
"""Kind of careful shoot just to make it work. Non rigorous at all."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
player... | stack_v2_sparse_classes_36k_train_026623 | 12,573 | no_license | [
{
"docstring": "Create a random spaceship group.",
"name": "random",
"signature": "def random(cls, nh=10, nb=2, **kwargs)"
},
{
"docstring": "Kind of careful shoot just to make it work. Non rigorous at all.",
"name": "shoot",
"signature": "def shoot(self)"
}
] | 2 | null | Implement the Python class `GameSpaceShipGroup` described below.
Class description:
Implement the GameSpaceShipGroup class.
Method signatures and docstrings:
- def random(cls, nh=10, nb=2, **kwargs): Create a random spaceship group.
- def shoot(self): Kind of careful shoot just to make it work. Non rigorous at all. | Implement the Python class `GameSpaceShipGroup` described below.
Class description:
Implement the GameSpaceShipGroup class.
Method signatures and docstrings:
- def random(cls, nh=10, nb=2, **kwargs): Create a random spaceship group.
- def shoot(self): Kind of careful shoot just to make it work. Non rigorous at all.
... | ebfcaaf4a028eddb36bbc99184eb3f7a86eb24ed | <|skeleton|>
class GameSpaceShipGroup:
def random(cls, nh=10, nb=2, **kwargs):
"""Create a random spaceship group."""
<|body_0|>
def shoot(self):
"""Kind of careful shoot just to make it work. Non rigorous at all."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameSpaceShipGroup:
def random(cls, nh=10, nb=2, **kwargs):
"""Create a random spaceship group."""
player = GamePlayer.random(side_color=mycolors.BLUE)
bases = [SpiderBase.random(color=mycolors.RED) for i in range(nb)]
for base in bases:
base.spread(10)
hunt... | the_stack_v2_python_sparse | Game Structure/geometry/version5/myspaceshipgroup.py | MarcPartensky/Python-Games | train | 2 | |
3a1acb44cc561bda6501a51a7d04ffac554f53b1 | [
"size = len(s)\nif size <= 1:\n return s\nnew_s = self.addDivide(s)\np = [1, 2]\nfor i in range(2, len(new_s)):\n tag = 0\n while i - tag >= 0 and i + tag < len(new_s) and (new_s[i - tag] == new_s[i + tag]):\n tag += 1\n p.append(tag)\nprint(p)\nradius = max(p)\nmid = p.index(radius)\nnew_s = new... | <|body_start_0|>
size = len(s)
if size <= 1:
return s
new_s = self.addDivide(s)
p = [1, 2]
for i in range(2, len(new_s)):
tag = 0
while i - tag >= 0 and i + tag < len(new_s) and (new_s[i - tag] == new_s[i + tag]):
tag += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""Manacher 算法本质上还是中心扩散法,只不过它使用了类似 KMP 算法的技巧,充分挖掘了已经进行回文判定的子串的特点,提高算法的效率。 1.对原始字符串进行预处理(为了避免奇数长度的回文子串or偶数长度的回文子串问题) 字符串长度 len 添加分隔符的个数 len+1 -> 最后得到的总长度 2*len+1 一定是奇数 2.得到p数组 p -> 回文半径 能扩散的步数+1 (1为原点) ---> 带分割符的最长子串 是 回文半径p*2-1 得到p-1数... | stack_v2_sparse_classes_36k_train_026624 | 6,670 | no_license | [
{
"docstring": "Manacher 算法本质上还是中心扩散法,只不过它使用了类似 KMP 算法的技巧,充分挖掘了已经进行回文判定的子串的特点,提高算法的效率。 1.对原始字符串进行预处理(为了避免奇数长度的回文子串or偶数长度的回文子串问题) 字符串长度 len 添加分隔符的个数 len+1 -> 最后得到的总长度 2*len+1 一定是奇数 2.得到p数组 p -> 回文半径 能扩散的步数+1 (1为原点) ---> 带分割符的最长子串 是 回文半径p*2-1 得到p-1数组 ---> 不带分割符的最长子串 要 减去 len+1个分隔符 p*2-1 - p+1 = p 3.p-1 数组中最大的数 就是... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: Manacher 算法本质上还是中心扩散法,只不过它使用了类似 KMP 算法的技巧,充分挖掘了已经进行回文判定的子串的特点,提高算法的效率。 1.对原始字符串进行预处理(为了避免奇数长度的回文子串or偶数长度的回文子串问题) 字符串长度 len 添加分隔符的个数 le... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: Manacher 算法本质上还是中心扩散法,只不过它使用了类似 KMP 算法的技巧,充分挖掘了已经进行回文判定的子串的特点,提高算法的效率。 1.对原始字符串进行预处理(为了避免奇数长度的回文子串or偶数长度的回文子串问题) 字符串长度 len 添加分隔符的个数 le... | c0807a7f31a265b3090ef3d32a0ad5a2b10579f7 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""Manacher 算法本质上还是中心扩散法,只不过它使用了类似 KMP 算法的技巧,充分挖掘了已经进行回文判定的子串的特点,提高算法的效率。 1.对原始字符串进行预处理(为了避免奇数长度的回文子串or偶数长度的回文子串问题) 字符串长度 len 添加分隔符的个数 len+1 -> 最后得到的总长度 2*len+1 一定是奇数 2.得到p数组 p -> 回文半径 能扩散的步数+1 (1为原点) ---> 带分割符的最长子串 是 回文半径p*2-1 得到p-1数... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s: str) -> str:
"""Manacher 算法本质上还是中心扩散法,只不过它使用了类似 KMP 算法的技巧,充分挖掘了已经进行回文判定的子串的特点,提高算法的效率。 1.对原始字符串进行预处理(为了避免奇数长度的回文子串or偶数长度的回文子串问题) 字符串长度 len 添加分隔符的个数 len+1 -> 最后得到的总长度 2*len+1 一定是奇数 2.得到p数组 p -> 回文半径 能扩散的步数+1 (1为原点) ---> 带分割符的最长子串 是 回文半径p*2-1 得到p-1数组 ---> 不带分割符的最... | the_stack_v2_python_sparse | five.py | Yanl05/LeetCode | train | 0 | |
31981a762e02e8681df74d7b65375cecad290c17 | [
"nums1.sort()\nself.nums1 = nums1\nself.nums2 = nums2\nself.ctr = collections.Counter(nums2)",
"self.ctr[self.nums2[index]] -= 1\nself.nums2[index] += val\nself.ctr[self.nums2[index]] = self.ctr.setdefault(self.nums2[index], 0) + 1",
"res = 0\nfor i, n1 in enumerate(self.nums1):\n if tot - n1 in self.ctr:\n ... | <|body_start_0|>
nums1.sort()
self.nums1 = nums1
self.nums2 = nums2
self.ctr = collections.Counter(nums2)
<|end_body_0|>
<|body_start_1|>
self.ctr[self.nums2[index]] -= 1
self.nums2[index] += val
self.ctr[self.nums2[index]] = self.ctr.setdefault(self.nums2[index]... | FindSumPairs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FindSumPairs:
def __init__(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int]"""
<|body_0|>
def add(self, index, val):
""":type index: int :type val: int :rtype: None"""
<|body_1|>
def count(self, tot):
""":type tot: int :rtype... | stack_v2_sparse_classes_36k_train_026625 | 1,125 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums1, nums2)"
},
{
"docstring": ":type index: int :type val: int :rtype: None",
"name": "add",
"signature": "def add(self, index, val)"
},
{
"docstring": ":type t... | 3 | null | Implement the Python class `FindSumPairs` described below.
Class description:
Implement the FindSumPairs class.
Method signatures and docstrings:
- def __init__(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int]
- def add(self, index, val): :type index: int :type val: int :rtype: None
- def count(self... | Implement the Python class `FindSumPairs` described below.
Class description:
Implement the FindSumPairs class.
Method signatures and docstrings:
- def __init__(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int]
- def add(self, index, val): :type index: int :type val: int :rtype: None
- def count(self... | ee59b82125f100970c842d5e1245287c484d6649 | <|skeleton|>
class FindSumPairs:
def __init__(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int]"""
<|body_0|>
def add(self, index, val):
""":type index: int :type val: int :rtype: None"""
<|body_1|>
def count(self, tot):
""":type tot: int :rtype... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FindSumPairs:
def __init__(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int]"""
nums1.sort()
self.nums1 = nums1
self.nums2 = nums2
self.ctr = collections.Counter(nums2)
def add(self, index, val):
""":type index: int :type val: int :rtype... | the_stack_v2_python_sparse | _CodeTopics/LeetCode_contest/weekly/weekly2021/241/241_3.py | BIAOXYZ/variousCodes | train | 0 | |
8ff01036032331a3e9a13d5e92a06a43487a5d19 | [
"super().__init__('@'.join(['BalanceTargetSplitter', str(len(split_ratio))]), df=df, fit_flag=False, target_col=target_col)\nif valid_split_ratio(split_ratio):\n if len(split_ratio) == 2:\n train_size = split_ratio[0]\n test_size = split_ratio[1]\n self.splitters = [StratifiedShuffleSplit(n_... | <|body_start_0|>
super().__init__('@'.join(['BalanceTargetSplitter', str(len(split_ratio))]), df=df, fit_flag=False, target_col=target_col)
if valid_split_ratio(split_ratio):
if len(split_ratio) == 2:
train_size = split_ratio[0]
test_size = split_ratio[1]
... | BalanceTargetSplitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BalanceTargetSplitter:
def __init__(self, df, split_ratio, target_col, seed=0):
""":param df: pandas dataframe, stores the data to split. :param split_ratio: list of float, each float represents the size-ratio of splitted data. Corresponding order maps to the size of the train, [validata... | stack_v2_sparse_classes_36k_train_026626 | 6,593 | no_license | [
{
"docstring": ":param df: pandas dataframe, stores the data to split. :param split_ratio: list of float, each float represents the size-ratio of splitted data. Corresponding order maps to the size of the train, [validataion], and test set. Value ranges in [0,1]. Sum of the values in this list should be equal t... | 2 | stack_v2_sparse_classes_30k_train_011260 | Implement the Python class `BalanceTargetSplitter` described below.
Class description:
Implement the BalanceTargetSplitter class.
Method signatures and docstrings:
- def __init__(self, df, split_ratio, target_col, seed=0): :param df: pandas dataframe, stores the data to split. :param split_ratio: list of float, each ... | Implement the Python class `BalanceTargetSplitter` described below.
Class description:
Implement the BalanceTargetSplitter class.
Method signatures and docstrings:
- def __init__(self, df, split_ratio, target_col, seed=0): :param df: pandas dataframe, stores the data to split. :param split_ratio: list of float, each ... | 064c07972dcdd7ae7d4f268bcbde63389be2a9c9 | <|skeleton|>
class BalanceTargetSplitter:
def __init__(self, df, split_ratio, target_col, seed=0):
""":param df: pandas dataframe, stores the data to split. :param split_ratio: list of float, each float represents the size-ratio of splitted data. Corresponding order maps to the size of the train, [validata... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BalanceTargetSplitter:
def __init__(self, df, split_ratio, target_col, seed=0):
""":param df: pandas dataframe, stores the data to split. :param split_ratio: list of float, each float represents the size-ratio of splitted data. Corresponding order maps to the size of the train, [validataion], and test... | the_stack_v2_python_sparse | pipeline/preprocess/splitters.py | tinluu/Fairness_Labels_for_ML_Pipelines | train | 0 | |
144ca81cdcb097590c25ac1e088ad6ac3f8040c2 | [
"self.validate_parameters(content_type=content_type, accept=accept, customer_id=customer_id, account_id=account_id, body=body)\n_url_path = '/aggregation/v1/customers/{customerId}/accounts/{accountId}/transactions'\n_url_path = APIHelper.append_url_with_template_parameters(_url_path, {'customerId': customer_id, 'ac... | <|body_start_0|>
self.validate_parameters(content_type=content_type, accept=accept, customer_id=customer_id, account_id=account_id, body=body)
_url_path = '/aggregation/v1/customers/{customerId}/accounts/{accountId}/transactions'
_url_path = APIHelper.append_url_with_template_parameters(_url_pat... | A Controller to access Endpoints in the finicityapi API. | TxpushController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TxpushController:
"""A Controller to access Endpoints in the finicityapi API."""
def create_txpush_test_transaction(self, content_type, accept, customer_id, account_id, body):
"""Does a POST request to /aggregation/v1/customers/{customerId}/accounts/{accountId}/transactions. Inject a... | stack_v2_sparse_classes_36k_train_026627 | 11,724 | permissive | [
{
"docstring": "Does a POST request to /aggregation/v1/customers/{customerId}/accounts/{accountId}/transactions. Inject a transaction into the transaction list for a testing account. This allows an app to trigger TxPush notifications for the account in order to test the app’s TxPush Listener service. This cause... | 4 | null | Implement the Python class `TxpushController` described below.
Class description:
A Controller to access Endpoints in the finicityapi API.
Method signatures and docstrings:
- def create_txpush_test_transaction(self, content_type, accept, customer_id, account_id, body): Does a POST request to /aggregation/v1/customers... | Implement the Python class `TxpushController` described below.
Class description:
A Controller to access Endpoints in the finicityapi API.
Method signatures and docstrings:
- def create_txpush_test_transaction(self, content_type, accept, customer_id, account_id, body): Does a POST request to /aggregation/v1/customers... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class TxpushController:
"""A Controller to access Endpoints in the finicityapi API."""
def create_txpush_test_transaction(self, content_type, accept, customer_id, account_id, body):
"""Does a POST request to /aggregation/v1/customers/{customerId}/accounts/{accountId}/transactions. Inject a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TxpushController:
"""A Controller to access Endpoints in the finicityapi API."""
def create_txpush_test_transaction(self, content_type, accept, customer_id, account_id, body):
"""Does a POST request to /aggregation/v1/customers/{customerId}/accounts/{accountId}/transactions. Inject a transaction ... | the_stack_v2_python_sparse | finicityapi/controllers/txpush_controller.py | monarchmoney/finicity-python | train | 0 |
5e5f9408e62f14e81887a775f16399416197df1e | [
"super(CNNModel, self).__init__(env=env, args=args)\nself.args = args\nself.num_actions = env.action_space.n\nself.head = nn.Sequential(nn.Conv2d(4, 32, kernel_size=8, stride=4), nn.ReLU(), nn.BatchNorm2d(32) if self.args.use_bnorm else nn.Identity(), nn.Conv2d(32, 64, kernel_size=4, stride=2), nn.ReLU(), nn.BatchN... | <|body_start_0|>
super(CNNModel, self).__init__(env=env, args=args)
self.args = args
self.num_actions = env.action_space.n
self.head = nn.Sequential(nn.Conv2d(4, 32, kernel_size=8, stride=4), nn.ReLU(), nn.BatchNorm2d(32) if self.args.use_bnorm else nn.Identity(), nn.Conv2d(32, 64, kerne... | Initialize a deep Q-learning network Hints: ----- Original paper for DQN https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf This is just a hint. You can build your own structure. | CNNModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNNModel:
"""Initialize a deep Q-learning network Hints: ----- Original paper for DQN https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf This is just a hint. You can build your own structure."""
def __init__(self, env, args):
"""You can add additi... | stack_v2_sparse_classes_36k_train_026628 | 1,807 | permissive | [
{
"docstring": "You can add additional arguments as you need. In the constructor we instantiate modules and assign them as member variables.",
"name": "__init__",
"signature": "def __init__(self, env, args)"
},
{
"docstring": "In the forward function we accept a Tensor of input data and we must ... | 2 | stack_v2_sparse_classes_30k_train_015135 | Implement the Python class `CNNModel` described below.
Class description:
Initialize a deep Q-learning network Hints: ----- Original paper for DQN https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf This is just a hint. You can build your own structure.
Method signatures and docstr... | Implement the Python class `CNNModel` described below.
Class description:
Initialize a deep Q-learning network Hints: ----- Original paper for DQN https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf This is just a hint. You can build your own structure.
Method signatures and docstr... | 01b3c6568f263d60cb8a7e9c3b048d93b64443d4 | <|skeleton|>
class CNNModel:
"""Initialize a deep Q-learning network Hints: ----- Original paper for DQN https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf This is just a hint. You can build your own structure."""
def __init__(self, env, args):
"""You can add additi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CNNModel:
"""Initialize a deep Q-learning network Hints: ----- Original paper for DQN https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf This is just a hint. You can build your own structure."""
def __init__(self, env, args):
"""You can add additional argument... | the_stack_v2_python_sparse | curious_agent/models/cnn_model.py | kingspp/curious_agent | train | 1 |
dec2f87205f505a6d7bff655506b0bfadae68be9 | [
"self.ad_domain_name = ad_domain_name\nself.attribute_common_name = attribute_common_name\nself.attribute_gid = attribute_gid\nself.attribute_member_of = attribute_member_of\nself.attribute_uid = attribute_uid\nself.attribute_user_name = attribute_user_name\nself.auth_type = auth_type\nself.base_distinguished_name ... | <|body_start_0|>
self.ad_domain_name = ad_domain_name
self.attribute_common_name = attribute_common_name
self.attribute_gid = attribute_gid
self.attribute_member_of = attribute_member_of
self.attribute_uid = attribute_uid
self.attribute_user_name = attribute_user_name
... | Implementation of the 'LdapProviderResponse' model. LDAP provider response struct. Attributes: ad_domain_name (string): Specifies the domain name of an Active Directory which is mapped to this LDAP provider attribute_common_name (string): Name of the LDAP attribute used for common name of an object. attribute_gid (stri... | LdapProviderResponse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LdapProviderResponse:
"""Implementation of the 'LdapProviderResponse' model. LDAP provider response struct. Attributes: ad_domain_name (string): Specifies the domain name of an Active Directory which is mapped to this LDAP provider attribute_common_name (string): Name of the LDAP attribute used f... | stack_v2_sparse_classes_36k_train_026629 | 7,420 | permissive | [
{
"docstring": "Constructor for the LdapProviderResponse class",
"name": "__init__",
"signature": "def __init__(self, ad_domain_name=None, attribute_common_name=None, attribute_gid=None, attribute_member_of=None, attribute_uid=None, attribute_user_name=None, auth_type=None, base_distinguished_name=None,... | 2 | null | Implement the Python class `LdapProviderResponse` described below.
Class description:
Implementation of the 'LdapProviderResponse' model. LDAP provider response struct. Attributes: ad_domain_name (string): Specifies the domain name of an Active Directory which is mapped to this LDAP provider attribute_common_name (str... | Implement the Python class `LdapProviderResponse` described below.
Class description:
Implementation of the 'LdapProviderResponse' model. LDAP provider response struct. Attributes: ad_domain_name (string): Specifies the domain name of an Active Directory which is mapped to this LDAP provider attribute_common_name (str... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class LdapProviderResponse:
"""Implementation of the 'LdapProviderResponse' model. LDAP provider response struct. Attributes: ad_domain_name (string): Specifies the domain name of an Active Directory which is mapped to this LDAP provider attribute_common_name (string): Name of the LDAP attribute used f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LdapProviderResponse:
"""Implementation of the 'LdapProviderResponse' model. LDAP provider response struct. Attributes: ad_domain_name (string): Specifies the domain name of an Active Directory which is mapped to this LDAP provider attribute_common_name (string): Name of the LDAP attribute used for common nam... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ldap_provider_response.py | cohesity/management-sdk-python | train | 24 |
6c62533f884b57095d1924b36cba24805dac91fe | [
"uri = self.base_path\nresp = session.post(uri, headers={'Content-Type': 'application/json'}, endpoint_filter=self.service, json={'image_id': image_id, 'tenant_id_dst': tenant_id_dst})\nself._translate_response(resp, has_body=True)\nreturn self",
"uri = self.base_path + '/' + str(job_id)\nresp = session.delete(ur... | <|body_start_0|>
uri = self.base_path
resp = session.post(uri, headers={'Content-Type': 'application/json'}, endpoint_filter=self.service, json={'image_id': image_id, 'tenant_id_dst': tenant_id_dst})
self._translate_response(resp, has_body=True)
return self
<|end_body_0|>
<|body_start_1... | ImageCopy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageCopy:
def copy_image(self, session, image_id, tenant_id_dst):
"""Copy image to a specified region."""
<|body_0|>
def cancel_copy_image(self, session, job_id):
"""Cancel a specified image copy job."""
<|body_1|>
def list_image_copy_jobs(self, session... | stack_v2_sparse_classes_36k_train_026630 | 2,977 | permissive | [
{
"docstring": "Copy image to a specified region.",
"name": "copy_image",
"signature": "def copy_image(self, session, image_id, tenant_id_dst)"
},
{
"docstring": "Cancel a specified image copy job.",
"name": "cancel_copy_image",
"signature": "def cancel_copy_image(self, session, job_id)"... | 4 | stack_v2_sparse_classes_30k_val_000449 | Implement the Python class `ImageCopy` described below.
Class description:
Implement the ImageCopy class.
Method signatures and docstrings:
- def copy_image(self, session, image_id, tenant_id_dst): Copy image to a specified region.
- def cancel_copy_image(self, session, job_id): Cancel a specified image copy job.
- d... | Implement the Python class `ImageCopy` described below.
Class description:
Implement the ImageCopy class.
Method signatures and docstrings:
- def copy_image(self, session, image_id, tenant_id_dst): Copy image to a specified region.
- def cancel_copy_image(self, session, job_id): Cancel a specified image copy job.
- d... | c2dafba850c4e6fb55b5e10de79257bbc9a01af3 | <|skeleton|>
class ImageCopy:
def copy_image(self, session, image_id, tenant_id_dst):
"""Copy image to a specified region."""
<|body_0|>
def cancel_copy_image(self, session, job_id):
"""Cancel a specified image copy job."""
<|body_1|>
def list_image_copy_jobs(self, session... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageCopy:
def copy_image(self, session, image_id, tenant_id_dst):
"""Copy image to a specified region."""
uri = self.base_path
resp = session.post(uri, headers={'Content-Type': 'application/json'}, endpoint_filter=self.service, json={'image_id': image_id, 'tenant_id_dst': tenant_id_ds... | the_stack_v2_python_sparse | ecl/image/v2/image_copy.py | nttcom/eclsdk | train | 5 | |
c5fcdfe636c82671a7c45559fcfbdb1a92e64a26 | [
"a = opencue.api.filter_pb2.Action()\na.type = Convert.strToActionType(actionType)\nActionUtil.setValue(a, value)\nreturn a",
"valueType = str(a.data.value_type)\nif valueType == 'GroupType':\n return a.data.group_value\nif valueType == 'StringType':\n return a.data.string_value\nif valueType == 'IntegerTyp... | <|body_start_0|>
a = opencue.api.filter_pb2.Action()
a.type = Convert.strToActionType(actionType)
ActionUtil.setValue(a, value)
return a
<|end_body_0|>
<|body_start_1|>
valueType = str(a.data.value_type)
if valueType == 'GroupType':
return a.data.group_value
... | Utility class for interacting with Actions. | ActionUtil | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionUtil:
"""Utility class for interacting with Actions."""
def factory(actionType, value):
"""Creates an Action."""
<|body_0|>
def getValue(a):
"""Gets an action's value."""
<|body_1|>
def setValue(act, value):
"""Sets an action's value.""... | stack_v2_sparse_classes_36k_train_026631 | 33,946 | permissive | [
{
"docstring": "Creates an Action.",
"name": "factory",
"signature": "def factory(actionType, value)"
},
{
"docstring": "Gets an action's value.",
"name": "getValue",
"signature": "def getValue(a)"
},
{
"docstring": "Sets an action's value.",
"name": "setValue",
"signatur... | 3 | null | Implement the Python class `ActionUtil` described below.
Class description:
Utility class for interacting with Actions.
Method signatures and docstrings:
- def factory(actionType, value): Creates an Action.
- def getValue(a): Gets an action's value.
- def setValue(act, value): Sets an action's value. | Implement the Python class `ActionUtil` described below.
Class description:
Utility class for interacting with Actions.
Method signatures and docstrings:
- def factory(actionType, value): Creates an Action.
- def getValue(a): Gets an action's value.
- def setValue(act, value): Sets an action's value.
<|skeleton|>
cl... | c1f335d22e59cdf75859aa14ecdfe43d9cb43e95 | <|skeleton|>
class ActionUtil:
"""Utility class for interacting with Actions."""
def factory(actionType, value):
"""Creates an Action."""
<|body_0|>
def getValue(a):
"""Gets an action's value."""
<|body_1|>
def setValue(act, value):
"""Sets an action's value.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionUtil:
"""Utility class for interacting with Actions."""
def factory(actionType, value):
"""Creates an Action."""
a = opencue.api.filter_pb2.Action()
a.type = Convert.strToActionType(actionType)
ActionUtil.setValue(a, value)
return a
def getValue(a):
... | the_stack_v2_python_sparse | cueadmin/cueadmin/common.py | AcademySoftwareFoundation/OpenCue | train | 439 |
e1d5cf21586fd700760096b550b4b7c0fef1ed2f | [
"if not request.user.groups.filter(name='Rep Admin').count():\n obj.sales_rep = request.user\nobj.save()",
"if request.user.groups.filter(name='Rep Admin').count():\n self.fields = ['task_date', 'is_in_schedule', 'description', 'urgency', 'practice', 'category', 'is_completed', 'sales_rep']\nelse:\n self... | <|body_start_0|>
if not request.user.groups.filter(name='Rep Admin').count():
obj.sales_rep = request.user
obj.save()
<|end_body_0|>
<|body_start_1|>
if request.user.groups.filter(name='Rep Admin').count():
self.fields = ['task_date', 'is_in_schedule', 'description', 'ur... | TaskAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskAdmin:
def save_model(self, request, obj, form, change):
"""saves employee name who creates task, only if user is not an admin"""
<|body_0|>
def get_form(self, request, obj=None, **kwargs):
"""Adds employee name field"""
<|body_1|>
def changelist_vie... | stack_v2_sparse_classes_36k_train_026632 | 1,832 | no_license | [
{
"docstring": "saves employee name who creates task, only if user is not an admin",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "Adds employee name field",
"name": "get_form",
"signature": "def get_form(self, request, obj=None,... | 3 | stack_v2_sparse_classes_30k_train_020934 | Implement the Python class `TaskAdmin` described below.
Class description:
Implement the TaskAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): saves employee name who creates task, only if user is not an admin
- def get_form(self, request, obj=None, **kwargs): Adds emp... | Implement the Python class `TaskAdmin` described below.
Class description:
Implement the TaskAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): saves employee name who creates task, only if user is not an admin
- def get_form(self, request, obj=None, **kwargs): Adds emp... | c216ab3e5c1aad5c5022d55514b6e39acbf1dd23 | <|skeleton|>
class TaskAdmin:
def save_model(self, request, obj, form, change):
"""saves employee name who creates task, only if user is not an admin"""
<|body_0|>
def get_form(self, request, obj=None, **kwargs):
"""Adds employee name field"""
<|body_1|>
def changelist_vie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskAdmin:
def save_model(self, request, obj, form, change):
"""saves employee name who creates task, only if user is not an admin"""
if not request.user.groups.filter(name='Rep Admin').count():
obj.sales_rep = request.user
obj.save()
def get_form(self, request, obj=No... | the_stack_v2_python_sparse | tasks/admin.py | chc5286/lindencare | train | 0 | |
bfeafaadc6fd0c350c3a59e02565ccf3be744853 | [
"order_db = OrderDbQueries()\nif current_user.username == 'admin':\n if orderId:\n query = order_db.fetch_specific_order_by_parameter('orders', 'orderId', orderId)\n for order in query:\n return (jsonify({'orders': order}), 200)\n return (jsonify({'message': 'Order not found.'}), ... | <|body_start_0|>
order_db = OrderDbQueries()
if current_user.username == 'admin':
if orderId:
query = order_db.fetch_specific_order_by_parameter('orders', 'orderId', orderId)
for order in query:
return (jsonify({'orders': order}), 200)
... | OrdersManagementView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrdersManagementView:
def get(self, current_user, orderId):
"""Return all orders."""
<|body_0|>
def put(self, current_user, orderId):
"""Update an order."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
order_db = OrderDbQueries()
if current_... | stack_v2_sparse_classes_36k_train_026633 | 3,187 | no_license | [
{
"docstring": "Return all orders.",
"name": "get",
"signature": "def get(self, current_user, orderId)"
},
{
"docstring": "Update an order.",
"name": "put",
"signature": "def put(self, current_user, orderId)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002398 | Implement the Python class `OrdersManagementView` described below.
Class description:
Implement the OrdersManagementView class.
Method signatures and docstrings:
- def get(self, current_user, orderId): Return all orders.
- def put(self, current_user, orderId): Update an order. | Implement the Python class `OrdersManagementView` described below.
Class description:
Implement the OrdersManagementView class.
Method signatures and docstrings:
- def get(self, current_user, orderId): Return all orders.
- def put(self, current_user, orderId): Update an order.
<|skeleton|>
class OrdersManagementView... | 4c02cb785ff39e99f678a9e36d992dcd62c01f2d | <|skeleton|>
class OrdersManagementView:
def get(self, current_user, orderId):
"""Return all orders."""
<|body_0|>
def put(self, current_user, orderId):
"""Update an order."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrdersManagementView:
def get(self, current_user, orderId):
"""Return all orders."""
order_db = OrderDbQueries()
if current_user.username == 'admin':
if orderId:
query = order_db.fetch_specific_order_by_parameter('orders', 'orderId', orderId)
... | the_stack_v2_python_sparse | app/orders/api.py | alexkayabula/data-vizr | train | 0 | |
22682255bae50d8cd3b8bff3efcad4e0766b305a | [
"self._rows = invert(rows)\nself._columns = invert(columns)\nself._characters = characters\nself._last = None\ntry:\n self._rows.write(~0)\nexcept:\n pass\nif self._rows.n * self._columns.n != len(self._characters):\n raise Exception('keypad error %d rows %d columns %d characters' % (self._rows.n, self._co... | <|body_start_0|>
self._rows = invert(rows)
self._columns = invert(columns)
self._characters = characters
self._last = None
try:
self._rows.write(~0)
except:
pass
if self._rows.n * self._columns.n != len(self._characters):
raise ... | Interface for a matrix keypad. | keypad | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class keypad:
"""Interface for a matrix keypad."""
def __init__(self, rows, columns, characters):
"""Create a matrix keypad interface. Create a matrix keypad from the rows and columns ports, and the list of characters to be returned for pressed keys. The characters list is by row. The leng... | stack_v2_sparse_classes_36k_train_026634 | 3,252 | permissive | [
{
"docstring": "Create a matrix keypad interface. Create a matrix keypad from the rows and columns ports, and the list of characters to be returned for pressed keys. The characters list is by row. The length of the list must be the number of rows multiplied by the number of columns. The rows must support write ... | 5 | stack_v2_sparse_classes_30k_train_000875 | Implement the Python class `keypad` described below.
Class description:
Interface for a matrix keypad.
Method signatures and docstrings:
- def __init__(self, rows, columns, characters): Create a matrix keypad interface. Create a matrix keypad from the rows and columns ports, and the list of characters to be returned ... | Implement the Python class `keypad` described below.
Class description:
Interface for a matrix keypad.
Method signatures and docstrings:
- def __init__(self, rows, columns, characters): Create a matrix keypad interface. Create a matrix keypad from the rows and columns ports, and the list of characters to be returned ... | f00f2acf23bc7160d0970be609b06ea4d824b76b | <|skeleton|>
class keypad:
"""Interface for a matrix keypad."""
def __init__(self, rows, columns, characters):
"""Create a matrix keypad interface. Create a matrix keypad from the rows and columns ports, and the list of characters to be returned for pressed keys. The characters list is by row. The leng... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class keypad:
"""Interface for a matrix keypad."""
def __init__(self, rows, columns, characters):
"""Create a matrix keypad interface. Create a matrix keypad from the rows and columns ports, and the list of characters to be returned for pressed keys. The characters list is by row. The length of the lis... | the_stack_v2_python_sparse | hwpy_modules/keypad.py | wovo/hwpy | train | 0 |
6159cbf0fe7a5abbdae8e7e77194f7ee0c3d9e38 | [
"self.index_name = args.index_name\nself.index_type = args.index_type\nself.seven = args.seven\nself.endpoint = args.endpoint",
"\"\"\" TODO: This should use the timezone of the current host or UTC.\"\"\"\nnow_utc = datetime.now(timezone('UTC'))\nreturn now_utc.astimezone(timezone('US/Pacific'))",
"batch = []\n... | <|body_start_0|>
self.index_name = args.index_name
self.index_type = args.index_type
self.seven = args.seven
self.endpoint = args.endpoint
<|end_body_0|>
<|body_start_1|>
""" TODO: This should use the timezone of the current host or UTC."""
now_utc = datetime.now(timezon... | Use this class to send documents in bulk to Elasticsearch | MetricWriter | [
"Apache-2.0",
"MIT-0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricWriter:
"""Use this class to send documents in bulk to Elasticsearch"""
def __init__(self, args):
"""Recieves the command-line args, which must include an index root, and an ES type."""
<|body_0|>
def now_pst(self):
"""Return the current time in PST timezon... | stack_v2_sparse_classes_36k_train_026635 | 6,421 | permissive | [
{
"docstring": "Recieves the command-line args, which must include an index root, and an ES type.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Return the current time in PST timezone",
"name": "now_pst",
"signature": "def now_pst(self)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_015144 | Implement the Python class `MetricWriter` described below.
Class description:
Use this class to send documents in bulk to Elasticsearch
Method signatures and docstrings:
- def __init__(self, args): Recieves the command-line args, which must include an index root, and an ES type.
- def now_pst(self): Return the curren... | Implement the Python class `MetricWriter` described below.
Class description:
Use this class to send documents in bulk to Elasticsearch
Method signatures and docstrings:
- def __init__(self, args): Recieves the command-line args, which must include an index root, and an ES type.
- def now_pst(self): Return the curren... | 02e7da9e100d8ba4ab41416fe38c3cf911dc8a29 | <|skeleton|>
class MetricWriter:
"""Use this class to send documents in bulk to Elasticsearch"""
def __init__(self, args):
"""Recieves the command-line args, which must include an index root, and an ES type."""
<|body_0|>
def now_pst(self):
"""Return the current time in PST timezon... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetricWriter:
"""Use this class to send documents in bulk to Elasticsearch"""
def __init__(self, args):
"""Recieves the command-line args, which must include an index root, and an ES type."""
self.index_name = args.index_name
self.index_type = args.index_type
self.seven = ... | the_stack_v2_python_sparse | pa-to-es/main.py | gaiksaya/community | train | 0 |
da523ce490dd993eeca02599f67aa7c1bd4d45f0 | [
"self.names_set = set(old_gene_names)\nself.names_to_add = list(set(new_gene_names).difference(old_gene_names))\nif len(self.names_to_add) == 0:\n print('No new genes to add')\nif fixed_new and len(self.names_set.difference(new_gene_names)) == 0:\n print('using new gene names')\n self.names_list = np.array... | <|body_start_0|>
self.names_set = set(old_gene_names)
self.names_to_add = list(set(new_gene_names).difference(old_gene_names))
if len(self.names_to_add) == 0:
print('No new genes to add')
if fixed_new and len(self.names_set.difference(new_gene_names)) == 0:
print(... | GeneNameTransform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneNameTransform:
def __init__(self, old_gene_names, new_gene_names, fixed_new=False):
"""Args: old_gene_names (array of str) new_gene_names (array of str)"""
<|body_0|>
def transform_old(self, old_data):
"""Transforms a dataset of the "old" gene names to the unifie... | stack_v2_sparse_classes_36k_train_026636 | 11,844 | no_license | [
{
"docstring": "Args: old_gene_names (array of str) new_gene_names (array of str)",
"name": "__init__",
"signature": "def __init__(self, old_gene_names, new_gene_names, fixed_new=False)"
},
{
"docstring": "Transforms a dataset of the \"old\" gene names to the unified form. old_data: 1d array or ... | 3 | stack_v2_sparse_classes_30k_train_001462 | Implement the Python class `GeneNameTransform` described below.
Class description:
Implement the GeneNameTransform class.
Method signatures and docstrings:
- def __init__(self, old_gene_names, new_gene_names, fixed_new=False): Args: old_gene_names (array of str) new_gene_names (array of str)
- def transform_old(self,... | Implement the Python class `GeneNameTransform` described below.
Class description:
Implement the GeneNameTransform class.
Method signatures and docstrings:
- def __init__(self, old_gene_names, new_gene_names, fixed_new=False): Args: old_gene_names (array of str) new_gene_names (array of str)
- def transform_old(self,... | e60704e35994cb65e6b086db76719c8a671d61d8 | <|skeleton|>
class GeneNameTransform:
def __init__(self, old_gene_names, new_gene_names, fixed_new=False):
"""Args: old_gene_names (array of str) new_gene_names (array of str)"""
<|body_0|>
def transform_old(self, old_data):
"""Transforms a dataset of the "old" gene names to the unifie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneNameTransform:
def __init__(self, old_gene_names, new_gene_names, fixed_new=False):
"""Args: old_gene_names (array of str) new_gene_names (array of str)"""
self.names_set = set(old_gene_names)
self.names_to_add = list(set(new_gene_names).difference(old_gene_names))
if len(s... | the_stack_v2_python_sparse | preprocess_mca_microwell_seq.py | yjzhang/mouse_cell_query | train | 2 | |
92d897d3613bf38f74ff95557c17964b76e4ba8b | [
"longest_streak = 0\nnum_set = set(nums)\nfor num in num_set:\n if num - 1 not in num_set:\n current_num = num\n current_streak = 1\n while current_num + 1 in num_set:\n current_num += 1\n current_streak += 1\n longest_streak = max(longest_streak, current_streak)... | <|body_start_0|>
longest_streak = 0
num_set = set(nums)
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_streak = 1
while current_num + 1 in num_set:
current_num += 1
curre... | Sequence | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sequence:
def find_longest_consecutive(self, nums: List[int]) -> int:
"""Approach: Hash Set and Intelligence Sequence Building Time Complexity: O(n) Space Complexity: O(n) :param nums: :return:"""
<|body_0|>
def find_longest_consecutive_(self, nums: List[int]) -> int:
... | stack_v2_sparse_classes_36k_train_026637 | 2,192 | no_license | [
{
"docstring": "Approach: Hash Set and Intelligence Sequence Building Time Complexity: O(n) Space Complexity: O(n) :param nums: :return:",
"name": "find_longest_consecutive",
"signature": "def find_longest_consecutive(self, nums: List[int]) -> int"
},
{
"docstring": "Approach: Sorting Time Compl... | 3 | stack_v2_sparse_classes_30k_train_016582 | Implement the Python class `Sequence` described below.
Class description:
Implement the Sequence class.
Method signatures and docstrings:
- def find_longest_consecutive(self, nums: List[int]) -> int: Approach: Hash Set and Intelligence Sequence Building Time Complexity: O(n) Space Complexity: O(n) :param nums: :retur... | Implement the Python class `Sequence` described below.
Class description:
Implement the Sequence class.
Method signatures and docstrings:
- def find_longest_consecutive(self, nums: List[int]) -> int: Approach: Hash Set and Intelligence Sequence Building Time Complexity: O(n) Space Complexity: O(n) :param nums: :retur... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Sequence:
def find_longest_consecutive(self, nums: List[int]) -> int:
"""Approach: Hash Set and Intelligence Sequence Building Time Complexity: O(n) Space Complexity: O(n) :param nums: :return:"""
<|body_0|>
def find_longest_consecutive_(self, nums: List[int]) -> int:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Sequence:
def find_longest_consecutive(self, nums: List[int]) -> int:
"""Approach: Hash Set and Intelligence Sequence Building Time Complexity: O(n) Space Complexity: O(n) :param nums: :return:"""
longest_streak = 0
num_set = set(nums)
for num in num_set:
if num - 1... | the_stack_v2_python_sparse | data_structures/longest_consecutive_sequence.py | Shiv2157k/leet_code | train | 1 | |
2a324e8acd6318312984201b68794a9a1b688599 | [
"self.repetitions = repetitions\nself.num_sources = num_sources\nself.probabilities = probabilities\nif self.probabilities is not None:\n self.probabilities = [float(x) / np.sum(probabilities) for x in self.probabilities]\nif self.probabilities is not None:\n assert self.num_sources == len(self.probabilities)... | <|body_start_0|>
self.repetitions = repetitions
self.num_sources = num_sources
self.probabilities = probabilities
if self.probabilities is not None:
self.probabilities = [float(x) / np.sum(probabilities) for x in self.probabilities]
if self.probabilities is not None:
... | RandomBranchSelector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomBranchSelector:
def __init__(self, num_sources, probabilities=None, repetitions=1):
"""Create random points in a provided ROI with the given density. Args: repetitions (int): How many times the generator will be used in a pipeline. Only the first request to the RandomSource will ha... | stack_v2_sparse_classes_36k_train_026638 | 3,329 | no_license | [
{
"docstring": "Create random points in a provided ROI with the given density. Args: repetitions (int): How many times the generator will be used in a pipeline. Only the first request to the RandomSource will have a random source chosen. Future calls will use the same source.",
"name": "__init__",
"sign... | 2 | stack_v2_sparse_classes_30k_train_006795 | Implement the Python class `RandomBranchSelector` described below.
Class description:
Implement the RandomBranchSelector class.
Method signatures and docstrings:
- def __init__(self, num_sources, probabilities=None, repetitions=1): Create random points in a provided ROI with the given density. Args: repetitions (int)... | Implement the Python class `RandomBranchSelector` described below.
Class description:
Implement the RandomBranchSelector class.
Method signatures and docstrings:
- def __init__(self, num_sources, probabilities=None, repetitions=1): Create random points in a provided ROI with the given density. Args: repetitions (int)... | 188c9296e38e9be2161732ecd0f7da273d1492d2 | <|skeleton|>
class RandomBranchSelector:
def __init__(self, num_sources, probabilities=None, repetitions=1):
"""Create random points in a provided ROI with the given density. Args: repetitions (int): How many times the generator will be used in a pipeline. Only the first request to the RandomSource will ha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomBranchSelector:
def __init__(self, num_sources, probabilities=None, repetitions=1):
"""Create random points in a provided ROI with the given density. Args: repetitions (int): How many times the generator will be used in a pipeline. Only the first request to the RandomSource will have a random so... | the_stack_v2_python_sparse | lisl/gp/random_provider.py | funkelab/lisl | train | 1 | |
fe6f208cddc84bea8d5bca52e0bc3c6d2764cfcc | [
"tests = ['test.1', 'test.2']\nexpected = 'test.1:test.2'\nself.assertEqual(test_runner.get_gtest_filter(tests), expected)",
"tests = ['test.1', 'test.2']\nexpected = '-test.1:test.2'\nself.assertEqual(test_runner.get_gtest_filter(tests, invert=True), expected)"
] | <|body_start_0|>
tests = ['test.1', 'test.2']
expected = 'test.1:test.2'
self.assertEqual(test_runner.get_gtest_filter(tests), expected)
<|end_body_0|>
<|body_start_1|>
tests = ['test.1', 'test.2']
expected = '-test.1:test.2'
self.assertEqual(test_runner.get_gtest_filter... | Tests for test_runner.get_gtest_filter. | GetGTestFilterTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetGTestFilterTest:
"""Tests for test_runner.get_gtest_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
<|body_0|>
def test_correct_inverted(self):
"""Ensures correctness of inverted filter."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_026639 | 19,298 | permissive | [
{
"docstring": "Ensures correctness of filter.",
"name": "test_correct",
"signature": "def test_correct(self)"
},
{
"docstring": "Ensures correctness of inverted filter.",
"name": "test_correct_inverted",
"signature": "def test_correct_inverted(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008282 | Implement the Python class `GetGTestFilterTest` described below.
Class description:
Tests for test_runner.get_gtest_filter.
Method signatures and docstrings:
- def test_correct(self): Ensures correctness of filter.
- def test_correct_inverted(self): Ensures correctness of inverted filter. | Implement the Python class `GetGTestFilterTest` described below.
Class description:
Tests for test_runner.get_gtest_filter.
Method signatures and docstrings:
- def test_correct(self): Ensures correctness of filter.
- def test_correct_inverted(self): Ensures correctness of inverted filter.
<|skeleton|>
class GetGTest... | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | <|skeleton|>
class GetGTestFilterTest:
"""Tests for test_runner.get_gtest_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
<|body_0|>
def test_correct_inverted(self):
"""Ensures correctness of inverted filter."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetGTestFilterTest:
"""Tests for test_runner.get_gtest_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
tests = ['test.1', 'test.2']
expected = 'test.1:test.2'
self.assertEqual(test_runner.get_gtest_filter(tests), expected)
def test_correct_inve... | the_stack_v2_python_sparse | ios/build/bots/scripts/test_runner_test.py | Samsung/Castanets | train | 58 |
8f0d7b11194195600ddf1d1e0ff6b8ab8f935317 | [
"self.real_counter = 0\nfor keyword, value in keywords.iteritems():\n setattr(self, keyword, value)",
"param_obj.counter += 1\nif read.is_unmapped:\n return\nif read.qname not in param_obj.qname2count:\n param_obj.qname2count[read.qname] = 0\nparam_obj.qname2count[read.qname] += 1\nscore = None\nrefName ... | <|body_start_0|>
self.real_counter = 0
for keyword, value in keywords.iteritems():
setattr(self, keyword, value)
<|end_body_0|>
<|body_start_1|>
param_obj.counter += 1
if read.is_unmapped:
return
if read.qname not in param_obj.qname2count:
par... | 2011-7-8 This class filters bwa output bam file based on two criteria. read.mapq>=minMapQ score >= minPerBaseAS only for bwasw, which has AS (alignment score) tag. | FilterAlignmentByReferenceIDs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterAlignmentByReferenceIDs:
"""2011-7-8 This class filters bwa output bam file based on two criteria. read.mapq>=minMapQ score >= minPerBaseAS only for bwasw, which has AS (alignment score) tag."""
def __init__(self, **keywords):
"""keywords shall include bamOutputF, scoreType, mi... | stack_v2_sparse_classes_36k_train_026640 | 5,164 | no_license | [
{
"docstring": "keywords shall include bamOutputF, scoreType, minMapQ, minPerBaseAS",
"name": "__init__",
"signature": "def __init__(self, **keywords)"
},
{
"docstring": "2011-7-8",
"name": "run",
"signature": "def run(self, read, param_obj=None)"
}
] | 2 | null | Implement the Python class `FilterAlignmentByReferenceIDs` described below.
Class description:
2011-7-8 This class filters bwa output bam file based on two criteria. read.mapq>=minMapQ score >= minPerBaseAS only for bwasw, which has AS (alignment score) tag.
Method signatures and docstrings:
- def __init__(self, **ke... | Implement the Python class `FilterAlignmentByReferenceIDs` described below.
Class description:
2011-7-8 This class filters bwa output bam file based on two criteria. read.mapq>=minMapQ score >= minPerBaseAS only for bwasw, which has AS (alignment score) tag.
Method signatures and docstrings:
- def __init__(self, **ke... | a550680f83d4c0c524734ee94bdd540c40f3a537 | <|skeleton|>
class FilterAlignmentByReferenceIDs:
"""2011-7-8 This class filters bwa output bam file based on two criteria. read.mapq>=minMapQ score >= minPerBaseAS only for bwasw, which has AS (alignment score) tag."""
def __init__(self, **keywords):
"""keywords shall include bamOutputF, scoreType, mi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterAlignmentByReferenceIDs:
"""2011-7-8 This class filters bwa output bam file based on two criteria. read.mapq>=minMapQ score >= minPerBaseAS only for bwasw, which has AS (alignment score) tag."""
def __init__(self, **keywords):
"""keywords shall include bamOutputF, scoreType, minMapQ, minPer... | the_stack_v2_python_sparse | src/alignment/SelectAndSplitAlignment.py | polyactis/vervet-web | train | 0 |
82a7e90cb7dc6f5dc4aeec82aec9b6cfa7d711bf | [
"s_map = super(VSCSIMapping, cls)._bld(adapter)\ns_map._client_lpar_href(cls.crt_related_href(adapter, None, client_lpar_uuid))\ns_map._client_adapter(stor.VClientStorageAdapterElement.bld(adapter, slot_num=lpar_slot_num))\ns_map._server_adapter(stor.VServerStorageAdapterElement.bld(adapter))\ns_map._set_stg_and_tg... | <|body_start_0|>
s_map = super(VSCSIMapping, cls)._bld(adapter)
s_map._client_lpar_href(cls.crt_related_href(adapter, None, client_lpar_uuid))
s_map._client_adapter(stor.VClientStorageAdapterElement.bld(adapter, slot_num=lpar_slot_num))
s_map._server_adapter(stor.VServerStorageAdapterEle... | The mapping of a VIOS SCSI adapter to the Client LPAR SCSI adapter. PowerVM provides a mechanism for Server/Client adapters to provide storage connectivity (for LPARs that do not have dedicated hardware). This mapping describes the Virtual I/O Server's Server SCSI Adapter and the Client LPAR's Client SCSI Adapter. To c... | VSCSIMapping | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VSCSIMapping:
"""The mapping of a VIOS SCSI adapter to the Client LPAR SCSI adapter. PowerVM provides a mechanism for Server/Client adapters to provide storage connectivity (for LPARs that do not have dedicated hardware). This mapping describes the Virtual I/O Server's Server SCSI Adapter and the... | stack_v2_sparse_classes_36k_train_026641 | 34,192 | permissive | [
{
"docstring": "Creates a new VSCSIMapping :param adapter: The pypowervm Adapter that will be used to create the mapping. :param host_uuid: Not used. :param client_lpar_uuid: The client LPAR's UUID. :param stg_ref: The backing storage element (PV, LU, VDisk, or VOptMedia) to use in the new mapping. :param lpar_... | 2 | null | Implement the Python class `VSCSIMapping` described below.
Class description:
The mapping of a VIOS SCSI adapter to the Client LPAR SCSI adapter. PowerVM provides a mechanism for Server/Client adapters to provide storage connectivity (for LPARs that do not have dedicated hardware). This mapping describes the Virtual I... | Implement the Python class `VSCSIMapping` described below.
Class description:
The mapping of a VIOS SCSI adapter to the Client LPAR SCSI adapter. PowerVM provides a mechanism for Server/Client adapters to provide storage connectivity (for LPARs that do not have dedicated hardware). This mapping describes the Virtual I... | 68f2b586b4f17489f379534ab52fc56a524b6da5 | <|skeleton|>
class VSCSIMapping:
"""The mapping of a VIOS SCSI adapter to the Client LPAR SCSI adapter. PowerVM provides a mechanism for Server/Client adapters to provide storage connectivity (for LPARs that do not have dedicated hardware). This mapping describes the Virtual I/O Server's Server SCSI Adapter and the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VSCSIMapping:
"""The mapping of a VIOS SCSI adapter to the Client LPAR SCSI adapter. PowerVM provides a mechanism for Server/Client adapters to provide storage connectivity (for LPARs that do not have dedicated hardware). This mapping describes the Virtual I/O Server's Server SCSI Adapter and the Client LPAR'... | the_stack_v2_python_sparse | pypowervm/wrappers/virtual_io_server.py | powervm/pypowervm | train | 25 |
2d64146a0001a1efb3e5e98209c9553d882e14b9 | [
"menu_item.MenuItem.__init__(self, main_menu, frame)\nself.create_menu_item_button('Help')\nself.menu_item_button['command'] = self.get_help_window",
"self.gui.active_window.hide()\nself.associated_window = help_window.HelpWindow(self.gui)\nself.gui.active_window = self.associated_window\nself.gui.active_window.s... | <|body_start_0|>
menu_item.MenuItem.__init__(self, main_menu, frame)
self.create_menu_item_button('Help')
self.menu_item_button['command'] = self.get_help_window
<|end_body_0|>
<|body_start_1|>
self.gui.active_window.hide()
self.associated_window = help_window.HelpWindow(self.gu... | This class is used to create a button that will bring the user to the Help menu. | HelpMenuItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HelpMenuItem:
"""This class is used to create a button that will bring the user to the Help menu."""
def __init__(self, main_menu, frame):
"""Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's active window"""... | stack_v2_sparse_classes_36k_train_026642 | 994 | no_license | [
{
"docstring": "Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's active window",
"name": "__init__",
"signature": "def __init__(self, main_menu, frame)"
},
{
"docstring": "This function will hide everything on the activ... | 2 | stack_v2_sparse_classes_30k_train_013438 | Implement the Python class `HelpMenuItem` described below.
Class description:
This class is used to create a button that will bring the user to the Help menu.
Method signatures and docstrings:
- def __init__(self, main_menu, frame): Args: main_menu ([]): this class must know about the main menu because it knows about... | Implement the Python class `HelpMenuItem` described below.
Class description:
This class is used to create a button that will bring the user to the Help menu.
Method signatures and docstrings:
- def __init__(self, main_menu, frame): Args: main_menu ([]): this class must know about the main menu because it knows about... | e26d9450b98fa0f372bcdf6eaf251a2c9dcba44e | <|skeleton|>
class HelpMenuItem:
"""This class is used to create a button that will bring the user to the Help menu."""
def __init__(self, main_menu, frame):
"""Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's active window"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HelpMenuItem:
"""This class is used to create a button that will bring the user to the Help menu."""
def __init__(self, main_menu, frame):
"""Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's active window"""
menu... | the_stack_v2_python_sparse | user_interface/menu_items/help_menu_item.py | pucheng-tan/WordFlow | train | 0 |
c8fd1208d7b8082d42de8cdaa90db36e81ba08f2 | [
"for i in range(2, len(cost)):\n cost[i] = min(cost[i - 2], cost[i - 1]) + cost[i]\nreturn min(cost[-2], cost[-1])",
"li = [0] * len(cost)\nli[0] = cost[0]\nli[1] = cost[1]\nfor i in range(2, len(cost)):\n li[i] = min(li[i - 2], li[i - 1]) + cost[i]\nreturn min(li[-2], li[-1])"
] | <|body_start_0|>
for i in range(2, len(cost)):
cost[i] = min(cost[i - 2], cost[i - 1]) + cost[i]
return min(cost[-2], cost[-1])
<|end_body_0|>
<|body_start_1|>
li = [0] * len(cost)
li[0] = cost[0]
li[1] = cost[1]
for i in range(2, len(cost)):
li[i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCostClimbingStairs(self, cost):
""":type cost: List[int] :rtype: int"""
<|body_0|>
def minCostClimbingStairs(self, cost):
""":type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in range(2, len(cos... | stack_v2_sparse_classes_36k_train_026643 | 671 | no_license | [
{
"docstring": ":type cost: List[int] :rtype: int",
"name": "minCostClimbingStairs",
"signature": "def minCostClimbingStairs(self, cost)"
},
{
"docstring": ":type cost: List[int] :rtype: int",
"name": "minCostClimbingStairs",
"signature": "def minCostClimbingStairs(self, cost)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010682 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCostClimbingStairs(self, cost): :type cost: List[int] :rtype: int
- def minCostClimbingStairs(self, cost): :type cost: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCostClimbingStairs(self, cost): :type cost: List[int] :rtype: int
- def minCostClimbingStairs(self, cost): :type cost: List[int] :rtype: int
<|skeleton|>
class Solution:
... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def minCostClimbingStairs(self, cost):
""":type cost: List[int] :rtype: int"""
<|body_0|>
def minCostClimbingStairs(self, cost):
""":type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minCostClimbingStairs(self, cost):
""":type cost: List[int] :rtype: int"""
for i in range(2, len(cost)):
cost[i] = min(cost[i - 2], cost[i - 1]) + cost[i]
return min(cost[-2], cost[-1])
def minCostClimbingStairs(self, cost):
""":type cost: List[in... | the_stack_v2_python_sparse | 0746_Min_Cost_Climbing_Stairs.py | bingli8802/leetcode | train | 0 | |
2609a035a46266bc98770a5f76ca9614773c5949 | [
"super().__init__()\nself.use_additional_convs = use_additional_convs\nself.convs1 = nn.LayerList()\nif use_additional_convs:\n self.convs2 = nn.LayerList()\nassert kernel_size % 2 == 1, 'Kernel size must be odd number.'\nfor dilation in dilations:\n self.convs1.append(nn.Sequential(get_activation(nonlinear_a... | <|body_start_0|>
super().__init__()
self.use_additional_convs = use_additional_convs
self.convs1 = nn.LayerList()
if use_additional_convs:
self.convs2 = nn.LayerList()
assert kernel_size % 2 == 1, 'Kernel size must be odd number.'
for dilation in dilations:
... | Residual block module in HiFiGAN. | HiFiGANResidualBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HiFiGANResidualBlock:
"""Residual block module in HiFiGAN."""
def __init__(self, kernel_size: int=3, channels: int=512, dilations: List[int]=(1, 3, 5), bias: bool=True, use_additional_convs: bool=True, nonlinear_activation: str='leakyrelu', nonlinear_activation_params: Dict[str, Any]={'negat... | stack_v2_sparse_classes_36k_train_026644 | 7,549 | permissive | [
{
"docstring": "Initialize HiFiGANResidualBlock module. Args: kernel_size (int): Kernel size of dilation convolution layer. channels (int): Number of channels for convolution layer. dilations (List[int]): List of dilation factors. use_additional_convs (bool): Whether to use additional convolution layers. bias (... | 2 | null | Implement the Python class `HiFiGANResidualBlock` described below.
Class description:
Residual block module in HiFiGAN.
Method signatures and docstrings:
- def __init__(self, kernel_size: int=3, channels: int=512, dilations: List[int]=(1, 3, 5), bias: bool=True, use_additional_convs: bool=True, nonlinear_activation: ... | Implement the Python class `HiFiGANResidualBlock` described below.
Class description:
Residual block module in HiFiGAN.
Method signatures and docstrings:
- def __init__(self, kernel_size: int=3, channels: int=512, dilations: List[int]=(1, 3, 5), bias: bool=True, use_additional_convs: bool=True, nonlinear_activation: ... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class HiFiGANResidualBlock:
"""Residual block module in HiFiGAN."""
def __init__(self, kernel_size: int=3, channels: int=512, dilations: List[int]=(1, 3, 5), bias: bool=True, use_additional_convs: bool=True, nonlinear_activation: str='leakyrelu', nonlinear_activation_params: Dict[str, Any]={'negat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HiFiGANResidualBlock:
"""Residual block module in HiFiGAN."""
def __init__(self, kernel_size: int=3, channels: int=512, dilations: List[int]=(1, 3, 5), bias: bool=True, use_additional_convs: bool=True, nonlinear_activation: str='leakyrelu', nonlinear_activation_params: Dict[str, Any]={'negative_slope': 0... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/residual_block.py | anniyanvr/DeepSpeech-1 | train | 0 |
38b926659961b81e1a6ec10aa7df54dbfd9905a4 | [
"info = s.split(' ')\ndirectory = info[0]\npattern = re.compile('\\\\((.*)\\\\)')\npattern2 = re.compile('(.*?)\\\\(')\nfor file in info[1:]:\n content = pattern.findall(file)[-1]\n filename = pattern2.findall(file)[-1]\n if m.get(content, None):\n m[content].append(directory + '/' + filename)\n ... | <|body_start_0|>
info = s.split(' ')
directory = info[0]
pattern = re.compile('\\((.*)\\)')
pattern2 = re.compile('(.*?)\\(')
for file in info[1:]:
content = pattern.findall(file)[-1]
filename = pattern2.findall(file)[-1]
if m.get(content, None... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def manager(self, s, m):
""":type s: str :type m: dict :return:"""
<|body_0|>
def findDuplicate(self, paths):
""":type paths: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
info = s.split(' ')
dir... | stack_v2_sparse_classes_36k_train_026645 | 1,255 | no_license | [
{
"docstring": ":type s: str :type m: dict :return:",
"name": "manager",
"signature": "def manager(self, s, m)"
},
{
"docstring": ":type paths: List[str] :rtype: List[List[str]]",
"name": "findDuplicate",
"signature": "def findDuplicate(self, paths)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def manager(self, s, m): :type s: str :type m: dict :return:
- def findDuplicate(self, paths): :type paths: List[str] :rtype: List[List[str]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def manager(self, s, m): :type s: str :type m: dict :return:
- def findDuplicate(self, paths): :type paths: List[str] :rtype: List[List[str]]
<|skeleton|>
class Solution:
d... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def manager(self, s, m):
""":type s: str :type m: dict :return:"""
<|body_0|>
def findDuplicate(self, paths):
""":type paths: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def manager(self, s, m):
""":type s: str :type m: dict :return:"""
info = s.split(' ')
directory = info[0]
pattern = re.compile('\\((.*)\\)')
pattern2 = re.compile('(.*?)\\(')
for file in info[1:]:
content = pattern.findall(file)[-1]
... | the_stack_v2_python_sparse | python/leetcode/609_Find_Duplicate_File_in_System.py | bobcaoge/my-code | train | 0 | |
65982469a75deba17041dc9aaa3c1d8e188eb7e0 | [
"def ser(cur, s):\n if not cur:\n return s + 'None,'\n else:\n string = ser(cur.left, s + str(cur.val) + ',')\n string = ser(cur.right, string)\n return string\ns = ser(root, '')\nreturn s",
"def deser(data):\n d = data.pop(0)\n if d == 'None':\n return None\n cur... | <|body_start_0|>
def ser(cur, s):
if not cur:
return s + 'None,'
else:
string = ser(cur.left, s + str(cur.val) + ',')
string = ser(cur.right, string)
return string
s = ser(root, '')
return s
<|end_body_0|>
<... | 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_026646 | 1,437 | 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:... | 2c534185854c1a6f5ffdb2698f9db9989f30a25b | <|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 ser(cur, s):
if not cur:
return s + 'None,'
else:
string = ser(cur.left, s + str(cur.val) + ',')
string = ser(... | the_stack_v2_python_sparse | Week 02/id_738/课堂题目实战/LeetCode_297_738.py | Carryours/algorithm004-03 | train | 2 | |
0de8590bd887722a697cbcbcdd3a37483f72f6bb | [
"questions = TranscriptionFeedbackQuestions.objects.all()\ncontext = {'story_id': story_id, 'questions': questions, 'session_id': session_id}\nreturn render(request, 'transcription/feedback.html', context)",
"change_score_by_constant = float(TranscriptionConfig.objects.get(name='CHANGE_SCORE_BY').config)\nyes_rat... | <|body_start_0|>
questions = TranscriptionFeedbackQuestions.objects.all()
context = {'story_id': story_id, 'questions': questions, 'session_id': session_id}
return render(request, 'transcription/feedback.html', context)
<|end_body_0|>
<|body_start_1|>
change_score_by_constant = float(Tr... | Renders the answers. Saves the logs for how the person answered and updates the values of what where they score is. | ShadowingFeedBack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShadowingFeedBack:
"""Renders the answers. Saves the logs for how the person answered and updates the values of what where they score is."""
def get(self, request, story_id, session_id):
"""Gets all the questions from the database for shadowing questions and puts it into a context to... | stack_v2_sparse_classes_36k_train_026647 | 8,687 | no_license | [
{
"docstring": "Gets all the questions from the database for shadowing questions and puts it into a context to show the user. :param request: :param story_id: :return:",
"name": "get",
"signature": "def get(self, request, story_id, session_id)"
},
{
"docstring": "Logs all the answers to the ques... | 2 | null | Implement the Python class `ShadowingFeedBack` described below.
Class description:
Renders the answers. Saves the logs for how the person answered and updates the values of what where they score is.
Method signatures and docstrings:
- def get(self, request, story_id, session_id): Gets all the questions from the datab... | Implement the Python class `ShadowingFeedBack` described below.
Class description:
Renders the answers. Saves the logs for how the person answered and updates the values of what where they score is.
Method signatures and docstrings:
- def get(self, request, story_id, session_id): Gets all the questions from the datab... | 174c8c6c9ecb2905830832419e9c332b4d8b13df | <|skeleton|>
class ShadowingFeedBack:
"""Renders the answers. Saves the logs for how the person answered and updates the values of what where they score is."""
def get(self, request, story_id, session_id):
"""Gets all the questions from the database for shadowing questions and puts it into a context to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShadowingFeedBack:
"""Renders the answers. Saves the logs for how the person answered and updates the values of what where they score is."""
def get(self, request, story_id, session_id):
"""Gets all the questions from the database for shadowing questions and puts it into a context to show the use... | the_stack_v2_python_sparse | CreeTutorBackEnd/transcription/views.py | EdTeKLA/Cree-Tutor | train | 0 |
d2b5c2f6a37c0fafee85c7c15176fc76d0f4d880 | [
"assert citName and end1 and end2\nosh = ObjectStateHolder(citName)\nosh.setAttribute('link_end1', end1)\nosh.setAttribute('link_end2', end2)\nreturn osh",
"if not who:\n raise ValueError('Who-OSH is not specified')\nif not whom:\n raise ValueError('Whom-OSH is not specified')\nreturn self.reportLink('conta... | <|body_start_0|>
assert citName and end1 and end2
osh = ObjectStateHolder(citName)
osh.setAttribute('link_end1', end1)
osh.setAttribute('link_end2', end2)
return osh
<|end_body_0|>
<|body_start_1|>
if not who:
raise ValueError('Who-OSH is not specified')
... | LinkReporter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkReporter:
def reportLink(self, citName, end1, end2):
"""Creates an C{ObjectStateHolder} class that represents a link. The link must be a valid link according to the class model. @types: str, ObjectStateHolder, ObjectStateHolder -> ObjectStateHolder @param citName: the name of the lin... | stack_v2_sparse_classes_36k_train_026648 | 7,537 | no_license | [
{
"docstring": "Creates an C{ObjectStateHolder} class that represents a link. The link must be a valid link according to the class model. @types: str, ObjectStateHolder, ObjectStateHolder -> ObjectStateHolder @param citName: the name of the link to create @param end1: the I{from} of the link @param end2: the I{... | 3 | null | Implement the Python class `LinkReporter` described below.
Class description:
Implement the LinkReporter class.
Method signatures and docstrings:
- def reportLink(self, citName, end1, end2): Creates an C{ObjectStateHolder} class that represents a link. The link must be a valid link according to the class model. @type... | Implement the Python class `LinkReporter` described below.
Class description:
Implement the LinkReporter class.
Method signatures and docstrings:
- def reportLink(self, citName, end1, end2): Creates an C{ObjectStateHolder} class that represents a link. The link must be a valid link according to the class model. @type... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class LinkReporter:
def reportLink(self, citName, end1, end2):
"""Creates an C{ObjectStateHolder} class that represents a link. The link must be a valid link according to the class model. @types: str, ObjectStateHolder, ObjectStateHolder -> ObjectStateHolder @param citName: the name of the lin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkReporter:
def reportLink(self, citName, end1, end2):
"""Creates an C{ObjectStateHolder} class that represents a link. The link must be a valid link according to the class model. @types: str, ObjectStateHolder, ObjectStateHolder -> ObjectStateHolder @param citName: the name of the link to create @p... | the_stack_v2_python_sparse | reference/ucmdb/discovery/plugins_bobj_service.py | madmonkyang/cda-record | train | 0 | |
0956654df916daed62cfaa1b2f71405d263746fb | [
"self._consensus_address = '0x0000000000000000000000000000000000001003'\nself.contract_name = 'Consensus'\nself.gasPrice = 300000000\nself.client = transaction_common.TransactionCommon(self._consensus_address, contract_path, self.contract_name)",
"common.check_nodeId(nodeId)\nfn_name = 'addSealer'\nfn_args = [nod... | <|body_start_0|>
self._consensus_address = '0x0000000000000000000000000000000000001003'
self.contract_name = 'Consensus'
self.gasPrice = 300000000
self.client = transaction_common.TransactionCommon(self._consensus_address, contract_path, self.contract_name)
<|end_body_0|>
<|body_start_1... | implementation of ConsensusPrecompile | ConsensusPrecompile | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsensusPrecompile:
"""implementation of ConsensusPrecompile"""
def __init__(self, contract_path):
"""init the address for Consensus contract"""
<|body_0|>
def addSealer(self, nodeId):
"""addSealer"""
<|body_1|>
def addObserver(self, nodeId):
... | stack_v2_sparse_classes_36k_train_026649 | 2,141 | permissive | [
{
"docstring": "init the address for Consensus contract",
"name": "__init__",
"signature": "def __init__(self, contract_path)"
},
{
"docstring": "addSealer",
"name": "addSealer",
"signature": "def addSealer(self, nodeId)"
},
{
"docstring": "addObserver",
"name": "addObserver"... | 4 | null | Implement the Python class `ConsensusPrecompile` described below.
Class description:
implementation of ConsensusPrecompile
Method signatures and docstrings:
- def __init__(self, contract_path): init the address for Consensus contract
- def addSealer(self, nodeId): addSealer
- def addObserver(self, nodeId): addObserve... | Implement the Python class `ConsensusPrecompile` described below.
Class description:
implementation of ConsensusPrecompile
Method signatures and docstrings:
- def __init__(self, contract_path): init the address for Consensus contract
- def addSealer(self, nodeId): addSealer
- def addObserver(self, nodeId): addObserve... | 5fa6cc416b604de4bbd0d2407f36ed286d67a792 | <|skeleton|>
class ConsensusPrecompile:
"""implementation of ConsensusPrecompile"""
def __init__(self, contract_path):
"""init the address for Consensus contract"""
<|body_0|>
def addSealer(self, nodeId):
"""addSealer"""
<|body_1|>
def addObserver(self, nodeId):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConsensusPrecompile:
"""implementation of ConsensusPrecompile"""
def __init__(self, contract_path):
"""init the address for Consensus contract"""
self._consensus_address = '0x0000000000000000000000000000000000001003'
self.contract_name = 'Consensus'
self.gasPrice = 3000000... | the_stack_v2_python_sparse | client/precompile/consensus/consensus_precompile.py | FISCO-BCOS/python-sdk | train | 68 |
59f877dbd0b64b2215ee2fae2fdac8a1133d29bd | [
"self.capacity = k\nself.queue = nums\nheapq.heapify(self.queue)",
"heapq.heappush(self.queue, val)\nif len(self.queue) > self.capacity:\n heapq.heappop(self.queue)\nreturn self.queue[0]"
] | <|body_start_0|>
self.capacity = k
self.queue = nums
heapq.heapify(self.queue)
<|end_body_0|>
<|body_start_1|>
heapq.heappush(self.queue, val)
if len(self.queue) > self.capacity:
heapq.heappop(self.queue)
return self.queue[0]
<|end_body_1|>
| KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.capacity = k
self.queue = nums
heapq.... | stack_v2_sparse_classes_36k_train_026650 | 677 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | null | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 441c8e1c090c44f578fdabaf1aba4bb4c6c4a597 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.capacity = k
self.queue = nums
heapq.heapify(self.queue)
def add(self, val):
""":type val: int :rtype: int"""
heapq.heappush(self.queue, val)
if len(self.queue) >... | the_stack_v2_python_sparse | python/703.py | NOI-X/leetcode-solution | train | 0 | |
1f75b1b043d4103464823deadfcb338b7ffeac65 | [
"docs = list(map(Document, items))\nfor d in docs:\n self.store[d.hid] = d\ndocs_id = list(map(lambda d: d.hid, docs))\nChain.multi_add(self, docs_id)",
"item = Chain.get(self, block_index, item_index, evidence)\nd = self.store[item]\ncheck_hash(item, d)\nif evidence != None:\n evidence[d.hid] = d\nreturn s... | <|body_start_0|>
docs = list(map(Document, items))
for d in docs:
self.store[d.hid] = d
docs_id = list(map(lambda d: d.hid, docs))
Chain.multi_add(self, docs_id)
<|end_body_0|>
<|body_start_1|>
item = Chain.get(self, block_index, item_index, evidence)
d = sel... | A chain that stores hashes of documents. Construct like a *Chain*. | DocChain | [
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocChain:
"""A chain that stores hashes of documents. Construct like a *Chain*."""
def multi_add(self, items):
"""Add multiple items to seal a new block."""
<|body_0|>
def get(self, block_index, item_index, evidence=None):
"""Get a sealed item, and optionally a b... | stack_v2_sparse_classes_36k_train_026651 | 5,983 | permissive | [
{
"docstring": "Add multiple items to seal a new block.",
"name": "multi_add",
"signature": "def multi_add(self, items)"
},
{
"docstring": "Get a sealed item, and optionally a bundle of evidence.",
"name": "get",
"signature": "def get(self, block_index, item_index, evidence=None)"
},
... | 3 | null | Implement the Python class `DocChain` described below.
Class description:
A chain that stores hashes of documents. Construct like a *Chain*.
Method signatures and docstrings:
- def multi_add(self, items): Add multiple items to seal a new block.
- def get(self, block_index, item_index, evidence=None): Get a sealed ite... | Implement the Python class `DocChain` described below.
Class description:
A chain that stores hashes of documents. Construct like a *Chain*.
Method signatures and docstrings:
- def multi_add(self, items): Add multiple items to seal a new block.
- def get(self, block_index, item_index, evidence=None): Get a sealed ite... | 881fe3e9aac89f42eb7877b480498f910aa37d22 | <|skeleton|>
class DocChain:
"""A chain that stores hashes of documents. Construct like a *Chain*."""
def multi_add(self, items):
"""Add multiple items to seal a new block."""
<|body_0|>
def get(self, block_index, item_index, evidence=None):
"""Get a sealed item, and optionally a b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DocChain:
"""A chain that stores hashes of documents. Construct like a *Chain*."""
def multi_add(self, items):
"""Add multiple items to seal a new block."""
docs = list(map(Document, items))
for d in docs:
self.store[d.hid] = d
docs_id = list(map(lambda d: d.hi... | the_stack_v2_python_sparse | hippiehug-package/hippiehug/Chain.py | FrancisPouliot/rousseau-chain | train | 0 |
da8091bc1649b808f9ee65dfd57b4e3bb34ecb64 | [
"ops = block_string.split('_')\noptions = {}\nfor op in ops:\n splits = re.split('(\\\\d.*)', op)\n if len(splits) >= 2:\n key, value = splits[:2]\n options[key] = value\nstride_check = 's' in options and len(options['s']) == 1 or (len(options['s']) == 2 and options['s'][0] == options['s'][1]) o... | <|body_start_0|>
ops = block_string.split('_')
options = {}
for op in ops:
splits = re.split('(\\d.*)', op)
if len(splits) >= 2:
key, value = splits[:2]
options[key] = value
stride_check = 's' in options and len(options['s']) == 1 o... | BlockArgs object to assist in decoding string notation of arguments for MBConvBlock definition. | BlockArgs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlockArgs:
"""BlockArgs object to assist in decoding string notation of arguments for MBConvBlock definition."""
def from_string(block_string: str):
"""Get a BlockArgs object from a string notation of arguments. Args: block_string (str): A string notation of arguments. Examples: "r1_... | stack_v2_sparse_classes_36k_train_026652 | 40,667 | permissive | [
{
"docstring": "Get a BlockArgs object from a string notation of arguments. Args: block_string (str): A string notation of arguments. Examples: \"r1_k3_s11_e1_i32_o16_se0.25\". Returns: BlockArgs: namedtuple defined at the top of this function.",
"name": "from_string",
"signature": "def from_string(bloc... | 2 | stack_v2_sparse_classes_30k_train_018114 | Implement the Python class `BlockArgs` described below.
Class description:
BlockArgs object to assist in decoding string notation of arguments for MBConvBlock definition.
Method signatures and docstrings:
- def from_string(block_string: str): Get a BlockArgs object from a string notation of arguments. Args: block_str... | Implement the Python class `BlockArgs` described below.
Class description:
BlockArgs object to assist in decoding string notation of arguments for MBConvBlock definition.
Method signatures and docstrings:
- def from_string(block_string: str): Get a BlockArgs object from a string notation of arguments. Args: block_str... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class BlockArgs:
"""BlockArgs object to assist in decoding string notation of arguments for MBConvBlock definition."""
def from_string(block_string: str):
"""Get a BlockArgs object from a string notation of arguments. Args: block_string (str): A string notation of arguments. Examples: "r1_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlockArgs:
"""BlockArgs object to assist in decoding string notation of arguments for MBConvBlock definition."""
def from_string(block_string: str):
"""Get a BlockArgs object from a string notation of arguments. Args: block_string (str): A string notation of arguments. Examples: "r1_k3_s11_e1_i32... | the_stack_v2_python_sparse | monai/networks/nets/efficientnet.py | Project-MONAI/MONAI | train | 4,805 |
d6799115a341033dea184e5be5325fc47309f0ed | [
"self.graph = graph\nself.weight = weight\nself.threshold = threshold\nself.distance = dict(nx.all_pairs_dijkstra_path_length(self.graph, weight=self.weight))",
"assert metric in ['ndtw', 'sdtw', 'dtw']\ndtw_matrix = np.inf * np.ones((len(prediction) + 1, len(reference) + 1))\ndtw_matrix[0][0] = 0\nfor i in range... | <|body_start_0|>
self.graph = graph
self.weight = weight
self.threshold = threshold
self.distance = dict(nx.all_pairs_dijkstra_path_length(self.graph, weight=self.weight))
<|end_body_0|>
<|body_start_1|>
assert metric in ['ndtw', 'sdtw', 'dtw']
dtw_matrix = np.inf * np.o... | Dynamic Time Warping (DTW) evaluation metrics. Python doctest: >>> graph = nx.grid_graph([3, 4]) >>> prediction = [(0, 0), (1, 0), (2, 0), (3, 0)] >>> reference = [(0, 0), (1, 0), (2, 1), (3, 2)] >>> dtw = DTW(graph) >>> assert np.isclose(dtw(prediction, reference, 'dtw'), 3.0) >>> assert np.isclose(dtw(prediction, ref... | DTW | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DTW:
"""Dynamic Time Warping (DTW) evaluation metrics. Python doctest: >>> graph = nx.grid_graph([3, 4]) >>> prediction = [(0, 0), (1, 0), (2, 0), (3, 0)] >>> reference = [(0, 0), (1, 0), (2, 1), (3, 2)] >>> dtw = DTW(graph) >>> assert np.isclose(dtw(prediction, reference, 'dtw'), 3.0) >>> assert... | stack_v2_sparse_classes_36k_train_026653 | 2,866 | permissive | [
{
"docstring": "Initializes a DTW object. Args: graph: networkx graph for the environment. weight: networkx edge weight key (str). threshold: distance threshold $d_{th}$ (float).",
"name": "__init__",
"signature": "def __init__(self, graph, weight='weight', threshold=3.0)"
},
{
"docstring": "Com... | 2 | null | Implement the Python class `DTW` described below.
Class description:
Dynamic Time Warping (DTW) evaluation metrics. Python doctest: >>> graph = nx.grid_graph([3, 4]) >>> prediction = [(0, 0), (1, 0), (2, 0), (3, 0)] >>> reference = [(0, 0), (1, 0), (2, 1), (3, 2)] >>> dtw = DTW(graph) >>> assert np.isclose(dtw(predict... | Implement the Python class `DTW` described below.
Class description:
Dynamic Time Warping (DTW) evaluation metrics. Python doctest: >>> graph = nx.grid_graph([3, 4]) >>> prediction = [(0, 0), (1, 0), (2, 0), (3, 0)] >>> reference = [(0, 0), (1, 0), (2, 1), (3, 2)] >>> dtw = DTW(graph) >>> assert np.isclose(dtw(predict... | dea327aa9e7ef7f7bca5a6c225dbdca1077a06e9 | <|skeleton|>
class DTW:
"""Dynamic Time Warping (DTW) evaluation metrics. Python doctest: >>> graph = nx.grid_graph([3, 4]) >>> prediction = [(0, 0), (1, 0), (2, 0), (3, 0)] >>> reference = [(0, 0), (1, 0), (2, 1), (3, 2)] >>> dtw = DTW(graph) >>> assert np.isclose(dtw(prediction, reference, 'dtw'), 3.0) >>> assert... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DTW:
"""Dynamic Time Warping (DTW) evaluation metrics. Python doctest: >>> graph = nx.grid_graph([3, 4]) >>> prediction = [(0, 0), (1, 0), (2, 0), (3, 0)] >>> reference = [(0, 0), (1, 0), (2, 1), (3, 2)] >>> dtw = DTW(graph) >>> assert np.isclose(dtw(prediction, reference, 'dtw'), 3.0) >>> assert np.isclose(d... | the_stack_v2_python_sparse | r4r/dtw.py | Tarkiyah/googleResearch | train | 11 |
d84bd57e7fa0398b7d9e5527445e0f30c6951980 | [
"if item in self:\n return super(_LoadedConfigs, self).__getitem__(item)\naddon = item.replace('_config', '')\nif addon in ValidAddons.all:\n import_path = 'gungame51.scripts.%s.%s.%s' % (ValidAddons.get_addon_type(addon), addon, item)\nelif _base_configs.joinpath(item + '.py').isfile():\n import_path = 'g... | <|body_start_0|>
if item in self:
return super(_LoadedConfigs, self).__getitem__(item)
addon = item.replace('_config', '')
if addon in ValidAddons.all:
import_path = 'gungame51.scripts.%s.%s.%s' % (ValidAddons.get_addon_type(addon), addon, item)
elif _base_configs... | Class used to store loaded config files | _LoadedConfigs | [
"Artistic-1.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _LoadedConfigs:
"""Class used to store loaded config files"""
def __getitem__(self, item):
"""Verify that the given item is a config file instance and store it"""
<|body_0|>
def clear(self):
"""Unloads all configs within the dicionary"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_026654 | 2,849 | permissive | [
{
"docstring": "Verify that the given item is a config file instance and store it",
"name": "__getitem__",
"signature": "def __getitem__(self, item)"
},
{
"docstring": "Unloads all configs within the dicionary",
"name": "clear",
"signature": "def clear(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013476 | Implement the Python class `_LoadedConfigs` described below.
Class description:
Class used to store loaded config files
Method signatures and docstrings:
- def __getitem__(self, item): Verify that the given item is a config file instance and store it
- def clear(self): Unloads all configs within the dicionary | Implement the Python class `_LoadedConfigs` described below.
Class description:
Class used to store loaded config files
Method signatures and docstrings:
- def __getitem__(self, item): Verify that the given item is a config file instance and store it
- def clear(self): Unloads all configs within the dicionary
<|skel... | ebf4624626266f552189a32612b8d09cd5b4c5a3 | <|skeleton|>
class _LoadedConfigs:
"""Class used to store loaded config files"""
def __getitem__(self, item):
"""Verify that the given item is a config file instance and store it"""
<|body_0|>
def clear(self):
"""Unloads all configs within the dicionary"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _LoadedConfigs:
"""Class used to store loaded config files"""
def __getitem__(self, item):
"""Verify that the given item is a config file instance and store it"""
if item in self:
return super(_LoadedConfigs, self).__getitem__(item)
addon = item.replace('_config', '')
... | the_stack_v2_python_sparse | cstrike/addons/eventscripts/gungame51/core/cfg/loaded.py | GunGame-Dev-Team/GunGame51 | train | 0 |
f58c08ea38b41ddea754e06fbbbcca2488828904 | [
"for k in list(orig_dict.keys()):\n if k not in keys_whitelist:\n del orig_dict[k]\nfor v in orig_dict.values():\n if isinstance(v, dict):\n self.delete_keys_from_dict(v, keys_whitelist)\nreturn orig_dict",
"if not self.fields:\n raise ImproperlyConfigured('fields attribute must be specifie... | <|body_start_0|>
for k in list(orig_dict.keys()):
if k not in keys_whitelist:
del orig_dict[k]
for v in orig_dict.values():
if isinstance(v, dict):
self.delete_keys_from_dict(v, keys_whitelist)
return orig_dict
<|end_body_0|>
<|body_start_... | GenericCSVRenderer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericCSVRenderer:
def delete_keys_from_dict(self, orig_dict, keys_whitelist):
"""recursively delete keys which are not in whitelist from dict"""
<|body_0|>
def render(self, data, media_type=None, renderer_context=None, writer_opts=None):
"""extract the array from r... | stack_v2_sparse_classes_36k_train_026655 | 1,211 | permissive | [
{
"docstring": "recursively delete keys which are not in whitelist from dict",
"name": "delete_keys_from_dict",
"signature": "def delete_keys_from_dict(self, orig_dict, keys_whitelist)"
},
{
"docstring": "extract the array from results field & remove fields which were not specified in whitelist"... | 2 | stack_v2_sparse_classes_30k_train_016170 | Implement the Python class `GenericCSVRenderer` described below.
Class description:
Implement the GenericCSVRenderer class.
Method signatures and docstrings:
- def delete_keys_from_dict(self, orig_dict, keys_whitelist): recursively delete keys which are not in whitelist from dict
- def render(self, data, media_type=N... | Implement the Python class `GenericCSVRenderer` described below.
Class description:
Implement the GenericCSVRenderer class.
Method signatures and docstrings:
- def delete_keys_from_dict(self, orig_dict, keys_whitelist): recursively delete keys which are not in whitelist from dict
- def render(self, data, media_type=N... | cf9ab30c67523062e1a3e0b8ff1b7b5ba4c8586f | <|skeleton|>
class GenericCSVRenderer:
def delete_keys_from_dict(self, orig_dict, keys_whitelist):
"""recursively delete keys which are not in whitelist from dict"""
<|body_0|>
def render(self, data, media_type=None, renderer_context=None, writer_opts=None):
"""extract the array from r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenericCSVRenderer:
def delete_keys_from_dict(self, orig_dict, keys_whitelist):
"""recursively delete keys which are not in whitelist from dict"""
for k in list(orig_dict.keys()):
if k not in keys_whitelist:
del orig_dict[k]
for v in orig_dict.values():
... | the_stack_v2_python_sparse | server/server/utils/renderers.py | jeremyhakoune/connective | train | 0 | |
9bec828aff3b6cd5cfe8c4ab3089e8f6474e97f6 | [
"super(Critic, self).__init__()\nself.state_dim = state_dim\nself.action_dim = action_dim\nself.fcs1 = nn.Linear(state_dim, 256)\nself.fcs1.weight.data = fanin_init(self.fcs1.weight.data.size())\nself.fcs2 = nn.Linear(256, 128)\nself.fcs2.weight.data = fanin_init(self.fcs2.weight.data.size())\nself.fca1 = nn.Linear... | <|body_start_0|>
super(Critic, self).__init__()
self.state_dim = state_dim
self.action_dim = action_dim
self.fcs1 = nn.Linear(state_dim, 256)
self.fcs1.weight.data = fanin_init(self.fcs1.weight.data.size())
self.fcs2 = nn.Linear(256, 128)
self.fcs2.weight.data = f... | Critic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Critic:
def __init__(self, state_dim, action_dim):
""":param state_dim: Dimension of input state (int) :param action_dim: Dimension of input action (int) :return:"""
<|body_0|>
def forward(self, state, action):
"""returns Value function Q(s,a) obtained from critic ne... | stack_v2_sparse_classes_36k_train_026656 | 3,144 | no_license | [
{
"docstring": ":param state_dim: Dimension of input state (int) :param action_dim: Dimension of input action (int) :return:",
"name": "__init__",
"signature": "def __init__(self, state_dim, action_dim)"
},
{
"docstring": "returns Value function Q(s,a) obtained from critic network :param state: ... | 2 | stack_v2_sparse_classes_30k_train_007119 | Implement the Python class `Critic` described below.
Class description:
Implement the Critic class.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim): :param state_dim: Dimension of input state (int) :param action_dim: Dimension of input action (int) :return:
- def forward(self, state, act... | Implement the Python class `Critic` described below.
Class description:
Implement the Critic class.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim): :param state_dim: Dimension of input state (int) :param action_dim: Dimension of input action (int) :return:
- def forward(self, state, act... | ffb9e53eeff011c4d3d5933a60c2b65fdbb18e2a | <|skeleton|>
class Critic:
def __init__(self, state_dim, action_dim):
""":param state_dim: Dimension of input state (int) :param action_dim: Dimension of input action (int) :return:"""
<|body_0|>
def forward(self, state, action):
"""returns Value function Q(s,a) obtained from critic ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Critic:
def __init__(self, state_dim, action_dim):
""":param state_dim: Dimension of input state (int) :param action_dim: Dimension of input action (int) :return:"""
super(Critic, self).__init__()
self.state_dim = state_dim
self.action_dim = action_dim
self.fcs1 = nn.Li... | the_stack_v2_python_sparse | model/VNet.py | SamPlvs/reinforcement_learning_pytorch | train | 0 | |
34c1c697af0bca8405d489a6451088e9b9c6bb3b | [
"self.preprocessors = preprocessors\nif self.preprocessors is None:\n self.preprocessors = list()",
"data = list()\nlabels = list()\nfor i, imagepath in enumerate(imagepaths):\n image = cv2.imread(imagepath)\n label = imagepath.split(os.path.sep)[-2]\n if self.preprocessors is not None:\n for p... | <|body_start_0|>
self.preprocessors = preprocessors
if self.preprocessors is None:
self.preprocessors = list()
<|end_body_0|>
<|body_start_1|>
data = list()
labels = list()
for i, imagepath in enumerate(imagepaths):
image = cv2.imread(imagepath)
... | Load image | SimpleDatasetLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleDatasetLoader:
"""Load image"""
def __init__(self, preprocessors=None):
"""Store the image preprocessor"""
<|body_0|>
def load(self, imagepaths, verbose=-1):
"""images and labels loading"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self... | stack_v2_sparse_classes_36k_train_026657 | 2,737 | no_license | [
{
"docstring": "Store the image preprocessor",
"name": "__init__",
"signature": "def __init__(self, preprocessors=None)"
},
{
"docstring": "images and labels loading",
"name": "load",
"signature": "def load(self, imagepaths, verbose=-1)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000777 | Implement the Python class `SimpleDatasetLoader` described below.
Class description:
Load image
Method signatures and docstrings:
- def __init__(self, preprocessors=None): Store the image preprocessor
- def load(self, imagepaths, verbose=-1): images and labels loading | Implement the Python class `SimpleDatasetLoader` described below.
Class description:
Load image
Method signatures and docstrings:
- def __init__(self, preprocessors=None): Store the image preprocessor
- def load(self, imagepaths, verbose=-1): images and labels loading
<|skeleton|>
class SimpleDatasetLoader:
"""L... | 7e6253141468480d4beb3cbc982961862acd876f | <|skeleton|>
class SimpleDatasetLoader:
"""Load image"""
def __init__(self, preprocessors=None):
"""Store the image preprocessor"""
<|body_0|>
def load(self, imagepaths, verbose=-1):
"""images and labels loading"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleDatasetLoader:
"""Load image"""
def __init__(self, preprocessors=None):
"""Store the image preprocessor"""
self.preprocessors = preprocessors
if self.preprocessors is None:
self.preprocessors = list()
def load(self, imagepaths, verbose=-1):
"""images... | the_stack_v2_python_sparse | basic/7-knn/data_tools.py | j-bd/computer_vision_course | train | 0 |
475bf52730ecbcdabcb36c14bf5a9c089e361a53 | [
"n = 0\nfor i, c in enumerate(S):\n if c.isdigit():\n n = n * int(c)\n else:\n n += 1\nfor j in range(i, -1, -1):\n c = S[j]\n if c.isdigit():\n n //= int(c)\n K %= n\n else:\n if K == n or K == 0:\n return c\n n -= 1",
"tmp = ''\nfor c in S:\n ... | <|body_start_0|>
n = 0
for i, c in enumerate(S):
if c.isdigit():
n = n * int(c)
else:
n += 1
for j in range(i, -1, -1):
c = S[j]
if c.isdigit():
n //= int(c)
K %= n
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def decodeAtIndex(self, S, K):
""":type S: str :type K: int :rtype: str"""
<|body_0|>
def decodeAtIndex_own_MLE(self, S, K):
""":type S: str :type K: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = 0
for i, c in... | stack_v2_sparse_classes_36k_train_026658 | 949 | no_license | [
{
"docstring": ":type S: str :type K: int :rtype: str",
"name": "decodeAtIndex",
"signature": "def decodeAtIndex(self, S, K)"
},
{
"docstring": ":type S: str :type K: int :rtype: str",
"name": "decodeAtIndex_own_MLE",
"signature": "def decodeAtIndex_own_MLE(self, S, K)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000913 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeAtIndex(self, S, K): :type S: str :type K: int :rtype: str
- def decodeAtIndex_own_MLE(self, S, K): :type S: str :type K: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeAtIndex(self, S, K): :type S: str :type K: int :rtype: str
- def decodeAtIndex_own_MLE(self, S, K): :type S: str :type K: int :rtype: str
<|skeleton|>
class Solution:
... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def decodeAtIndex(self, S, K):
""":type S: str :type K: int :rtype: str"""
<|body_0|>
def decodeAtIndex_own_MLE(self, S, K):
""":type S: str :type K: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def decodeAtIndex(self, S, K):
""":type S: str :type K: int :rtype: str"""
n = 0
for i, c in enumerate(S):
if c.isdigit():
n = n * int(c)
else:
n += 1
for j in range(i, -1, -1):
c = S[j]
i... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetcodePythonProject/leetcode_0851_0900/LeetCode0880_DecodedStringAtIndex.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
0fbd5d6c3f5adfcb49d94d476df4a940202127f9 | [
"self.target = os.path.realpath(target_filename)\nself.tmpdir = os.path.dirname(self.target)\nself.append = append\numask = os.umask(0)\nos.umask(umask)\nself.mode = mode & ~umask",
"self.tempfile = tempfile.NamedTemporaryFile(dir=self.tmpdir, delete=False)\nself.tempname = self.tempfile.name\nos.chmod(self.tempn... | <|body_start_0|>
self.target = os.path.realpath(target_filename)
self.tmpdir = os.path.dirname(self.target)
self.append = append
umask = os.umask(0)
os.umask(umask)
self.mode = mode & ~umask
<|end_body_0|>
<|body_start_1|>
self.tempfile = tempfile.NamedTemporaryF... | Write to a given file using a temporary file and then rename it to the target file. This renaming should be atomic on modern operating systems. Therefore, this class can be used to avoid race conditions when a file might be read while it is being written. It also avoids having partially written files due to exceptions ... | atomic_write | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class atomic_write:
"""Write to a given file using a temporary file and then rename it to the target file. This renaming should be atomic on modern operating systems. Therefore, this class can be used to avoid race conditions when a file might be read while it is being written. It also avoids having pa... | stack_v2_sparse_classes_36k_train_026659 | 13,747 | no_license | [
{
"docstring": "TESTS:: sage: from sage.misc.temporary_file import atomic_write sage: link_to_target = os.path.join(tmp_dir(), \"templink\") sage: os.symlink(\"/foobar\", link_to_target) sage: aw = atomic_write(link_to_target) sage: print(aw.target) /foobar sage: print(aw.tmpdir) /",
"name": "__init__",
... | 3 | null | Implement the Python class `atomic_write` described below.
Class description:
Write to a given file using a temporary file and then rename it to the target file. This renaming should be atomic on modern operating systems. Therefore, this class can be used to avoid race conditions when a file might be read while it is ... | Implement the Python class `atomic_write` described below.
Class description:
Write to a given file using a temporary file and then rename it to the target file. This renaming should be atomic on modern operating systems. Therefore, this class can be used to avoid race conditions when a file might be read while it is ... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class atomic_write:
"""Write to a given file using a temporary file and then rename it to the target file. This renaming should be atomic on modern operating systems. Therefore, this class can be used to avoid race conditions when a file might be read while it is being written. It also avoids having pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class atomic_write:
"""Write to a given file using a temporary file and then rename it to the target file. This renaming should be atomic on modern operating systems. Therefore, this class can be used to avoid race conditions when a file might be read while it is being written. It also avoids having partially writt... | the_stack_v2_python_sparse | sage/src/sage/misc/temporary_file.py | bopopescu/geosci | train | 0 |
bb978a4a03a661295a7e8dc58aa2b91502ddf3f5 | [
"if not isinstance(tseries, self.__supported_types):\n raise TypeError('Unsupported time series object. Try Pandas Series, NumPy array or list.')\nself.N = len(tseries)\nif not 2 <= L <= self.N / 2:\n raise ValueError('The window length must be in the interval [2, N/2].')\nself.L = L\nself.orig_TS = pd.Series... | <|body_start_0|>
if not isinstance(tseries, self.__supported_types):
raise TypeError('Unsupported time series object. Try Pandas Series, NumPy array or list.')
self.N = len(tseries)
if not 2 <= L <= self.N / 2:
raise ValueError('The window length must be in the interval [... | SSA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSA:
def __init__(self, tseries, L, save_mem=True):
"""Decomposes the given time series with a singular-spectrum analysis. Assumes the values of the time series are recorded at equal intervals. Parameters ---------- tseries : The original time series, in the form of a Pandas Series, NumP... | stack_v2_sparse_classes_36k_train_026660 | 36,658 | no_license | [
{
"docstring": "Decomposes the given time series with a singular-spectrum analysis. Assumes the values of the time series are recorded at equal intervals. Parameters ---------- tseries : The original time series, in the form of a Pandas Series, NumPy array or list. L : The window length. Must be an integer 2 <=... | 5 | stack_v2_sparse_classes_30k_train_002187 | Implement the Python class `SSA` described below.
Class description:
Implement the SSA class.
Method signatures and docstrings:
- def __init__(self, tseries, L, save_mem=True): Decomposes the given time series with a singular-spectrum analysis. Assumes the values of the time series are recorded at equal intervals. Pa... | Implement the Python class `SSA` described below.
Class description:
Implement the SSA class.
Method signatures and docstrings:
- def __init__(self, tseries, L, save_mem=True): Decomposes the given time series with a singular-spectrum analysis. Assumes the values of the time series are recorded at equal intervals. Pa... | 215ac4d16d21d07e87964fe9a97a5bf36f4c7d64 | <|skeleton|>
class SSA:
def __init__(self, tseries, L, save_mem=True):
"""Decomposes the given time series with a singular-spectrum analysis. Assumes the values of the time series are recorded at equal intervals. Parameters ---------- tseries : The original time series, in the form of a Pandas Series, NumP... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSA:
def __init__(self, tseries, L, save_mem=True):
"""Decomposes the given time series with a singular-spectrum analysis. Assumes the values of the time series are recorded at equal intervals. Parameters ---------- tseries : The original time series, in the form of a Pandas Series, NumPy array or lis... | the_stack_v2_python_sparse | kaggle/python_files/sample86.py | SocioProphet/CodeGraph | train | 0 | |
974d93b6bd0a0499c22650e0051c10ee10c55c46 | [
"super(NeRS, self).__init__()\nself.nodes = nodes\nreturn",
"if parameters is not None:\n addresses = parameters.nodes.parameters\n if type(addresses) is StringType:\n addresses = [addresses]\n for address in addresses:\n self.logger.info(\"Enabling: '{0}'\".format(address))\n self.n... | <|body_start_0|>
super(NeRS, self).__init__()
self.nodes = nodes
return
<|end_body_0|>
<|body_start_1|>
if parameters is not None:
addresses = parameters.nodes.parameters
if type(addresses) is StringType:
addresses = [addresses]
for ad... | A Networked Radio Switch to enable and disable radios over the network. | NeRS | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeRS:
"""A Networked Radio Switch to enable and disable radios over the network."""
def __init__(self, nodes):
""":param: - `nodes`: A dictionary of <address>:Wifi enabler/disabler"""
<|body_0|>
def __call__(self, parameters=None):
""":param: - `parameters`: name... | stack_v2_sparse_classes_36k_train_026661 | 1,490 | permissive | [
{
"docstring": ":param: - `nodes`: A dictionary of <address>:Wifi enabler/disabler",
"name": "__init__",
"signature": "def __init__(self, nodes)"
},
{
"docstring": ":param: - `parameters`: namedtuple with `.ners.parameters` List of addresses (node-keys) to turn on. :postconditions: - `enable_wif... | 2 | null | Implement the Python class `NeRS` described below.
Class description:
A Networked Radio Switch to enable and disable radios over the network.
Method signatures and docstrings:
- def __init__(self, nodes): :param: - `nodes`: A dictionary of <address>:Wifi enabler/disabler
- def __call__(self, parameters=None): :param:... | Implement the Python class `NeRS` described below.
Class description:
A Networked Radio Switch to enable and disable radios over the network.
Method signatures and docstrings:
- def __init__(self, nodes): :param: - `nodes`: A dictionary of <address>:Wifi enabler/disabler
- def __call__(self, parameters=None): :param:... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class NeRS:
"""A Networked Radio Switch to enable and disable radios over the network."""
def __init__(self, nodes):
""":param: - `nodes`: A dictionary of <address>:Wifi enabler/disabler"""
<|body_0|>
def __call__(self, parameters=None):
""":param: - `parameters`: name... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NeRS:
"""A Networked Radio Switch to enable and disable radios over the network."""
def __init__(self, nodes):
""":param: - `nodes`: A dictionary of <address>:Wifi enabler/disabler"""
super(NeRS, self).__init__()
self.nodes = nodes
return
def __call__(self, parameters... | the_stack_v2_python_sparse | apetools/affectors/ners.py | russell-n/oldape | train | 0 |
783d064a880646d78c18f3d25379f96da6a714e4 | [
"if is_live is True:\n self.client = MongoClient(host=host, port=port, connect=False)\n self.db = self.client.get_database(database)\n self.db.authenticate(user, password)\nelse:\n self.client = MongoClient(f'mongodb://{user}:{password}@{host}:{port}/')\n self.db = self.client[database]",
"collecti... | <|body_start_0|>
if is_live is True:
self.client = MongoClient(host=host, port=port, connect=False)
self.db = self.client.get_database(database)
self.db.authenticate(user, password)
else:
self.client = MongoClient(f'mongodb://{user}:{password}@{host}:{port... | Mongodb | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mongodb:
def __init__(self, host, port, user, password, database, is_live=False):
"""初始化mongodb链接 :param host: :param port: :param user: :param password: :param database: :param is_live: :return:"""
<|body_0|>
def get(self, collection_name, query, limit):
"""根据条件查询 :... | stack_v2_sparse_classes_36k_train_026662 | 1,079 | no_license | [
{
"docstring": "初始化mongodb链接 :param host: :param port: :param user: :param password: :param database: :param is_live: :return:",
"name": "__init__",
"signature": "def __init__(self, host, port, user, password, database, is_live=False)"
},
{
"docstring": "根据条件查询 :param collection_name: :param que... | 2 | stack_v2_sparse_classes_30k_train_009564 | Implement the Python class `Mongodb` described below.
Class description:
Implement the Mongodb class.
Method signatures and docstrings:
- def __init__(self, host, port, user, password, database, is_live=False): 初始化mongodb链接 :param host: :param port: :param user: :param password: :param database: :param is_live: :retu... | Implement the Python class `Mongodb` described below.
Class description:
Implement the Mongodb class.
Method signatures and docstrings:
- def __init__(self, host, port, user, password, database, is_live=False): 初始化mongodb链接 :param host: :param port: :param user: :param password: :param database: :param is_live: :retu... | 8120cc60437ef92e5a462634360e107917d8d9d2 | <|skeleton|>
class Mongodb:
def __init__(self, host, port, user, password, database, is_live=False):
"""初始化mongodb链接 :param host: :param port: :param user: :param password: :param database: :param is_live: :return:"""
<|body_0|>
def get(self, collection_name, query, limit):
"""根据条件查询 :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mongodb:
def __init__(self, host, port, user, password, database, is_live=False):
"""初始化mongodb链接 :param host: :param port: :param user: :param password: :param database: :param is_live: :return:"""
if is_live is True:
self.client = MongoClient(host=host, port=port, connect=False)
... | the_stack_v2_python_sparse | classes/DooMongodb.py | Samuel875154270/src | train | 0 | |
b22b9964a2f842567ae74166802036d1ffd01a79 | [
"assert isinstance(output_space, ContainerSpace), 'ERROR: `output_space` must be a ContainerSpace (Dict or Tuple)!'\nsuper(Merger, self).__init__(scope=scope, **kwargs)\nself.output_space = output_space\nassert isinstance(output_space, ContainerSpace), 'ERROR: `output_space` of Merger Component must be a ContainerS... | <|body_start_0|>
assert isinstance(output_space, ContainerSpace), 'ERROR: `output_space` must be a ContainerSpace (Dict or Tuple)!'
super(Merger, self).__init__(scope=scope, **kwargs)
self.output_space = output_space
assert isinstance(output_space, ContainerSpace), 'ERROR: `output_space`... | Merges incoming items into one FlattenedDataOp. | Merger | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Merger:
"""Merges incoming items into one FlattenedDataOp."""
def __init__(self, output_space, scope='merger', **kwargs):
"""Args: output_space (Space): The output Space to merge to from the single components. Must be a ContainerSpace."""
<|body_0|>
def _graph_fn_merge(s... | stack_v2_sparse_classes_36k_train_026663 | 2,587 | permissive | [
{
"docstring": "Args: output_space (Space): The output Space to merge to from the single components. Must be a ContainerSpace.",
"name": "__init__",
"signature": "def __init__(self, output_space, scope='merger', **kwargs)"
},
{
"docstring": "Merges the inputs into a single FlattenedDataOp. Args:... | 2 | stack_v2_sparse_classes_30k_train_017620 | Implement the Python class `Merger` described below.
Class description:
Merges incoming items into one FlattenedDataOp.
Method signatures and docstrings:
- def __init__(self, output_space, scope='merger', **kwargs): Args: output_space (Space): The output Space to merge to from the single components. Must be a Contain... | Implement the Python class `Merger` described below.
Class description:
Merges incoming items into one FlattenedDataOp.
Method signatures and docstrings:
- def __init__(self, output_space, scope='merger', **kwargs): Args: output_space (Space): The output Space to merge to from the single components. Must be a Contain... | ff7d4768579c0e30aa6ceb932cd16f1e51940010 | <|skeleton|>
class Merger:
"""Merges incoming items into one FlattenedDataOp."""
def __init__(self, output_space, scope='merger', **kwargs):
"""Args: output_space (Space): The output Space to merge to from the single components. Must be a ContainerSpace."""
<|body_0|>
def _graph_fn_merge(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Merger:
"""Merges incoming items into one FlattenedDataOp."""
def __init__(self, output_space, scope='merger', **kwargs):
"""Args: output_space (Space): The output Space to merge to from the single components. Must be a ContainerSpace."""
assert isinstance(output_space, ContainerSpace), '... | the_stack_v2_python_sparse | yarl/components/common/merger.py | pascalwhoop/YARL | train | 0 |
16921f7040deb60d11601a21e855a58ad6a4a188 | [
"project = Project.query.filter_by(slug=project_slug).first_or_404()\nif not (project.public or current_user.is_authenticated()):\n flask_restful.abort(404)\nreturn project",
"try:\n docker_repo_field(project_slug, 'slug')\nexcept ValueError as ex:\n raise WrappedValueError(ex)\nargs = PROJECT_NEW_PARSER... | <|body_start_0|>
project = Project.query.filter_by(slug=project_slug).first_or_404()
if not (project.public or current_user.is_authenticated()):
flask_restful.abort(404)
return project
<|end_body_0|>
<|body_start_1|>
try:
docker_repo_field(project_slug, 'slug')
... | API resource to handle getting project details, creating new projects, updating existing projects, and deleting projects | ProjectDetail | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectDetail:
"""API resource to handle getting project details, creating new projects, updating existing projects, and deleting projects"""
def get(self, project_slug):
"""Get project details"""
<|body_0|>
def put(self, project_slug):
"""Create a new project"""... | stack_v2_sparse_classes_36k_train_026664 | 11,089 | permissive | [
{
"docstring": "Get project details",
"name": "get",
"signature": "def get(self, project_slug)"
},
{
"docstring": "Create a new project",
"name": "put",
"signature": "def put(self, project_slug)"
},
{
"docstring": "Update an existing project",
"name": "post",
"signature":... | 4 | stack_v2_sparse_classes_30k_train_020581 | Implement the Python class `ProjectDetail` described below.
Class description:
API resource to handle getting project details, creating new projects, updating existing projects, and deleting projects
Method signatures and docstrings:
- def get(self, project_slug): Get project details
- def put(self, project_slug): Cr... | Implement the Python class `ProjectDetail` described below.
Class description:
API resource to handle getting project details, creating new projects, updating existing projects, and deleting projects
Method signatures and docstrings:
- def get(self, project_slug): Get project details
- def put(self, project_slug): Cr... | a4cae55de15a829a3e1b72006f3baa1276e95f30 | <|skeleton|>
class ProjectDetail:
"""API resource to handle getting project details, creating new projects, updating existing projects, and deleting projects"""
def get(self, project_slug):
"""Get project details"""
<|body_0|>
def put(self, project_slug):
"""Create a new project"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectDetail:
"""API resource to handle getting project details, creating new projects, updating existing projects, and deleting projects"""
def get(self, project_slug):
"""Get project details"""
project = Project.query.filter_by(slug=project_slug).first_or_404()
if not (project.... | the_stack_v2_python_sparse | dockci/api/project.py | sprucedev/DockCI | train | 1 |
c75d79c8534d388600aec8169f4e8b8abba84ee6 | [
"self.k = k\nself.heap = nums\nprint(self.heap)\nheapq.heapify(self.heap)\nprint(self.heap)\nwhile len(self.heap) > k:\n heapq.heappop(self.heap)",
"if len(self.heap) < self.k:\n heapq.heappush(self.heap, val)\nelse:\n heapq.heappushpop(self.heap, val)\nreturn self.heap[0]"
] | <|body_start_0|>
self.k = k
self.heap = nums
print(self.heap)
heapq.heapify(self.heap)
print(self.heap)
while len(self.heap) > k:
heapq.heappop(self.heap)
<|end_body_0|>
<|body_start_1|>
if len(self.heap) < self.k:
heapq.heappush(self.heap... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.heap = nums
print(self.hea... | stack_v2_sparse_classes_36k_train_026665 | 1,294 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | null | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.heap = nums
print(self.heap)
heapq.heapify(self.heap)
print(self.heap)
while len(self.heap) > k:
heapq.heappop(self.heap)
def add(self, val... | the_stack_v2_python_sparse | 18.HEAP AND PRIORITY QUEUE/703_Kth_largest_element_in_a_stream/solution.py | kimmyoo/python_leetcode | train | 1 | |
2abf6fd1cd8fad8a261d1d38564ebde731111e66 | [
"warehouse = self.cleaned_data.get('warehouse')\nif self.instance.type.by_warehouse and (not warehouse):\n raise forms.ValidationError(_('Warehouse missing'))\nreturn warehouse",
"start = self.cleaned_data['start']\nend = self.cleaned_data['end']\nif start > end:\n raise forms.ValidationError(_('End date mu... | <|body_start_0|>
warehouse = self.cleaned_data.get('warehouse')
if self.instance.type.by_warehouse and (not warehouse):
raise forms.ValidationError(_('Warehouse missing'))
return warehouse
<|end_body_0|>
<|body_start_1|>
start = self.cleaned_data['start']
end = self.... | Used by factory to create UsagesFormSet. Contain basic form infromation like fields and widgets and simple validation like warehouse and team presence. | UsagePriceForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsagePriceForm:
"""Used by factory to create UsagesFormSet. Contain basic form infromation like fields and widgets and simple validation like warehouse and team presence."""
def clean_warehouse(self):
"""If usage type is by_warehouse check if warehouse was provided"""
<|body_... | stack_v2_sparse_classes_36k_train_026666 | 8,678 | permissive | [
{
"docstring": "If usage type is by_warehouse check if warehouse was provided",
"name": "clean_warehouse",
"signature": "def clean_warehouse(self)"
},
{
"docstring": "Test if end date is later or equal to the start date :returns string: the end of the time interval :rtype string:",
"name": "... | 2 | null | Implement the Python class `UsagePriceForm` described below.
Class description:
Used by factory to create UsagesFormSet. Contain basic form infromation like fields and widgets and simple validation like warehouse and team presence.
Method signatures and docstrings:
- def clean_warehouse(self): If usage type is by_war... | Implement the Python class `UsagePriceForm` described below.
Class description:
Used by factory to create UsagesFormSet. Contain basic form infromation like fields and widgets and simple validation like warehouse and team presence.
Method signatures and docstrings:
- def clean_warehouse(self): If usage type is by_war... | cbfd7227ebe97d44fbe1d286f90184d9feb9eced | <|skeleton|>
class UsagePriceForm:
"""Used by factory to create UsagesFormSet. Contain basic form infromation like fields and widgets and simple validation like warehouse and team presence."""
def clean_warehouse(self):
"""If usage type is by_warehouse check if warehouse was provided"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsagePriceForm:
"""Used by factory to create UsagesFormSet. Contain basic form infromation like fields and widgets and simple validation like warehouse and team presence."""
def clean_warehouse(self):
"""If usage type is by_warehouse check if warehouse was provided"""
warehouse = self.cle... | the_stack_v2_python_sparse | src/ralph_scrooge/forms.py | mkurek/ralph_pricing | train | 0 |
bc6e0a1f7b6a008e7507a6f14e585406dc0b2cd5 | [
"web.header('X-Frame-Options', 'SAMEORIGIN')\nweb.header('X-Content-Type-Options', 'nosniff')\nweb.header('X-XSS-Protection', '1')\nif not session.validate_session():\n raise web.seeother('/login')\nelse:\n current_ay_with_current_date = model.get_current_ay_sem()[0:8]\n current_database_ay = model.get_cur... | <|body_start_0|>
web.header('X-Frame-Options', 'SAMEORIGIN')
web.header('X-Content-Type-Options', 'nosniff')
web.header('X-XSS-Protection', '1')
if not session.validate_session():
raise web.seeother('/login')
else:
current_ay_with_current_date = model.get_... | This class is responsible for methods corresponding to the database migration page. | DatabaseMigrate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseMigrate:
"""This class is responsible for methods corresponding to the database migration page."""
def GET(self):
"""This function is called when the database migration page is loaded If user is not logged in, they are redirected to the login page."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_026667 | 1,887 | permissive | [
{
"docstring": "This function is called when the database migration page is loaded If user is not logged in, they are redirected to the login page.",
"name": "GET",
"signature": "def GET(self)"
},
{
"docstring": "Performs the database migration, should the user acknowledges the implication invol... | 2 | stack_v2_sparse_classes_30k_train_007854 | Implement the Python class `DatabaseMigrate` described below.
Class description:
This class is responsible for methods corresponding to the database migration page.
Method signatures and docstrings:
- def GET(self): This function is called when the database migration page is loaded If user is not logged in, they are ... | Implement the Python class `DatabaseMigrate` described below.
Class description:
This class is responsible for methods corresponding to the database migration page.
Method signatures and docstrings:
- def GET(self): This function is called when the database migration page is loaded If user is not logged in, they are ... | 02b52871a34f580b779ede08750f2d4e887bcf65 | <|skeleton|>
class DatabaseMigrate:
"""This class is responsible for methods corresponding to the database migration page."""
def GET(self):
"""This function is called when the database migration page is loaded If user is not logged in, they are redirected to the login page."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatabaseMigrate:
"""This class is responsible for methods corresponding to the database migration page."""
def GET(self):
"""This function is called when the database migration page is loaded If user is not logged in, they are redirected to the login page."""
web.header('X-Frame-Options',... | the_stack_v2_python_sparse | components/handlers/database_migrate.py | nus-mtp/cs-modify | train | 1 |
32aa3e77edd63b76826e226d0ff1d79cb09caa39 | [
"super(Bottleneck, self).__init__()\nself.linear1 = layers.Dense(planes, use_bias=False)\nself.bn1 = layers.BatchNormalization(momentum=0.9, epsilon=1e-05)\nself.transformer2 = Transformer(planes, planes, share_planes, nsample)\nself.bn2 = layers.BatchNormalization(momentum=0.9, epsilon=1e-05)\nself.linear3 = layer... | <|body_start_0|>
super(Bottleneck, self).__init__()
self.linear1 = layers.Dense(planes, use_bias=False)
self.bn1 = layers.BatchNormalization(momentum=0.9, epsilon=1e-05)
self.transformer2 = Transformer(planes, planes, share_planes, nsample)
self.bn2 = layers.BatchNormalization(mo... | Bottleneck layer for PointTransformer. Block of layers using Transformer layer as building block. | Bottleneck | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bottleneck:
"""Bottleneck layer for PointTransformer. Block of layers using Transformer layer as building block."""
def __init__(self, in_planes, planes, share_planes=8, nsample=16):
"""Constructor for Bottleneck Layer. Args: in_planes (int): Number of input planes. planes (int): Num... | stack_v2_sparse_classes_36k_train_026668 | 29,888 | permissive | [
{
"docstring": "Constructor for Bottleneck Layer. Args: in_planes (int): Number of input planes. planes (int): Number of output planes. share_planes (int): Number of shared planes. nsample (int): Number of neighbours.",
"name": "__init__",
"signature": "def __init__(self, in_planes, planes, share_planes... | 2 | stack_v2_sparse_classes_30k_train_001430 | Implement the Python class `Bottleneck` described below.
Class description:
Bottleneck layer for PointTransformer. Block of layers using Transformer layer as building block.
Method signatures and docstrings:
- def __init__(self, in_planes, planes, share_planes=8, nsample=16): Constructor for Bottleneck Layer. Args: i... | Implement the Python class `Bottleneck` described below.
Class description:
Bottleneck layer for PointTransformer. Block of layers using Transformer layer as building block.
Method signatures and docstrings:
- def __init__(self, in_planes, planes, share_planes=8, nsample=16): Constructor for Bottleneck Layer. Args: i... | 51482281dc180786e7563c73c12ac5df89289748 | <|skeleton|>
class Bottleneck:
"""Bottleneck layer for PointTransformer. Block of layers using Transformer layer as building block."""
def __init__(self, in_planes, planes, share_planes=8, nsample=16):
"""Constructor for Bottleneck Layer. Args: in_planes (int): Number of input planes. planes (int): Num... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bottleneck:
"""Bottleneck layer for PointTransformer. Block of layers using Transformer layer as building block."""
def __init__(self, in_planes, planes, share_planes=8, nsample=16):
"""Constructor for Bottleneck Layer. Args: in_planes (int): Number of input planes. planes (int): Number of output... | the_stack_v2_python_sparse | ml3d/tf/models/point_transformer.py | CosmosHua/Open3D-ML | train | 0 |
837803a51129291203e1652f8c1bde5a5b5ac5ac | [
"self.wrong = False\nself.element_1 = StartingWindow()\nif self.element_1.name != 'quit' and len(self.element_1.name) > 0:\n self.element_2 = TimeWindow()\n self.get_chart()\n self.get_rep()\n if self.element_2 != None:\n a = Represent()\n if a.continu == True:\n Start()",
"tr... | <|body_start_0|>
self.wrong = False
self.element_1 = StartingWindow()
if self.element_1.name != 'quit' and len(self.element_1.name) > 0:
self.element_2 = TimeWindow()
self.get_chart()
self.get_rep()
if self.element_2 != None:
a = Re... | This is class to start and rule the program | Start | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Start:
"""This is class to start and rule the program"""
def __init__(self):
"""obj -> None This method initializes an object"""
<|body_0|>
def get_chart(self):
"""obj -> None This makes a graphic chart"""
<|body_1|>
def get_rep(self):
"""obj... | stack_v2_sparse_classes_36k_train_026669 | 1,355 | no_license | [
{
"docstring": "obj -> None This method initializes an object",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "obj -> None This makes a graphic chart",
"name": "get_chart",
"signature": "def get_chart(self)"
},
{
"docstring": "obj, str -> None This metho... | 3 | stack_v2_sparse_classes_30k_val_001204 | Implement the Python class `Start` described below.
Class description:
This is class to start and rule the program
Method signatures and docstrings:
- def __init__(self): obj -> None This method initializes an object
- def get_chart(self): obj -> None This makes a graphic chart
- def get_rep(self): obj, str -> None T... | Implement the Python class `Start` described below.
Class description:
This is class to start and rule the program
Method signatures and docstrings:
- def __init__(self): obj -> None This method initializes an object
- def get_chart(self): obj -> None This makes a graphic chart
- def get_rep(self): obj, str -> None T... | 85d5f93c62aa05f3f66908df827f2ae58faf8dfe | <|skeleton|>
class Start:
"""This is class to start and rule the program"""
def __init__(self):
"""obj -> None This method initializes an object"""
<|body_0|>
def get_chart(self):
"""obj -> None This makes a graphic chart"""
<|body_1|>
def get_rep(self):
"""obj... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Start:
"""This is class to start and rule the program"""
def __init__(self):
"""obj -> None This method initializes an object"""
self.wrong = False
self.element_1 = StartingWindow()
if self.element_1.name != 'quit' and len(self.element_1.name) > 0:
self.element... | the_stack_v2_python_sparse | Final/build/lib/main.py | captainvlad/course_project | train | 0 |
8d00f7daeec821f0a17fa2c149dbeb96396891cd | [
"if not db_session:\n db_session = g.db.session\nself.db_session = db_session",
"default_error_msg = 'Invalid filename. Please inform a file named \"time-report-{id}.csv\"'\nfilename = secure_filename(source.filename)\ntry:\n filename_parts = filename.split('.')[0].split('-')\n report_id = int(filename_p... | <|body_start_0|>
if not db_session:
db_session = g.db.session
self.db_session = db_session
<|end_body_0|>
<|body_start_1|>
default_error_msg = 'Invalid filename. Please inform a file named "time-report-{id}.csv"'
filename = secure_filename(source.filename)
try:
... | Controller to encapsulate employee-related data/logic manipulations. | EmployeeController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmployeeController:
"""Controller to encapsulate employee-related data/logic manipulations."""
def __init__(self, db_session: Optional[scoped_session]=None):
"""Class constructor. Args: - db_session (Optional[scoped_session]): Current database session. When not informed, defaults to ... | stack_v2_sparse_classes_36k_train_026670 | 6,209 | no_license | [
{
"docstring": "Class constructor. Args: - db_session (Optional[scoped_session]): Current database session. When not informed, defaults to the session present in the application context g.",
"name": "__init__",
"signature": "def __init__(self, db_session: Optional[scoped_session]=None)"
},
{
"do... | 5 | stack_v2_sparse_classes_30k_train_012895 | Implement the Python class `EmployeeController` described below.
Class description:
Controller to encapsulate employee-related data/logic manipulations.
Method signatures and docstrings:
- def __init__(self, db_session: Optional[scoped_session]=None): Class constructor. Args: - db_session (Optional[scoped_session]): ... | Implement the Python class `EmployeeController` described below.
Class description:
Controller to encapsulate employee-related data/logic manipulations.
Method signatures and docstrings:
- def __init__(self, db_session: Optional[scoped_session]=None): Class constructor. Args: - db_session (Optional[scoped_session]): ... | f9eef57216449c97849a5c73b9983fae5d0c5030 | <|skeleton|>
class EmployeeController:
"""Controller to encapsulate employee-related data/logic manipulations."""
def __init__(self, db_session: Optional[scoped_session]=None):
"""Class constructor. Args: - db_session (Optional[scoped_session]): Current database session. When not informed, defaults to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmployeeController:
"""Controller to encapsulate employee-related data/logic manipulations."""
def __init__(self, db_session: Optional[scoped_session]=None):
"""Class constructor. Args: - db_session (Optional[scoped_session]): Current database session. When not informed, defaults to the session p... | the_stack_v2_python_sparse | app/controllers/employees.py | rqroz/wave-challenge | train | 1 |
427dab5b72f91fb27bd6cb8f13923c76dd06bec5 | [
"list = [1, 18, 10, 9, 1, 0, 2]\nlist_heaped = heapify(list, 0)\nself.assertListEqual(list_heaped, [18, 9, 10, 1, 1, 0, 2])\nlist = [4, 18, 19, 9, 10, 3, 7, 1, 1, 0, 2]\nlist_heaped = heapify(list, 0)\nself.assertListEqual(list_heaped, [19, 18, 7, 9, 10, 3, 4, 1, 1, 0, 2])\nlist = [19, 1, 7, 18, 10, 3, 4, 9, 1, 0, ... | <|body_start_0|>
list = [1, 18, 10, 9, 1, 0, 2]
list_heaped = heapify(list, 0)
self.assertListEqual(list_heaped, [18, 9, 10, 1, 1, 0, 2])
list = [4, 18, 19, 9, 10, 3, 7, 1, 1, 0, 2]
list_heaped = heapify(list, 0)
self.assertListEqual(list_heaped, [19, 18, 7, 9, 10, 3, 4, ... | Tests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tests:
def test_heapify(self):
"""Does your heapify method work? The first tests for a sorted list. Since the heapify function heapifies subtrees, this will not return the same, sorted list"""
<|body_0|>
def test_buildmaxheap(self):
"""Does your max heap method work?... | stack_v2_sparse_classes_36k_train_026671 | 4,153 | no_license | [
{
"docstring": "Does your heapify method work? The first tests for a sorted list. Since the heapify function heapifies subtrees, this will not return the same, sorted list",
"name": "test_heapify",
"signature": "def test_heapify(self)"
},
{
"docstring": "Does your max heap method work? These sho... | 3 | stack_v2_sparse_classes_30k_train_003130 | Implement the Python class `Tests` described below.
Class description:
Implement the Tests class.
Method signatures and docstrings:
- def test_heapify(self): Does your heapify method work? The first tests for a sorted list. Since the heapify function heapifies subtrees, this will not return the same, sorted list
- de... | Implement the Python class `Tests` described below.
Class description:
Implement the Tests class.
Method signatures and docstrings:
- def test_heapify(self): Does your heapify method work? The first tests for a sorted list. Since the heapify function heapifies subtrees, this will not return the same, sorted list
- de... | 389e03247f82a05def69a5d558e98cde79cd0156 | <|skeleton|>
class Tests:
def test_heapify(self):
"""Does your heapify method work? The first tests for a sorted list. Since the heapify function heapifies subtrees, this will not return the same, sorted list"""
<|body_0|>
def test_buildmaxheap(self):
"""Does your max heap method work?... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tests:
def test_heapify(self):
"""Does your heapify method work? The first tests for a sorted list. Since the heapify function heapifies subtrees, this will not return the same, sorted list"""
list = [1, 18, 10, 9, 1, 0, 2]
list_heaped = heapify(list, 0)
self.assertListEqual(li... | the_stack_v2_python_sparse | labs/lab7.py | john-odonnell/csc_212 | train | 0 | |
fdda61069f20db9251ada9d4cef33f36a90ca8a5 | [
"super(Segmentation, self).__init__()\nself.word_segmentation = WordSegmentation(stop_words_file)\nself.sentence_segmentation = SentenceSegmentation(delimiters)",
"sentences = self.sentence_segmentation.segment_text(text)\nwords_no_filter = self.word_segmentation.segment_sentences(sentences=sentences, lower=lower... | <|body_start_0|>
super(Segmentation, self).__init__()
self.word_segmentation = WordSegmentation(stop_words_file)
self.sentence_segmentation = SentenceSegmentation(delimiters)
<|end_body_0|>
<|body_start_1|>
sentences = self.sentence_segmentation.segment_text(text)
words_no_filte... | 分割器 | Segmentation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Segmentation:
"""分割器"""
def __init__(self, stop_words_file=None, delimiters='?!;?!。;…\n'):
"""函数功能: 默认构造函数 stop_words_file: 停止词文件 delimiters: 分隔符集合"""
<|body_0|>
def segment_text(self, text, lower=False, speech_tag_filter=True):
"""函数功能: 对text进行分割处理(分词/分句) text: ... | stack_v2_sparse_classes_36k_train_026672 | 6,042 | no_license | [
{
"docstring": "函数功能: 默认构造函数 stop_words_file: 停止词文件 delimiters: 分隔符集合",
"name": "__init__",
"signature": "def __init__(self, stop_words_file=None, delimiters='?!;?!。;…\\n')"
},
{
"docstring": "函数功能: 对text进行分割处理(分词/分句) text: 待处理文本 lower: 是否将英语单词转化为小写 speech_tag_filter: 词性过滤器",
"name": "segmen... | 2 | stack_v2_sparse_classes_30k_train_018632 | Implement the Python class `Segmentation` described below.
Class description:
分割器
Method signatures and docstrings:
- def __init__(self, stop_words_file=None, delimiters='?!;?!。;…\n'): 函数功能: 默认构造函数 stop_words_file: 停止词文件 delimiters: 分隔符集合
- def segment_text(self, text, lower=False, speech_tag_filter=True): 函数功能: 对tex... | Implement the Python class `Segmentation` described below.
Class description:
分割器
Method signatures and docstrings:
- def __init__(self, stop_words_file=None, delimiters='?!;?!。;…\n'): 函数功能: 默认构造函数 stop_words_file: 停止词文件 delimiters: 分隔符集合
- def segment_text(self, text, lower=False, speech_tag_filter=True): 函数功能: 对tex... | 9855d6e69598f9cbf1652c3bcea27133a755c03c | <|skeleton|>
class Segmentation:
"""分割器"""
def __init__(self, stop_words_file=None, delimiters='?!;?!。;…\n'):
"""函数功能: 默认构造函数 stop_words_file: 停止词文件 delimiters: 分隔符集合"""
<|body_0|>
def segment_text(self, text, lower=False, speech_tag_filter=True):
"""函数功能: 对text进行分割处理(分词/分句) text: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Segmentation:
"""分割器"""
def __init__(self, stop_words_file=None, delimiters='?!;?!。;…\n'):
"""函数功能: 默认构造函数 stop_words_file: 停止词文件 delimiters: 分隔符集合"""
super(Segmentation, self).__init__()
self.word_segmentation = WordSegmentation(stop_words_file)
self.sentence_segmentation... | the_stack_v2_python_sparse | TextRank/Segmentation.py | xc15071347094/ASExtractor | train | 0 |
6efed2722f0b9444ccefa3dd504c482354827a0b | [
"self.root_dir = Path('{root}/{year}'.format(root=root_dir, year=year))\nself.annotations_zip_path = Path('{root}/annotations_trainval{year}.zip'.format(root=self.root_dir, year=year))\nself.train_zip_path = Path('{root}/train{year}.zip'.format(root=self.root_dir, year=year))\nself.val_zip_path = Path('{root}/val{y... | <|body_start_0|>
self.root_dir = Path('{root}/{year}'.format(root=root_dir, year=year))
self.annotations_zip_path = Path('{root}/annotations_trainval{year}.zip'.format(root=self.root_dir, year=year))
self.train_zip_path = Path('{root}/train{year}.zip'.format(root=self.root_dir, year=year))
... | COCOBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class COCOBase:
def __init__(self, root_dir: str='../../data/coco/', download_dataset: bool=False, year: Literal['2014', '2017']='2017', split: Literal['train', 'val', 'test']='train') -> None:
"""An abstract class for COCO based datasets Args: root_dir: The path to the COCO images and annotat... | stack_v2_sparse_classes_36k_train_026673 | 4,069 | permissive | [
{
"docstring": "An abstract class for COCO based datasets Args: root_dir: The path to the COCO images and annotations download_dataset: Specify whether to download the dataset if not present year: The year of the COCO dataset to use (2014, 2017) split: The split of the data to be used (train, val, test)",
"... | 2 | stack_v2_sparse_classes_30k_val_001200 | Implement the Python class `COCOBase` described below.
Class description:
Implement the COCOBase class.
Method signatures and docstrings:
- def __init__(self, root_dir: str='../../data/coco/', download_dataset: bool=False, year: Literal['2014', '2017']='2017', split: Literal['train', 'val', 'test']='train') -> None: ... | Implement the Python class `COCOBase` described below.
Class description:
Implement the COCOBase class.
Method signatures and docstrings:
- def __init__(self, root_dir: str='../../data/coco/', download_dataset: bool=False, year: Literal['2014', '2017']='2017', split: Literal['train', 'val', 'test']='train') -> None: ... | b436fbd95cbb62f6c58d2233d7affa0f62cb1817 | <|skeleton|>
class COCOBase:
def __init__(self, root_dir: str='../../data/coco/', download_dataset: bool=False, year: Literal['2014', '2017']='2017', split: Literal['train', 'val', 'test']='train') -> None:
"""An abstract class for COCO based datasets Args: root_dir: The path to the COCO images and annotat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class COCOBase:
def __init__(self, root_dir: str='../../data/coco/', download_dataset: bool=False, year: Literal['2014', '2017']='2017', split: Literal['train', 'val', 'test']='train') -> None:
"""An abstract class for COCO based datasets Args: root_dir: The path to the COCO images and annotations download_... | the_stack_v2_python_sparse | python/app/fedcv/image_segmentation/data/coco/coco_base.py | FedML-AI/FedML | train | 3,197 | |
ce1ff57e5e574220daf7c5449ce8609160936b84 | [
"pokemon = super().__getitem__(identifier)\nif isinstance(pokemon, db.Pokemon) and pokemon.is_hidden_gift() and (pokemon.trainer_id != current_trainer_id()):\n return None\nreturn pokemon",
"pokemon = super()._redirect(identifier)\nif pokemon is not None and pokemon.is_hidden_gift() and (pokemon.trainer_id != ... | <|body_start_0|>
pokemon = super().__getitem__(identifier)
if isinstance(pokemon, db.Pokemon) and pokemon.is_hidden_gift() and (pokemon.trainer_id != current_trainer_id()):
return None
return pokemon
<|end_body_0|>
<|body_start_1|>
pokemon = super()._redirect(identifier)
... | PokemonIndex | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PokemonIndex:
def __getitem__(self, identifier):
"""Intercept the Pokémon and check if it's currently being offered as a gift (and the sender is not the current user). If so, pretend nothing was found."""
<|body_0|>
def _redirect(self, identifier):
"""Intercept the r... | stack_v2_sparse_classes_36k_train_026674 | 6,536 | no_license | [
{
"docstring": "Intercept the Pokémon and check if it's currently being offered as a gift (and the sender is not the current user). If so, pretend nothing was found.",
"name": "__getitem__",
"signature": "def __getitem__(self, identifier)"
},
{
"docstring": "Intercept the redirect and check if t... | 2 | stack_v2_sparse_classes_30k_train_006011 | Implement the Python class `PokemonIndex` described below.
Class description:
Implement the PokemonIndex class.
Method signatures and docstrings:
- def __getitem__(self, identifier): Intercept the Pokémon and check if it's currently being offered as a gift (and the sender is not the current user). If so, pretend noth... | Implement the Python class `PokemonIndex` described below.
Class description:
Implement the PokemonIndex class.
Method signatures and docstrings:
- def __getitem__(self, identifier): Intercept the Pokémon and check if it's currently being offered as a gift (and the sender is not the current user). If so, pretend noth... | 872c0b21ed8d45a4c88d51969d3531b8b7913e71 | <|skeleton|>
class PokemonIndex:
def __getitem__(self, identifier):
"""Intercept the Pokémon and check if it's currently being offered as a gift (and the sender is not the current user). If so, pretend nothing was found."""
<|body_0|>
def _redirect(self, identifier):
"""Intercept the r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PokemonIndex:
def __getitem__(self, identifier):
"""Intercept the Pokémon and check if it's currently being offered as a gift (and the sender is not the current user). If so, pretend nothing was found."""
pokemon = super().__getitem__(identifier)
if isinstance(pokemon, db.Pokemon) and ... | the_stack_v2_python_sparse | asb/resources.py | CatTrinket/tcod-asb | train | 1 | |
27ca455585bda492365d0b063cb125b0fa31f0d3 | [
"wx.Panel.__init__(self, parent)\nbtn = wx.Button(self, label='Raise Exception')\nbtn.Bind(wx.EVT_BUTTON, self.onExcept)",
"print(self, event)\nprint(isinstance(self, wx.Panel))\n1 / 0"
] | <|body_start_0|>
wx.Panel.__init__(self, parent)
btn = wx.Button(self, label='Raise Exception')
btn.Bind(wx.EVT_BUTTON, self.onExcept)
<|end_body_0|>
<|body_start_1|>
print(self, event)
print(isinstance(self, wx.Panel))
1 / 0
<|end_body_1|>
| Panel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Panel:
def __init__(self, parent):
"""Constructor"""
<|body_0|>
def onExcept(self, event):
"""Raise an error"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
wx.Panel.__init__(self, parent)
btn = wx.Button(self, label='Raise Exception')
... | stack_v2_sparse_classes_36k_train_026675 | 2,203 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Raise an error",
"name": "onExcept",
"signature": "def onExcept(self, event)"
}
] | 2 | null | Implement the Python class `Panel` described below.
Class description:
Implement the Panel class.
Method signatures and docstrings:
- def __init__(self, parent): Constructor
- def onExcept(self, event): Raise an error | Implement the Python class `Panel` described below.
Class description:
Implement the Panel class.
Method signatures and docstrings:
- def __init__(self, parent): Constructor
- def onExcept(self, event): Raise an error
<|skeleton|>
class Panel:
def __init__(self, parent):
"""Constructor"""
<|body... | ebe43e870b1057c6252671d8739e8ce7bad424fe | <|skeleton|>
class Panel:
def __init__(self, parent):
"""Constructor"""
<|body_0|>
def onExcept(self, event):
"""Raise an error"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Panel:
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent)
btn = wx.Button(self, label='Raise Exception')
btn.Bind(wx.EVT_BUTTON, self.onExcept)
def onExcept(self, event):
"""Raise an error"""
print(self, event)
print(isins... | the_stack_v2_python_sparse | wxPython_recipes_book_code-master/chapter_20_bonus_recipes/recipe_20_1_catching_exceptions/exception_decorator3.py | canderson71/python | train | 0 | |
fdfb16032d63dccfe736757871f28ac55b96b3da | [
"self._filename = None\nself._data = None\nself.uhecr = {}\nself.source = {}\nself.detector = {}",
"if label == None:\n label = 'VCV_AGN'\nnew_source = Source(filename, label)\nself.source = new_source",
"if label == None:\n label = 'auger2010'\nnew_uhecr = Uhecr(filename, label)\nself.uhecr = new_uhecr",... | <|body_start_0|>
self._filename = None
self._data = None
self.uhecr = {}
self.source = {}
self.detector = {}
<|end_body_0|>
<|body_start_1|>
if label == None:
label = 'VCV_AGN'
new_source = Source(filename, label)
self.source = new_source
<|en... | A container for high level storage of data. | Data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Data:
"""A container for high level storage of data."""
def __init__(self):
"""A container for high level storage of data."""
<|body_0|>
def add_source(self, filename, label=None):
"""Add a source object to the data cotainer :param filename: name of the file cont... | stack_v2_sparse_classes_36k_train_026676 | 15,467 | no_license | [
{
"docstring": "A container for high level storage of data.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add a source object to the data cotainer :param filename: name of the file containing the object's data :param label: reference label for the source object",
... | 6 | stack_v2_sparse_classes_30k_train_012604 | Implement the Python class `Data` described below.
Class description:
A container for high level storage of data.
Method signatures and docstrings:
- def __init__(self): A container for high level storage of data.
- def add_source(self, filename, label=None): Add a source object to the data cotainer :param filename: ... | Implement the Python class `Data` described below.
Class description:
A container for high level storage of data.
Method signatures and docstrings:
- def __init__(self): A container for high level storage of data.
- def add_source(self, filename, label=None): Add a source object to the data cotainer :param filename: ... | 0c1894ce8d9f5daed539240d3ac86e645d6de44c | <|skeleton|>
class Data:
"""A container for high level storage of data."""
def __init__(self):
"""A container for high level storage of data."""
<|body_0|>
def add_source(self, filename, label=None):
"""Add a source object to the data cotainer :param filename: name of the file cont... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Data:
"""A container for high level storage of data."""
def __init__(self):
"""A container for high level storage of data."""
self._filename = None
self._data = None
self.uhecr = {}
self.source = {}
self.detector = {}
def add_source(self, filename, lab... | the_stack_v2_python_sparse | stan_implementation/analysis_interface/interfaces/data.py | cescalara/soiaporn_model | train | 1 |
ddf37877c7d17d389f42ff1651129f159edc0a06 | [
"dataseries.VoxelDataSeries.__init__(self, *args, **kwargs)\nif self.overlay.ndim < 4:\n raise ValueError('Overlay is not a 4D image')",
"data = dataseries.VoxelDataSeries.currentVoxelData(self, location)\ndata = calcPowerSpectrum(data)\nreturn data",
"overlay = self.overlay\nydata = self.dataAtCurrentVoxel(... | <|body_start_0|>
dataseries.VoxelDataSeries.__init__(self, *args, **kwargs)
if self.overlay.ndim < 4:
raise ValueError('Overlay is not a 4D image')
<|end_body_0|>
<|body_start_1|>
data = dataseries.VoxelDataSeries.currentVoxelData(self, location)
data = calcPowerSpectrum(dat... | The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property. | VoxelPowerSpectrumSeries | [
"Apache-2.0",
"CC-BY-3.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VoxelPowerSpectrumSeries:
"""The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property."""
def __init__(self, *args, **kwargs):
"""Create a ``Voxel... | stack_v2_sparse_classes_36k_train_026677 | 19,177 | permissive | [
{
"docstring": "Create a ``VoxelPowerSpectrumSeries``. All arguments are passed to the :meth:`VoxelDataSeries.__init__` method. A :exc:`ValueError` is raised if the overlay is not a 4D :class:`.Image`.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Ov... | 3 | null | Implement the Python class `VoxelPowerSpectrumSeries` described below.
Class description:
The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property.
Method signatures and docstrings... | Implement the Python class `VoxelPowerSpectrumSeries` described below.
Class description:
The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property.
Method signatures and docstrings... | 37b45d034d60660b6de3e4bdf5dd6349ed6d853b | <|skeleton|>
class VoxelPowerSpectrumSeries:
"""The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property."""
def __init__(self, *args, **kwargs):
"""Create a ``Voxel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VoxelPowerSpectrumSeries:
"""The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property."""
def __init__(self, *args, **kwargs):
"""Create a ``VoxelPowerSpectrum... | the_stack_v2_python_sparse | fsleyes/plotting/powerspectrumseries.py | CGSchwarzMayo/fsleyes | train | 0 |
b26ceef94cac4c3d888d6e3ce4defef62b088bac | [
"with self.__lock:\n if not self.__pool:\n self.__class__.__pool = PooledDB(pymysql, mincached, maxcached, maxshared, maxconnections, blocking, maxusage, setsession, reset, host=host, port=port, db=db, user=user, passwd=passwd, charset=charset)\nself._conn = self.__pool.connection()\nif self._conn:\n s... | <|body_start_0|>
with self.__lock:
if not self.__pool:
self.__class__.__pool = PooledDB(pymysql, mincached, maxcached, maxshared, maxconnections, blocking, maxusage, setsession, reset, host=host, port=port, db=db, user=user, passwd=passwd, charset=charset)
self._conn = self._... | MysqlPool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MysqlPool:
def __init__(self, mincached=10, maxcached=20, maxshared=10, maxconnections=200, blocking=True, maxusage=100, setsession=None, reset=True, host='127.0.0.1', port=3306, db='test', user='root', passwd='', charset='utf8mb4'):
"""dbapi :数据库接口 :param mincached:连接池中空闲连接的初始数量 :param ... | stack_v2_sparse_classes_36k_train_026678 | 4,364 | no_license | [
{
"docstring": "dbapi :数据库接口 :param mincached:连接池中空闲连接的初始数量 :param maxcached:连接池中空闲连接的最大数量 :param maxshared:共享连接的最大数量 :param maxconnections:创建连接池的最大数量 :param blocking:超过最大连接数量时候的表现,为True等待连接数量下降,为false直接报错处理 :param maxusage:单个连接的最大重复使用次数 :param setsession:optional list of SQL commands that may serve to prepare ... | 5 | stack_v2_sparse_classes_30k_train_014158 | Implement the Python class `MysqlPool` described below.
Class description:
Implement the MysqlPool class.
Method signatures and docstrings:
- def __init__(self, mincached=10, maxcached=20, maxshared=10, maxconnections=200, blocking=True, maxusage=100, setsession=None, reset=True, host='127.0.0.1', port=3306, db='test... | Implement the Python class `MysqlPool` described below.
Class description:
Implement the MysqlPool class.
Method signatures and docstrings:
- def __init__(self, mincached=10, maxcached=20, maxshared=10, maxconnections=200, blocking=True, maxusage=100, setsession=None, reset=True, host='127.0.0.1', port=3306, db='test... | b6d056551d1323fd418f870b6340d8e9b906dc0f | <|skeleton|>
class MysqlPool:
def __init__(self, mincached=10, maxcached=20, maxshared=10, maxconnections=200, blocking=True, maxusage=100, setsession=None, reset=True, host='127.0.0.1', port=3306, db='test', user='root', passwd='', charset='utf8mb4'):
"""dbapi :数据库接口 :param mincached:连接池中空闲连接的初始数量 :param ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MysqlPool:
def __init__(self, mincached=10, maxcached=20, maxshared=10, maxconnections=200, blocking=True, maxusage=100, setsession=None, reset=True, host='127.0.0.1', port=3306, db='test', user='root', passwd='', charset='utf8mb4'):
"""dbapi :数据库接口 :param mincached:连接池中空闲连接的初始数量 :param maxcached:连接池中... | the_stack_v2_python_sparse | 树莓派节点/分布式平台/DSP3.0/DASP/pysnooperdb/pool.py | Wales-Wyf/Mingze_Project | train | 1 | |
2e529051608992b761e0b6de81df583bd4cc459c | [
"super().__init__(*args, **kwargs)\nself._backdoor_vars = self._target_estimand.get_backdoor_variables()\nself._cat_feats = kwargs.pop('cat_feats', [])\nself._support_config = kwargs.pop('support_config', None)\nself._overlap_config = kwargs.pop('overlap_config', None)\nself._overlap_eps = kwargs.pop('overlap_eps',... | <|body_start_0|>
super().__init__(*args, **kwargs)
self._backdoor_vars = self._target_estimand.get_backdoor_variables()
self._cat_feats = kwargs.pop('cat_feats', [])
self._support_config = kwargs.pop('support_config', None)
self._overlap_config = kwargs.pop('overlap_config', None... | Assess Overlap This class implements the OverRule algorithm for assessing support and overlap via Boolean Rulesets, from [1]. [1] Oberst, M., Johansson, F., Wei, D., Gao, T., Brat, G., Sontag, D., & Varshney, K. (2020). Characterization of Overlap in Observational Studies. In S. Chiappa & R. Calandra (Eds.), Proceeding... | AssessOverlap | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssessOverlap:
"""Assess Overlap This class implements the OverRule algorithm for assessing support and overlap via Boolean Rulesets, from [1]. [1] Oberst, M., Johansson, F., Wei, D., Gao, T., Brat, G., Sontag, D., & Varshney, K. (2020). Characterization of Overlap in Observational Studies. In S.... | stack_v2_sparse_classes_36k_train_026679 | 5,959 | permissive | [
{
"docstring": "Initialize the parameters required for the refuter. Arguments are passed through to the `refute_estimate` method. See dowhy.causal_refuters.assess_overlap_overrule for the definition of the `SupportConfig` and `OverlapConfig` dataclasses that define optimization hyperparameters. .. warning:: Thi... | 2 | stack_v2_sparse_classes_30k_test_001132 | Implement the Python class `AssessOverlap` described below.
Class description:
Assess Overlap This class implements the OverRule algorithm for assessing support and overlap via Boolean Rulesets, from [1]. [1] Oberst, M., Johansson, F., Wei, D., Gao, T., Brat, G., Sontag, D., & Varshney, K. (2020). Characterization of ... | Implement the Python class `AssessOverlap` described below.
Class description:
Assess Overlap This class implements the OverRule algorithm for assessing support and overlap via Boolean Rulesets, from [1]. [1] Oberst, M., Johansson, F., Wei, D., Gao, T., Brat, G., Sontag, D., & Varshney, K. (2020). Characterization of ... | 0b5e2c3efa348ca232ecc6355f0fc6ec4458241a | <|skeleton|>
class AssessOverlap:
"""Assess Overlap This class implements the OverRule algorithm for assessing support and overlap via Boolean Rulesets, from [1]. [1] Oberst, M., Johansson, F., Wei, D., Gao, T., Brat, G., Sontag, D., & Varshney, K. (2020). Characterization of Overlap in Observational Studies. In S.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssessOverlap:
"""Assess Overlap This class implements the OverRule algorithm for assessing support and overlap via Boolean Rulesets, from [1]. [1] Oberst, M., Johansson, F., Wei, D., Gao, T., Brat, G., Sontag, D., & Varshney, K. (2020). Characterization of Overlap in Observational Studies. In S. Chiappa & R.... | the_stack_v2_python_sparse | dowhy/causal_refuters/assess_overlap.py | n8sty/dowhy | train | 0 |
20aa47d8198730a5ceb7f13af8df4cca76a2282f | [
"AssessmentResults.__init__(self, controller, **kwargs)\nself._lst_labels.append(u'π<sub>CYC</sub>:')\nself._lst_labels.append(u'π<sub>L</sub>:')\nself._lst_labels.append(u'π<sub>C</sub>:')\nself._lst_labels.append(u'π<sub>N</sub>:')\nself._lst_labels.append(u'π<sub>U</sub>:')\nself._lblModel.set_tooltip_markup(_(u... | <|body_start_0|>
AssessmentResults.__init__(self, controller, **kwargs)
self._lst_labels.append(u'π<sub>CYC</sub>:')
self._lst_labels.append(u'π<sub>L</sub>:')
self._lst_labels.append(u'π<sub>C</sub>:')
self._lst_labels.append(u'π<sub>N</sub>:')
self._lst_labels.append(u'... | Display Switch assessment results attribute data in the RAMSTK Work Book. The Switch assessment result view displays all the assessment results for the selected switch. This includes, currently, results for MIL-HDBK-217FN2 parts count and MIL-HDBK-217FN2 part stress methods. The attributes of a switch assessment result... | SwitchAssessmentResults | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwitchAssessmentResults:
"""Display Switch assessment results attribute data in the RAMSTK Work Book. The Switch assessment result view displays all the assessment results for the selected switch. This includes, currently, results for MIL-HDBK-217FN2 parts count and MIL-HDBK-217FN2 part stress me... | stack_v2_sparse_classes_36k_train_026680 | 22,336 | permissive | [
{
"docstring": "Initialize an instance of the Switch assessment result view. :param controller: the hardware data controller instance. :type controller: :class:`ramstk.hardware.Controller.HardwareBoMDataController`",
"name": "__init__",
"signature": "def __init__(self, controller, **kwargs)"
},
{
... | 5 | null | Implement the Python class `SwitchAssessmentResults` described below.
Class description:
Display Switch assessment results attribute data in the RAMSTK Work Book. The Switch assessment result view displays all the assessment results for the selected switch. This includes, currently, results for MIL-HDBK-217FN2 parts c... | Implement the Python class `SwitchAssessmentResults` described below.
Class description:
Display Switch assessment results attribute data in the RAMSTK Work Book. The Switch assessment result view displays all the assessment results for the selected switch. This includes, currently, results for MIL-HDBK-217FN2 parts c... | 488ffed8b842399ddcae93007de6c6f1dda23d05 | <|skeleton|>
class SwitchAssessmentResults:
"""Display Switch assessment results attribute data in the RAMSTK Work Book. The Switch assessment result view displays all the assessment results for the selected switch. This includes, currently, results for MIL-HDBK-217FN2 parts count and MIL-HDBK-217FN2 part stress me... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwitchAssessmentResults:
"""Display Switch assessment results attribute data in the RAMSTK Work Book. The Switch assessment result view displays all the assessment results for the selected switch. This includes, currently, results for MIL-HDBK-217FN2 parts count and MIL-HDBK-217FN2 part stress methods. The at... | the_stack_v2_python_sparse | src/ramstk/gui/gtk/workviews/components/Switch.py | JmiXIII/ramstk | train | 0 |
6274850a7790d0a8aaaf85782329f22aced74784 | [
"self._algo = alg_option\nif alg_option not in [TransitionParser.ARC_STANDARD, TransitionParser.ARC_EAGER]:\n raise ValueError(' Currently we only support %s and %s ' % (TransitionParser.ARC_STANDARD, TransitionParser.ARC_EAGER))",
"if len(conf.buffer) <= 0 or len(conf.stack) <= 0:\n return -1\nif conf.buff... | <|body_start_0|>
self._algo = alg_option
if alg_option not in [TransitionParser.ARC_STANDARD, TransitionParser.ARC_EAGER]:
raise ValueError(' Currently we only support %s and %s ' % (TransitionParser.ARC_STANDARD, TransitionParser.ARC_EAGER))
<|end_body_0|>
<|body_start_1|>
if len(c... | This class defines a set of transition which is applied to a configuration to get another configuration Note that for different parsing algorithm, the transition is different. | Transition | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-NC-ND-3.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transition:
"""This class defines a set of transition which is applied to a configuration to get another configuration Note that for different parsing algorithm, the transition is different."""
def __init__(self, alg_option):
""":param alg_option: the algorithm option of this parser.... | stack_v2_sparse_classes_36k_train_026681 | 31,478 | permissive | [
{
"docstring": ":param alg_option: the algorithm option of this parser. Currently support `arc-standard` and `arc-eager` algorithm :type alg_option: str",
"name": "__init__",
"signature": "def __init__(self, alg_option)"
},
{
"docstring": "Note that the algorithm for left-arc is quite similar ex... | 5 | null | Implement the Python class `Transition` described below.
Class description:
This class defines a set of transition which is applied to a configuration to get another configuration Note that for different parsing algorithm, the transition is different.
Method signatures and docstrings:
- def __init__(self, alg_option)... | Implement the Python class `Transition` described below.
Class description:
This class defines a set of transition which is applied to a configuration to get another configuration Note that for different parsing algorithm, the transition is different.
Method signatures and docstrings:
- def __init__(self, alg_option)... | 582e6e35f0e6c984b44ec49dcb8846d9c011d0a8 | <|skeleton|>
class Transition:
"""This class defines a set of transition which is applied to a configuration to get another configuration Note that for different parsing algorithm, the transition is different."""
def __init__(self, alg_option):
""":param alg_option: the algorithm option of this parser.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transition:
"""This class defines a set of transition which is applied to a configuration to get another configuration Note that for different parsing algorithm, the transition is different."""
def __init__(self, alg_option):
""":param alg_option: the algorithm option of this parser. Currently su... | the_stack_v2_python_sparse | nltk/parse/transitionparser.py | nltk/nltk | train | 11,860 |
fee9ebbf6d5f98f9d836a62e4b639a411861910e | [
"length = len(value)\nactual = ''\nfor x in range(0, length / 2):\n actual += value[length - 2 - 2 * x:length - 2 * x]\n x += 1\nintVal = Util.twosComp(actual)\nreturn intVal",
"firstVal = int(hex_value[:1], 16)\nif firstVal >= 8:\n bValue = bin(int(hex_value, 16))\n bValue = bValue[2:]\n newBinary... | <|body_start_0|>
length = len(value)
actual = ''
for x in range(0, length / 2):
actual += value[length - 2 - 2 * x:length - 2 * x]
x += 1
intVal = Util.twosComp(actual)
return intVal
<|end_body_0|>
<|body_start_1|>
firstVal = int(hex_value[:1], 16... | Util | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Util:
def little_endian(value):
"""littleEndian(value) receives: a parsed, hex data piece outputs: the decimal value of that data function: swaps byte by byte to convert little endian to big endian function: calls 2's compliment to convert to decimal returns: The integer value :param val... | stack_v2_sparse_classes_36k_train_026682 | 2,436 | no_license | [
{
"docstring": "littleEndian(value) receives: a parsed, hex data piece outputs: the decimal value of that data function: swaps byte by byte to convert little endian to big endian function: calls 2's compliment to convert to decimal returns: The integer value :param value: :return:",
"name": "little_endian",... | 2 | stack_v2_sparse_classes_30k_train_008163 | Implement the Python class `Util` described below.
Class description:
Implement the Util class.
Method signatures and docstrings:
- def little_endian(value): littleEndian(value) receives: a parsed, hex data piece outputs: the decimal value of that data function: swaps byte by byte to convert little endian to big endi... | Implement the Python class `Util` described below.
Class description:
Implement the Util class.
Method signatures and docstrings:
- def little_endian(value): littleEndian(value) receives: a parsed, hex data piece outputs: the decimal value of that data function: swaps byte by byte to convert little endian to big endi... | e9edc06adbc3371c1453e0b23bdd098564f73d5e | <|skeleton|>
class Util:
def little_endian(value):
"""littleEndian(value) receives: a parsed, hex data piece outputs: the decimal value of that data function: swaps byte by byte to convert little endian to big endian function: calls 2's compliment to convert to decimal returns: The integer value :param val... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Util:
def little_endian(value):
"""littleEndian(value) receives: a parsed, hex data piece outputs: the decimal value of that data function: swaps byte by byte to convert little endian to big endian function: calls 2's compliment to convert to decimal returns: The integer value :param value: :return:""... | the_stack_v2_python_sparse | raspi-python/raspi/fc/util.py | raman-belsevr/labs | train | 0 | |
ec835ee8511d58a5524d82e5b149e1fc5b27d6bc | [
"user_profile = get_object_or_404(UserProfileModel, account__username=username)\nserializer = self.serializer_class(user_profile)\nreturn Response(serializer.data)",
"if not request.user.is_authenticated:\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid():\n user_profi... | <|body_start_0|>
user_profile = get_object_or_404(UserProfileModel, account__username=username)
serializer = self.serializer_class(user_profile)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
if not request.user.is_authenticated:
serializer = self.serialize... | View for the user profile. Retrieves, creates, Updates and Deletes a User Profile. | UserProfileView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileView:
"""View for the user profile. Retrieves, creates, Updates and Deletes a User Profile."""
def retrieve(self, request, username=None):
"""Retrieves a user profile by its username Checks if a user profile with this username exist, if not, returns HTTP 404 Response. Argu... | stack_v2_sparse_classes_36k_train_026683 | 13,634 | permissive | [
{
"docstring": "Retrieves a user profile by its username Checks if a user profile with this username exist, if not, returns HTTP 404 Response. Arguments: request: the request data sent by the user, it is not used here but required by django username: the username of the user profile that the user wants info abo... | 5 | stack_v2_sparse_classes_30k_train_013600 | Implement the Python class `UserProfileView` described below.
Class description:
View for the user profile. Retrieves, creates, Updates and Deletes a User Profile.
Method signatures and docstrings:
- def retrieve(self, request, username=None): Retrieves a user profile by its username Checks if a user profile with thi... | Implement the Python class `UserProfileView` described below.
Class description:
View for the user profile. Retrieves, creates, Updates and Deletes a User Profile.
Method signatures and docstrings:
- def retrieve(self, request, username=None): Retrieves a user profile by its username Checks if a user profile with thi... | 7c361a31c5225c6ad649fcf92e323bdb10cc4c16 | <|skeleton|>
class UserProfileView:
"""View for the user profile. Retrieves, creates, Updates and Deletes a User Profile."""
def retrieve(self, request, username=None):
"""Retrieves a user profile by its username Checks if a user profile with this username exist, if not, returns HTTP 404 Response. Argu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileView:
"""View for the user profile. Retrieves, creates, Updates and Deletes a User Profile."""
def retrieve(self, request, username=None):
"""Retrieves a user profile by its username Checks if a user profile with this username exist, if not, returns HTTP 404 Response. Arguments: reques... | the_stack_v2_python_sparse | users/views.py | ahmed-alllam/Koshkie-Server | train | 0 |
72a3cadb24e6f2ece3e5abba15f83223eaf65c5e | [
"self.low = []\nheapq.heapify(self.low)\nself.high = []\nheapq.heapify(self.high)",
"heapq.heappush(self.high, num)\nif len(self.high) - len(self.low) > 1:\n temp = heapq.heappop(self.high)\n heapq.heappush(self.low, -1 * temp)",
"if len(self.high) == len(self.low):\n return float((self.high[0] - self.... | <|body_start_0|>
self.low = []
heapq.heapify(self.low)
self.high = []
heapq.heapify(self.high)
<|end_body_0|>
<|body_start_1|>
heapq.heappush(self.high, num)
if len(self.high) - len(self.low) > 1:
temp = heapq.heappop(self.high)
heapq.heappush(sel... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_36k_train_026684 | 958 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds a num into the data structure. :type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": "Returns the ... | 3 | stack_v2_sparse_classes_30k_train_005738 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | b0f85616d10a568d7faef7fef9fff68f8063db7c | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
self.low = []
heapq.heapify(self.low)
self.high = []
heapq.heapify(self.high)
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
h... | the_stack_v2_python_sparse | FindMedicanFromDateStream.py | RengarAndKhz/QuoraInterview | train | 0 | |
120ced6570e0497008be21ec960abef42f8c115e | [
"if src_type not in openOauth.OpenType:\n return jsonify(request_result(706, ret='src_type is error'))\nk = dict()\nk['src_type_arg'] = src_type\nk['user_uuid_arg'] = user_uuid\nrepo_list(kwargs=k)\nreturn jsonify(repo_list(kwargs=k))",
"if src_type not in openOauth.OpenType:\n return jsonify(request_result... | <|body_start_0|>
if src_type not in openOauth.OpenType:
return jsonify(request_result(706, ret='src_type is error'))
k = dict()
k['src_type_arg'] = src_type
k['user_uuid_arg'] = user_uuid
repo_list(kwargs=k)
return jsonify(repo_list(kwargs=k))
<|end_body_0|>
... | OauthRepo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OauthRepo:
def put(self, src_type, user_uuid):
"""@apiGroup OauthRepo @apiDescription 刷新获取用户对应代码平台下的代码项目, 从对应平台获取最新的数据 @apiVersion 2.0.0 @apiHeader {String} token 请求接口的token,放在请求头中 @api {put} /api/v2.0/oauths/repos/<string:src_type>/<string:user_uuid> 刷新代码项目 @apiSuccessExample {json} Suc... | stack_v2_sparse_classes_36k_train_026685 | 5,268 | no_license | [
{
"docstring": "@apiGroup OauthRepo @apiDescription 刷新获取用户对应代码平台下的代码项目, 从对应平台获取最新的数据 @apiVersion 2.0.0 @apiHeader {String} token 请求接口的token,放在请求头中 @api {put} /api/v2.0/oauths/repos/<string:src_type>/<string:user_uuid> 刷新代码项目 @apiSuccessExample {json} Success-Response: status 为 0 成功,其中result-->msg中即用户需要点击进行授权的地址... | 2 | null | Implement the Python class `OauthRepo` described below.
Class description:
Implement the OauthRepo class.
Method signatures and docstrings:
- def put(self, src_type, user_uuid): @apiGroup OauthRepo @apiDescription 刷新获取用户对应代码平台下的代码项目, 从对应平台获取最新的数据 @apiVersion 2.0.0 @apiHeader {String} token 请求接口的token,放在请求头中 @api {put... | Implement the Python class `OauthRepo` described below.
Class description:
Implement the OauthRepo class.
Method signatures and docstrings:
- def put(self, src_type, user_uuid): @apiGroup OauthRepo @apiDescription 刷新获取用户对应代码平台下的代码项目, 从对应平台获取最新的数据 @apiVersion 2.0.0 @apiHeader {String} token 请求接口的token,放在请求头中 @api {put... | 318f85e6ff5542cd70b7a127c0b1d77a01fdf5e3 | <|skeleton|>
class OauthRepo:
def put(self, src_type, user_uuid):
"""@apiGroup OauthRepo @apiDescription 刷新获取用户对应代码平台下的代码项目, 从对应平台获取最新的数据 @apiVersion 2.0.0 @apiHeader {String} token 请求接口的token,放在请求头中 @api {put} /api/v2.0/oauths/repos/<string:src_type>/<string:user_uuid> 刷新代码项目 @apiSuccessExample {json} Suc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OauthRepo:
def put(self, src_type, user_uuid):
"""@apiGroup OauthRepo @apiDescription 刷新获取用户对应代码平台下的代码项目, 从对应平台获取最新的数据 @apiVersion 2.0.0 @apiHeader {String} token 请求接口的token,放在请求头中 @api {put} /api/v2.0/oauths/repos/<string:src_type>/<string:user_uuid> 刷新代码项目 @apiSuccessExample {json} Success-Response:... | the_stack_v2_python_sparse | platform/authServer/v2/oauthclient/oauthrepos.py | woshidashayuchi/boxlinker-all | train | 1 | |
3699b41a41e25df8a448ddde82d9c8bd6dcc5ead | [
"super(RelationalNetwork, self).__init__(params)\nself.cnn_model = ConvInputModel()\nself.pair_network = PairwiseRelationNetwork(params['pair_net'])\nself.sum_network = SumOfPairsAnalysisNetwork(params['sum_net'])",
"coords = torch.linspace(-1 / 2.0, 1 / 2.0, d)\nx = coords.unsqueeze(0).repeat(d, 1)\ny = coords.u... | <|body_start_0|>
super(RelationalNetwork, self).__init__(params)
self.cnn_model = ConvInputModel()
self.pair_network = PairwiseRelationNetwork(params['pair_net'])
self.sum_network = SumOfPairsAnalysisNetwork(params['sum_net'])
<|end_body_0|>
<|body_start_1|>
coords = torch.linsp... | Implementation of the Relational Network model. Reference paper: https://arxiv.org/abs/1706.01427 The CNN model used for the image encoding is located in .conv_input_model.py The MLPs (g_theta & f_phi) are in .functions. | RelationalNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelationalNetwork:
"""Implementation of the Relational Network model. Reference paper: https://arxiv.org/abs/1706.01427 The CNN model used for the image encoding is located in .conv_input_model.py The MLPs (g_theta & f_phi) are in .functions."""
def __init__(self, params):
"""Constru... | stack_v2_sparse_classes_36k_train_026686 | 6,077 | permissive | [
{
"docstring": "Constructor. :param params: dict of parameters.",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Create the tensor containing the spatial relative coordinate of each region (1 pixel) in the feature maps of the ConvInputModel. These spatial relati... | 3 | stack_v2_sparse_classes_30k_train_020087 | Implement the Python class `RelationalNetwork` described below.
Class description:
Implementation of the Relational Network model. Reference paper: https://arxiv.org/abs/1706.01427 The CNN model used for the image encoding is located in .conv_input_model.py The MLPs (g_theta & f_phi) are in .functions.
Method signatu... | Implement the Python class `RelationalNetwork` described below.
Class description:
Implementation of the Relational Network model. Reference paper: https://arxiv.org/abs/1706.01427 The CNN model used for the image encoding is located in .conv_input_model.py The MLPs (g_theta & f_phi) are in .functions.
Method signatu... | c655c88cc6aec4d0724c19ea95209f1c2dd6770d | <|skeleton|>
class RelationalNetwork:
"""Implementation of the Relational Network model. Reference paper: https://arxiv.org/abs/1706.01427 The CNN model used for the image encoding is located in .conv_input_model.py The MLPs (g_theta & f_phi) are in .functions."""
def __init__(self, params):
"""Constru... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelationalNetwork:
"""Implementation of the Relational Network model. Reference paper: https://arxiv.org/abs/1706.01427 The CNN model used for the image encoding is located in .conv_input_model.py The MLPs (g_theta & f_phi) are in .functions."""
def __init__(self, params):
"""Constructor. :param ... | the_stack_v2_python_sparse | models/relational_net/relational_network.py | aasseman/mi-prometheus | train | 0 |
fa6deecde967815892cac53b61d6d4438ea78f10 | [
"def postorder(node):\n if node is None:\n return []\n return postorder(node.left) + postorder(node.right) + [str(node.val)]\nlst = postorder(root)\nreturn '#'.join(lst)",
"if data == '':\n return None\nlst = data.split('#')\nlst = [int(val) for val in lst]\n\ndef buildtree(low, high):\n if len... | <|body_start_0|>
def postorder(node):
if node is None:
return []
return postorder(node.left) + postorder(node.right) + [str(node.val)]
lst = postorder(root)
return '#'.join(lst)
<|end_body_0|>
<|body_start_1|>
if data == '':
return Non... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_026687 | 4,399 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: Optional[TreeNode]) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> Optional[TreeNode... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: Optional[TreeNode]) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> Optional[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: Optional[TreeNode]) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> Optional[TreeNode]: Decodes your encoded data to tree.
<... | 00fd1397b65c68a303fcf963db3e28cd35c1c003 | <|skeleton|>
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> Optional[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: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
def postorder(node):
if node is None:
return []
return postorder(node.left) + postorder(node.right) + [str(node.val)]
lst = postorder(root)
... | the_stack_v2_python_sparse | leetcode/449. Serialize and Deserialize BST.py | cuiy0006/Algorithms | train | 0 | |
6100f1a09996674b67a958a7026ada368ae699fb | [
"nn.Module.__init__(self)\nself.reduction = reduction\nself.criterion = nn.MSELoss(reduction='none')",
"loss = self.criterion(input * mask, target * mask)\nif self.reduction == 'mean':\n loss = torch.sum(loss) / torch.sum(mask)\nreturn loss"
] | <|body_start_0|>
nn.Module.__init__(self)
self.reduction = reduction
self.criterion = nn.MSELoss(reduction='none')
<|end_body_0|>
<|body_start_1|>
loss = self.criterion(input * mask, target * mask)
if self.reduction == 'mean':
loss = torch.sum(loss) / torch.sum(mask)... | Compute the MSE loss only on the masked region. | MaskedMSELoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskedMSELoss:
"""Compute the MSE loss only on the masked region."""
def __init__(self, reduction='mean'):
"""Loss Constructor. ---------- INPUT |---- reduction (str) the reduction to use on the loss. ONLY 'mean' or 'none'. OUTPUT |---- None"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_36k_train_026688 | 18,386 | permissive | [
{
"docstring": "Loss Constructor. ---------- INPUT |---- reduction (str) the reduction to use on the loss. ONLY 'mean' or 'none'. OUTPUT |---- None",
"name": "__init__",
"signature": "def __init__(self, reduction='mean')"
},
{
"docstring": "Forard pass of the loss. The loss is computed only wher... | 2 | stack_v2_sparse_classes_30k_train_009746 | Implement the Python class `MaskedMSELoss` described below.
Class description:
Compute the MSE loss only on the masked region.
Method signatures and docstrings:
- def __init__(self, reduction='mean'): Loss Constructor. ---------- INPUT |---- reduction (str) the reduction to use on the loss. ONLY 'mean' or 'none'. OUT... | Implement the Python class `MaskedMSELoss` described below.
Class description:
Compute the MSE loss only on the masked region.
Method signatures and docstrings:
- def __init__(self, reduction='mean'): Loss Constructor. ---------- INPUT |---- reduction (str) the reduction to use on the loss. ONLY 'mean' or 'none'. OUT... | 850b6195d6290a50eee865b4d5a66f5db5260e8f | <|skeleton|>
class MaskedMSELoss:
"""Compute the MSE loss only on the masked region."""
def __init__(self, reduction='mean'):
"""Loss Constructor. ---------- INPUT |---- reduction (str) the reduction to use on the loss. ONLY 'mean' or 'none'. OUTPUT |---- None"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaskedMSELoss:
"""Compute the MSE loss only on the masked region."""
def __init__(self, reduction='mean'):
"""Loss Constructor. ---------- INPUT |---- reduction (str) the reduction to use on the loss. ONLY 'mean' or 'none'. OUTPUT |---- None"""
nn.Module.__init__(self)
self.reduct... | the_stack_v2_python_sparse | Code/src/models/optim/CustomLosses.py | antoine-spahr/X-ray-Anomaly-Detection | train | 3 |
4df4d6233462111bf0db60982323ccf08ba48edc | [
"if a * b < 0:\n return -(abs(a) / abs(b))\nelse:\n return a / b",
"if not s:\n return 0\nnumstk = []\nnum = 0\nop = '+'\nfor i in xrange(len(s)):\n if s[i].isdigit():\n num = num * 10 + int(s[i])\n if not s[i].isdigit() and s[i] != ' ' or i == len(s) - 1:\n if op == '+' or op == '-':... | <|body_start_0|>
if a * b < 0:
return -(abs(a) / abs(b))
else:
return a / b
<|end_body_0|>
<|body_start_1|>
if not s:
return 0
numstk = []
num = 0
op = '+'
for i in xrange(len(s)):
if s[i].isdigit():
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def divideNeg(self, a, b):
"""python divide -3/2==-2"""
<|body_0|>
def calculate(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if a * b < 0:
return -(abs(a) / abs(b))
else:
... | stack_v2_sparse_classes_36k_train_026689 | 1,319 | permissive | [
{
"docstring": "python divide -3/2==-2",
"name": "divideNeg",
"signature": "def divideNeg(self, a, b)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "calculate",
"signature": "def calculate(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def divideNeg(self, a, b): python divide -3/2==-2
- def calculate(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 divideNeg(self, a, b): python divide -3/2==-2
- def calculate(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def divideNeg(self, a, b):
"""pyth... | 86f1cb98de801f58c39d9a48ce9de12df7303d20 | <|skeleton|>
class Solution:
def divideNeg(self, a, b):
"""python divide -3/2==-2"""
<|body_0|>
def calculate(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 divideNeg(self, a, b):
"""python divide -3/2==-2"""
if a * b < 0:
return -(abs(a) / abs(b))
else:
return a / b
def calculate(self, s):
""":type s: str :rtype: int"""
if not s:
return 0
numstk = []
nu... | the_stack_v2_python_sparse | 227-Basic-Calculator-II/solution.py | Tanych/CodeTracking | train | 0 | |
7fe25ccdb6f04d912678855d66258a35e98c59f6 | [
"tmpdir = tempfile.mkdtemp()\ntestProject = _emulateProject(('testProject1', 'testProject2'))\nbomWriter = BOMWriter(None, 'PythonUnitTesting', testProject, tmpdir)\nbomWriter.writeprojects()\nmyFile = open(tmpdir + '/PythonUnitTesting_projects.txt', 'r')\ncontents = myFile.readlines()\nmyFile.close()\nrmtree(tmpdi... | <|body_start_0|>
tmpdir = tempfile.mkdtemp()
testProject = _emulateProject(('testProject1', 'testProject2'))
bomWriter = BOMWriter(None, 'PythonUnitTesting', testProject, tmpdir)
bomWriter.writeprojects()
myFile = open(tmpdir + '/PythonUnitTesting_projects.txt', 'r')
cont... | Verifiying bomtofile module | BomtofileTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BomtofileTest:
"""Verifiying bomtofile module"""
def test_writeprojects(self):
"""Verifying writeprojects"""
<|body_0|>
def test_writebaselines(self):
"""Verifying writebaselines"""
<|body_1|>
def test_writebaselines_withnodata(self):
"""Veri... | stack_v2_sparse_classes_36k_train_026690 | 3,680 | no_license | [
{
"docstring": "Verifying writeprojects",
"name": "test_writeprojects",
"signature": "def test_writeprojects(self)"
},
{
"docstring": "Verifying writebaselines",
"name": "test_writebaselines",
"signature": "def test_writebaselines(self)"
},
{
"docstring": "Verifying writebaseline... | 4 | null | Implement the Python class `BomtofileTest` described below.
Class description:
Verifiying bomtofile module
Method signatures and docstrings:
- def test_writeprojects(self): Verifying writeprojects
- def test_writebaselines(self): Verifying writebaselines
- def test_writebaselines_withnodata(self): Verifying writebase... | Implement the Python class `BomtofileTest` described below.
Class description:
Verifiying bomtofile module
Method signatures and docstrings:
- def test_writeprojects(self): Verifying writeprojects
- def test_writebaselines(self): Verifying writebaselines
- def test_writebaselines_withnodata(self): Verifying writebase... | f458a4ce83f74d603362fe6b71eaa647ccc62fee | <|skeleton|>
class BomtofileTest:
"""Verifiying bomtofile module"""
def test_writeprojects(self):
"""Verifying writeprojects"""
<|body_0|>
def test_writebaselines(self):
"""Verifying writebaselines"""
<|body_1|>
def test_writebaselines_withnodata(self):
"""Veri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BomtofileTest:
"""Verifiying bomtofile module"""
def test_writeprojects(self):
"""Verifying writeprojects"""
tmpdir = tempfile.mkdtemp()
testProject = _emulateProject(('testProject1', 'testProject2'))
bomWriter = BOMWriter(None, 'PythonUnitTesting', testProject, tmpdir)
... | the_stack_v2_python_sparse | buildframework/helium/sf/python/pythoncore/lib/pythoncoretests/test_bomtofile.py | anagovitsyn/oss.FCL.sftools.dev.build | train | 0 |
75566788896259a138dae63d3619dec704c942d5 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jliang24_tpotye', 'jliang24_tpotye')\nrepo.dropPermanent('aggregatePropertyData')\nrepo.createPermanent('aggregatePropertyData')\nvalueZip = []\nnumBuild = []\nfor entry in repo.jliang24_tpotye.propertie... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jliang24_tpotye', 'jliang24_tpotye')
repo.dropPermanent('aggregatePropertyData')
repo.createPermanent('aggregatePropertyData')
valueZip = ... | aggregateProperty | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class aggregateProperty:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everyt... | stack_v2_sparse_classes_36k_train_026691 | 4,731 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `aggregateProperty` described below.
Class description:
Implement the aggregateProperty class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime... | Implement the Python class `aggregateProperty` described below.
Class description:
Implement the aggregateProperty class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class aggregateProperty:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everyt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class aggregateProperty:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jliang24_tpotye', 'jliang24_tpoty... | the_stack_v2_python_sparse | jliang24_tpotye/aggregateProperty.py | ROODAY/course-2017-fal-proj | train | 3 | |
318c64d010571298d12d991e96ceafc36f7a730a | [
"if not root:\n return 0\nhead = root\nleft_node = []\nright_node = []\ntmp_root = [head]\nwhile tmp_root:\n head = tmp_root.pop()\n if head.left:\n left_node.append(head.left)\n tmp_root.insert(0, head.left)\n if head.right:\n right_node.append(head.right)\n tmp_root.insert(... | <|body_start_0|>
if not root:
return 0
head = root
left_node = []
right_node = []
tmp_root = [head]
while tmp_root:
head = tmp_root.pop()
if head.left:
left_node.append(head.left)
tmp_root.insert(0, head.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumOfLeftLeaves1(self, root):
"""递归版:先判断是不是左树,然后判断是否有左右子节点"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
hea... | stack_v2_sparse_classes_36k_train_026692 | 1,627 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumOfLeftLeaves",
"signature": "def sumOfLeftLeaves(self, root)"
},
{
"docstring": "递归版:先判断是不是左树,然后判断是否有左右子节点",
"name": "sumOfLeftLeaves1",
"signature": "def sumOfLeftLeaves1(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfLeftLeaves(self, root): :type root: TreeNode :rtype: int
- def sumOfLeftLeaves1(self, root): 递归版:先判断是不是左树,然后判断是否有左右子节点 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfLeftLeaves(self, root): :type root: TreeNode :rtype: int
- def sumOfLeftLeaves1(self, root): 递归版:先判断是不是左树,然后判断是否有左右子节点
<|skeleton|>
class Solution:
def sumOfLeftLe... | 18c06a96bb14688e4a1d5fb6baf235a6b53bd3ae | <|skeleton|>
class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumOfLeftLeaves1(self, root):
"""递归版:先判断是不是左树,然后判断是否有左右子节点"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
head = root
left_node = []
right_node = []
tmp_root = [head]
while tmp_root:
head = tmp_root.pop()
if head.left:
... | the_stack_v2_python_sparse | easy/sum-of-left-leaves.py | congyingTech/Basic-Algorithm | train | 10 | |
0d65ecbbb78339ad30ca9eaf86e5ca5e500f4017 | [
"if weights is None:\n self.weights = [0, 0, 0]\nelse:\n self.weights = weights[:]\nself.alpha = alpha",
"y_hat = self.weights[-1]\nfor ii in range(len(x_vector)):\n y_hat += self.weights[ii] * x_vector[ii]\nif y_hat >= 0:\n return 1.0\nelse:\n return -1.0",
"y_hat = self.classify(x_vector)\nif y... | <|body_start_0|>
if weights is None:
self.weights = [0, 0, 0]
else:
self.weights = weights[:]
self.alpha = alpha
<|end_body_0|>
<|body_start_1|>
y_hat = self.weights[-1]
for ii in range(len(x_vector)):
y_hat += self.weights[ii] * x_vector[ii]
... | Class representing the Binary Perceptron --- It is an algorithm that can learn a binary classifier | BinaryPerceptron | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryPerceptron:
"""Class representing the Binary Perceptron --- It is an algorithm that can learn a binary classifier"""
def __init__(self, weights=None, alpha=0.5):
"""Initialize the Binary Perceptron --- weights: Weight vector of the form [w_0, w_1, ..., w_{n-1}, bias_weight] alp... | stack_v2_sparse_classes_36k_train_026693 | 4,625 | no_license | [
{
"docstring": "Initialize the Binary Perceptron --- weights: Weight vector of the form [w_0, w_1, ..., w_{n-1}, bias_weight] alpha: Learning rate",
"name": "__init__",
"signature": "def __init__(self, weights=None, alpha=0.5)"
},
{
"docstring": "Method that classifies a given data point into on... | 4 | stack_v2_sparse_classes_30k_train_014952 | Implement the Python class `BinaryPerceptron` described below.
Class description:
Class representing the Binary Perceptron --- It is an algorithm that can learn a binary classifier
Method signatures and docstrings:
- def __init__(self, weights=None, alpha=0.5): Initialize the Binary Perceptron --- weights: Weight vec... | Implement the Python class `BinaryPerceptron` described below.
Class description:
Class representing the Binary Perceptron --- It is an algorithm that can learn a binary classifier
Method signatures and docstrings:
- def __init__(self, weights=None, alpha=0.5): Initialize the Binary Perceptron --- weights: Weight vec... | 05620c2e7f2afe54027cdb3f6cb9eca52de377b5 | <|skeleton|>
class BinaryPerceptron:
"""Class representing the Binary Perceptron --- It is an algorithm that can learn a binary classifier"""
def __init__(self, weights=None, alpha=0.5):
"""Initialize the Binary Perceptron --- weights: Weight vector of the form [w_0, w_1, ..., w_{n-1}, bias_weight] alp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinaryPerceptron:
"""Class representing the Binary Perceptron --- It is an algorithm that can learn a binary classifier"""
def __init__(self, weights=None, alpha=0.5):
"""Initialize the Binary Perceptron --- weights: Weight vector of the form [w_0, w_1, ..., w_{n-1}, bias_weight] alpha: Learning ... | the_stack_v2_python_sparse | A6/a6-starter-files/a6-starter-files/binary_perceptron.py | mccullohg/McCulloh-CSE-415 | train | 1 |
00c14cb5bd0632b595243826eff880a6fc1add65 | [
"self.pump = Pump('127.0.0.1', 8000)\nself.decider = Decider(100, 0.05)\nself.sensor = Sensor('127.0.0.1', '8001')\nself.controller = Controller(self.sensor, self.pump, self.decider)\nself.actions = self.controller.actions",
"self.assertEqual(self.decider.decide(90, self.actions['PUMP_OFF'], self.actions), self.a... | <|body_start_0|>
self.pump = Pump('127.0.0.1', 8000)
self.decider = Decider(100, 0.05)
self.sensor = Sensor('127.0.0.1', '8001')
self.controller = Controller(self.sensor, self.pump, self.decider)
self.actions = self.controller.actions
<|end_body_0|>
<|body_start_1|>
self... | Unit tests for the Decider class | DeciderTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeciderTests:
"""Unit tests for the Decider class"""
def setUp(self):
"""setup"""
<|body_0|>
def test_decider(self):
"""Decider tests"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pump = Pump('127.0.0.1', 8000)
self.decider = Deci... | stack_v2_sparse_classes_36k_train_026694 | 3,712 | no_license | [
{
"docstring": "setup",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Decider tests",
"name": "test_decider",
"signature": "def test_decider(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021177 | Implement the Python class `DeciderTests` described below.
Class description:
Unit tests for the Decider class
Method signatures and docstrings:
- def setUp(self): setup
- def test_decider(self): Decider tests | Implement the Python class `DeciderTests` described below.
Class description:
Unit tests for the Decider class
Method signatures and docstrings:
- def setUp(self): setup
- def test_decider(self): Decider tests
<|skeleton|>
class DeciderTests:
"""Unit tests for the Decider class"""
def setUp(self):
"... | 263685ca90110609bfd05d621516727f8cd0028f | <|skeleton|>
class DeciderTests:
"""Unit tests for the Decider class"""
def setUp(self):
"""setup"""
<|body_0|>
def test_decider(self):
"""Decider tests"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeciderTests:
"""Unit tests for the Decider class"""
def setUp(self):
"""setup"""
self.pump = Pump('127.0.0.1', 8000)
self.decider = Decider(100, 0.05)
self.sensor = Sensor('127.0.0.1', '8001')
self.controller = Controller(self.sensor, self.pump, self.decider)
... | the_stack_v2_python_sparse | students/msirisha/lesson06/water-regulation/waterregulation/tests.py | aurel1212/Sp2018-Online | train | 0 |
ff3f3253645e4f2610ce8bee536cc94a836e9e4b | [
"QgsMapTool.__init__(self, Globs.iface.mapCanvas())\nself.action = action\nself.action.setChecked(False)\nself.layer_group = ['INTERSECTION', 'NORMAL', 'OTHER', 'UNKNOWN']\nself.layer_waypoints = None\nself.layer_route = None",
"super(LaneViewer, self).activate()\nself.__calculate_Lane_IDs__()\nself.action.setChe... | <|body_start_0|>
QgsMapTool.__init__(self, Globs.iface.mapCanvas())
self.action = action
self.action.setChecked(False)
self.layer_group = ['INTERSECTION', 'NORMAL', 'OTHER', 'UNKNOWN']
self.layer_waypoints = None
self.layer_route = None
<|end_body_0|>
<|body_start_1|>
... | ... | LaneViewer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LaneViewer:
"""..."""
def __init__(self, action):
"""..."""
<|body_0|>
def activate(self):
"""..."""
<|body_1|>
def deactivate(self):
"""..."""
<|body_2|>
def __calculate_Lane_IDs__(self):
"""..."""
<|body_3|>
<|... | stack_v2_sparse_classes_36k_train_026695 | 2,781 | permissive | [
{
"docstring": "...",
"name": "__init__",
"signature": "def __init__(self, action)"
},
{
"docstring": "...",
"name": "activate",
"signature": "def activate(self)"
},
{
"docstring": "...",
"name": "deactivate",
"signature": "def deactivate(self)"
},
{
"docstring": ... | 4 | stack_v2_sparse_classes_30k_train_009434 | Implement the Python class `LaneViewer` described below.
Class description:
...
Method signatures and docstrings:
- def __init__(self, action): ...
- def activate(self): ...
- def deactivate(self): ...
- def __calculate_Lane_IDs__(self): ... | Implement the Python class `LaneViewer` described below.
Class description:
...
Method signatures and docstrings:
- def __init__(self, action): ...
- def activate(self): ...
- def deactivate(self): ...
- def __calculate_Lane_IDs__(self): ...
<|skeleton|>
class LaneViewer:
"""..."""
def __init__(self, action... | cc9618fd005bc28ad08d0f89f30911bb7a75a41e | <|skeleton|>
class LaneViewer:
"""..."""
def __init__(self, action):
"""..."""
<|body_0|>
def activate(self):
"""..."""
<|body_1|>
def deactivate(self):
"""..."""
<|body_2|>
def __calculate_Lane_IDs__(self):
"""..."""
<|body_3|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LaneViewer:
"""..."""
def __init__(self, action):
"""..."""
QgsMapTool.__init__(self, Globs.iface.mapCanvas())
self.action = action
self.action.setChecked(False)
self.layer_group = ['INTERSECTION', 'NORMAL', 'OTHER', 'UNKNOWN']
self.layer_waypoints = None
... | the_stack_v2_python_sparse | tools/ad_map_access_qgis/ad_map_access_qgis/LaneViewer.py | carla-simulator/map | train | 87 |
f35fed08f143761fe680b809b2a5573cbd5f4dbc | [
"if not root:\n return 0\nif not root.left:\n return self.minDepth_MK1(root.right) + 1\nif not root.right:\n return self.minDepth_MK1(root.left) + 1\nreturn min(self.minDepth_MK1(root.left), self.minDepth_MK1(root.right)) + 1",
"if not root:\n return 0\ndeq = deque([(root, 1)])\nwhile deq:\n node, ... | <|body_start_0|>
if not root:
return 0
if not root.left:
return self.minDepth_MK1(root.right) + 1
if not root.right:
return self.minDepth_MK1(root.left) + 1
return min(self.minDepth_MK1(root.left), self.minDepth_MK1(root.right)) + 1
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth_MK1(self, root: TreeNode) -> int:
"""DFS"""
<|body_0|>
def minDepth_MK2(self, root: TreeNode) -> int:
"""BFS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
if not root.left:
... | stack_v2_sparse_classes_36k_train_026696 | 1,001 | no_license | [
{
"docstring": "DFS",
"name": "minDepth_MK1",
"signature": "def minDepth_MK1(self, root: TreeNode) -> int"
},
{
"docstring": "BFS",
"name": "minDepth_MK2",
"signature": "def minDepth_MK2(self, root: TreeNode) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_002985 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth_MK1(self, root: TreeNode) -> int: DFS
- def minDepth_MK2(self, root: TreeNode) -> int: BFS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth_MK1(self, root: TreeNode) -> int: DFS
- def minDepth_MK2(self, root: TreeNode) -> int: BFS
<|skeleton|>
class Solution:
def minDepth_MK1(self, root: TreeNode) ... | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | <|skeleton|>
class Solution:
def minDepth_MK1(self, root: TreeNode) -> int:
"""DFS"""
<|body_0|>
def minDepth_MK2(self, root: TreeNode) -> int:
"""BFS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth_MK1(self, root: TreeNode) -> int:
"""DFS"""
if not root:
return 0
if not root.left:
return self.minDepth_MK1(root.right) + 1
if not root.right:
return self.minDepth_MK1(root.left) + 1
return min(self.minDepth_MK... | the_stack_v2_python_sparse | 0111. Minimum Depth of Binary Tree/Solution.py | faterazer/LeetCode | train | 4 | |
f51e1d097372a31ab33b82037a7d422a477cf4e6 | [
"attrs = self.entity.attributes\ndevice_class: event.EventDeviceClass | None = attrs.get(ATTR_DEVICE_CLASS)\nif device_class == event.EventDeviceClass.DOORBELL:\n return [DisplayCategory.DOORBELL]\nreturn None",
"if self.default_display_categories() is not None:\n yield AlexaDoorbellEventSource(self.entity)... | <|body_start_0|>
attrs = self.entity.attributes
device_class: event.EventDeviceClass | None = attrs.get(ATTR_DEVICE_CLASS)
if device_class == event.EventDeviceClass.DOORBELL:
return [DisplayCategory.DOORBELL]
return None
<|end_body_0|>
<|body_start_1|>
if self.defaul... | Class to represent doorbel event capabilities. | EventCapabilities | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventCapabilities:
"""Class to represent doorbel event capabilities."""
def default_display_categories(self) -> list[str] | None:
"""Return the display categories for this entity."""
<|body_0|>
def interfaces(self) -> Generator[AlexaCapability, None, None]:
"""Yi... | stack_v2_sparse_classes_36k_train_026697 | 35,310 | permissive | [
{
"docstring": "Return the display categories for this entity.",
"name": "default_display_categories",
"signature": "def default_display_categories(self) -> list[str] | None"
},
{
"docstring": "Yield the supported interfaces.",
"name": "interfaces",
"signature": "def interfaces(self) -> ... | 2 | null | Implement the Python class `EventCapabilities` described below.
Class description:
Class to represent doorbel event capabilities.
Method signatures and docstrings:
- def default_display_categories(self) -> list[str] | None: Return the display categories for this entity.
- def interfaces(self) -> Generator[AlexaCapabi... | Implement the Python class `EventCapabilities` described below.
Class description:
Class to represent doorbel event capabilities.
Method signatures and docstrings:
- def default_display_categories(self) -> list[str] | None: Return the display categories for this entity.
- def interfaces(self) -> Generator[AlexaCapabi... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EventCapabilities:
"""Class to represent doorbel event capabilities."""
def default_display_categories(self) -> list[str] | None:
"""Return the display categories for this entity."""
<|body_0|>
def interfaces(self) -> Generator[AlexaCapability, None, None]:
"""Yi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventCapabilities:
"""Class to represent doorbel event capabilities."""
def default_display_categories(self) -> list[str] | None:
"""Return the display categories for this entity."""
attrs = self.entity.attributes
device_class: event.EventDeviceClass | None = attrs.get(ATTR_DEVICE... | the_stack_v2_python_sparse | homeassistant/components/alexa/entities.py | home-assistant/core | train | 35,501 |
0e96cdca18e894f539d0e2289f5557943f0046f3 | [
"for cq in variant['transcript_consequences']:\n if 'gene_symbol' not in cq:\n continue\n if cq['gene_symbol'] != gene:\n continue\n if cq['biotype'] not in ['protein_coding', 'polymorphic_pseudogene']:\n continue\n if vep_cq not in cq['consequence_terms'] and (vep_cq == 'conserved_... | <|body_start_0|>
for cq in variant['transcript_consequences']:
if 'gene_symbol' not in cq:
continue
if cq['gene_symbol'] != gene:
continue
if cq['biotype'] not in ['protein_coding', 'polymorphic_pseudogene']:
continue
... | this class extends the EnsemblRequest class from denovonear, in order to extract HGVS codes for variants from the ensembl REST API. | EnsemblVariant | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnsemblVariant:
"""this class extends the EnsemblRequest class from denovonear, in order to extract HGVS codes for variants from the ensembl REST API."""
def parse_alternate_consequences(self, variant, gene, vep_cq):
"""at the moment we're looking for the HGVS nomenclature for the ca... | stack_v2_sparse_classes_36k_train_026698 | 4,213 | no_license | [
{
"docstring": "at the moment we're looking for the HGVS nomenclature for the canonical transcript, where that transcript needs to match our most severe consequence. TODO: I might need to shift this to using HGVS nomenclature for the longest protein_coding transcript, where that transcript consequence matches o... | 2 | null | Implement the Python class `EnsemblVariant` described below.
Class description:
this class extends the EnsemblRequest class from denovonear, in order to extract HGVS codes for variants from the ensembl REST API.
Method signatures and docstrings:
- def parse_alternate_consequences(self, variant, gene, vep_cq): at the ... | Implement the Python class `EnsemblVariant` described below.
Class description:
this class extends the EnsemblRequest class from denovonear, in order to extract HGVS codes for variants from the ensembl REST API.
Method signatures and docstrings:
- def parse_alternate_consequences(self, variant, gene, vep_cq): at the ... | 244b11a041ef2f80320690cf9f39e95aba5f14ec | <|skeleton|>
class EnsemblVariant:
"""this class extends the EnsemblRequest class from denovonear, in order to extract HGVS codes for variants from the ensembl REST API."""
def parse_alternate_consequences(self, variant, gene, vep_cq):
"""at the moment we're looking for the HGVS nomenclature for the ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnsemblVariant:
"""this class extends the EnsemblRequest class from denovonear, in order to extract HGVS codes for variants from the ensembl REST API."""
def parse_alternate_consequences(self, variant, gene, vep_cq):
"""at the moment we're looking for the HGVS nomenclature for the canonical trans... | the_stack_v2_python_sparse | ddd_4k/ensembl_variant.py | jeremymcrae/ddd_4k | train | 0 |
b46a84277a6d9518a138f81436506fdb86067d43 | [
"self.wallx = 400\nself.pineUp = pygame.image.load('bird/top.png')\nself.pineDown = pygame.image.load('bird/bottom.png')",
"self.wallx -= 5\nif self.wallx < -50:\n global score\n score += 1\n self.wallx = 400"
] | <|body_start_0|>
self.wallx = 400
self.pineUp = pygame.image.load('bird/top.png')
self.pineDown = pygame.image.load('bird/bottom.png')
<|end_body_0|>
<|body_start_1|>
self.wallx -= 5
if self.wallx < -50:
global score
score += 1
self.wallx = 40... | 定义一个管道类 | Pipline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pipline:
"""定义一个管道类"""
def __init__(self):
"""定义管道类初始化方法"""
<|body_0|>
def UpdatePipe(self):
"""定义移动方法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.wallx = 400
self.pineUp = pygame.image.load('bird/top.png')
self.pineDown... | stack_v2_sparse_classes_36k_train_026699 | 7,811 | no_license | [
{
"docstring": "定义管道类初始化方法",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "定义移动方法",
"name": "UpdatePipe",
"signature": "def UpdatePipe(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018878 | Implement the Python class `Pipline` described below.
Class description:
定义一个管道类
Method signatures and docstrings:
- def __init__(self): 定义管道类初始化方法
- def UpdatePipe(self): 定义移动方法 | Implement the Python class `Pipline` described below.
Class description:
定义一个管道类
Method signatures and docstrings:
- def __init__(self): 定义管道类初始化方法
- def UpdatePipe(self): 定义移动方法
<|skeleton|>
class Pipline:
"""定义一个管道类"""
def __init__(self):
"""定义管道类初始化方法"""
<|body_0|>
def UpdatePipe(sel... | b2bf7ac34ccbb1e37a63109049607408f5487e8b | <|skeleton|>
class Pipline:
"""定义一个管道类"""
def __init__(self):
"""定义管道类初始化方法"""
<|body_0|>
def UpdatePipe(self):
"""定义移动方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pipline:
"""定义一个管道类"""
def __init__(self):
"""定义管道类初始化方法"""
self.wallx = 400
self.pineUp = pygame.image.load('bird/top.png')
self.pineDown = pygame.image.load('bird/bottom.png')
def UpdatePipe(self):
"""定义移动方法"""
self.wallx -= 5
if self.wallx <... | the_stack_v2_python_sparse | Python-2D游戏/pygame游戏开发.py | kyon1920/Python | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.