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
707fb53fbb7901bd72a6135f32bd4a95698d59f7
[ "with mock.patch('bisect_clang.execute') as mock_execute:\n mock_execute.return_value = (None, 'mips', None)\n with self.assertRaises(Exception):\n bisect_clang.get_clang_target_arch()", "arch_pairs = {'x86_64': 'X86', 'aarch64': 'AArch64'}\nfor uname_result, clang_target in arch_pairs.items():\n ...
<|body_start_0|> with mock.patch('bisect_clang.execute') as mock_execute: mock_execute.return_value = (None, 'mips', None) with self.assertRaises(Exception): bisect_clang.get_clang_target_arch() <|end_body_0|> <|body_start_1|> arch_pairs = {'x86_64': 'X86', 'aarc...
Tests for get_target_arch_to_build.
GetTargetArchToBuildTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetTargetArchToBuildTest: """Tests for get_target_arch_to_build.""" def test_unrecognized(self): """Test that an unrecognized architecture raises an exception.""" <|body_0|> def test_recognized(self): """Test that a recognized architecture returns the expected va...
stack_v2_sparse_classes_36k_train_020400
11,288
permissive
[ { "docstring": "Test that an unrecognized architecture raises an exception.", "name": "test_unrecognized", "signature": "def test_unrecognized(self)" }, { "docstring": "Test that a recognized architecture returns the expected value.", "name": "test_recognized", "signature": "def test_rec...
2
null
Implement the Python class `GetTargetArchToBuildTest` described below. Class description: Tests for get_target_arch_to_build. Method signatures and docstrings: - def test_unrecognized(self): Test that an unrecognized architecture raises an exception. - def test_recognized(self): Test that a recognized architecture re...
Implement the Python class `GetTargetArchToBuildTest` described below. Class description: Tests for get_target_arch_to_build. Method signatures and docstrings: - def test_unrecognized(self): Test that an unrecognized architecture raises an exception. - def test_recognized(self): Test that a recognized architecture re...
f0275421f84b8f80ee767fb9230134ac97cb687b
<|skeleton|> class GetTargetArchToBuildTest: """Tests for get_target_arch_to_build.""" def test_unrecognized(self): """Test that an unrecognized architecture raises an exception.""" <|body_0|> def test_recognized(self): """Test that a recognized architecture returns the expected va...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetTargetArchToBuildTest: """Tests for get_target_arch_to_build.""" def test_unrecognized(self): """Test that an unrecognized architecture raises an exception.""" with mock.patch('bisect_clang.execute') as mock_execute: mock_execute.return_value = (None, 'mips', None) ...
the_stack_v2_python_sparse
infra/base-images/base-builder/bisect_clang_test.py
google/oss-fuzz
train
9,438
27a55142a0835d99f741eafdf3e263040f7fae36
[ "actual = a1.stock_price_summary([0.01, 0.03, -0.02, -0.14, 0, 0, 0.1, -0.01])\nexpected = (0.14, -0.17)\nself.assertEqual(actual, expected)", "actual = actual = a1.stock_price_summary([-0.01, -0.03, 0.02, 0.14, 0, 0, -0.1, 0.01])\nexpected = (0.17, -0.14)\nself.assertEqual(actual, expected)", "actual = a1.stoc...
<|body_start_0|> actual = a1.stock_price_summary([0.01, 0.03, -0.02, -0.14, 0, 0, 0.1, -0.01]) expected = (0.14, -0.17) self.assertEqual(actual, expected) <|end_body_0|> <|body_start_1|> actual = actual = a1.stock_price_summary([-0.01, -0.03, 0.02, 0.14, 0, 0, -0.1, 0.01]) expec...
Test class for function a1.stock_price_summary.
TestStockPriceSummary
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestStockPriceSummary: """Test class for function a1.stock_price_summary.""" def test_random1(self): """Test the function with random numbers""" <|body_0|> def test_random2(self): """Test the function with inverted random numbers""" <|body_1|> def te...
stack_v2_sparse_classes_36k_train_020401
1,114
no_license
[ { "docstring": "Test the function with random numbers", "name": "test_random1", "signature": "def test_random1(self)" }, { "docstring": "Test the function with inverted random numbers", "name": "test_random2", "signature": "def test_random2(self)" }, { "docstring": "The the funct...
4
stack_v2_sparse_classes_30k_train_005829
Implement the Python class `TestStockPriceSummary` described below. Class description: Test class for function a1.stock_price_summary. Method signatures and docstrings: - def test_random1(self): Test the function with random numbers - def test_random2(self): Test the function with inverted random numbers - def test_z...
Implement the Python class `TestStockPriceSummary` described below. Class description: Test class for function a1.stock_price_summary. Method signatures and docstrings: - def test_random1(self): Test the function with random numbers - def test_random2(self): Test the function with inverted random numbers - def test_z...
ba0e48825e3f90f9da0e7506c89354622198c4a5
<|skeleton|> class TestStockPriceSummary: """Test class for function a1.stock_price_summary.""" def test_random1(self): """Test the function with random numbers""" <|body_0|> def test_random2(self): """Test the function with inverted random numbers""" <|body_1|> def te...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestStockPriceSummary: """Test class for function a1.stock_price_summary.""" def test_random1(self): """Test the function with random numbers""" actual = a1.stock_price_summary([0.01, 0.03, -0.02, -0.14, 0, 0, 0.1, -0.01]) expected = (0.14, -0.17) self.assertEqual(actual, ...
the_stack_v2_python_sparse
Coursera/Python3/Second Course Asignments/Assighment 1/test_stock_price_summary.py
Vutov/SideProjects
train
0
24b8fedff852ed30439b772a21d8802eaa222d89
[ "dp = [[[0] * n for _ in range(m)] for _ in range(N + 1)]\nfor s in range(1, N + 1):\n for x in range(m):\n for y in range(n):\n v1 = 1 if x == 0 else dp[s - 1][x - 1][y]\n v2 = 1 if x == m - 1 else dp[s - 1][x + 1][y]\n v3 = 1 if y == 0 else dp[s - 1][x][y - 1]\n ...
<|body_start_0|> dp = [[[0] * n for _ in range(m)] for _ in range(N + 1)] for s in range(1, N + 1): for x in range(m): for y in range(n): v1 = 1 if x == 0 else dp[s - 1][x - 1][y] v2 = 1 if x == m - 1 else dp[s - 1][x + 1][y] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findPaths(self, m, n, N, i, j): """:type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int""" <|body_0|> def findPaths(self, m, n, N, i, j): """:type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int""" ...
stack_v2_sparse_classes_36k_train_020402
4,620
no_license
[ { "docstring": ":type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int", "name": "findPaths", "signature": "def findPaths(self, m, n, N, i, j)" }, { "docstring": ":type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int", "name": "findPaths", "si...
2
stack_v2_sparse_classes_30k_train_017637
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findPaths(self, m, n, N, i, j): :type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int - def findPaths(self, m, n, N, i, j): :type m: int :type n: int :...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findPaths(self, m, n, N, i, j): :type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int - def findPaths(self, m, n, N, i, j): :type m: int :type n: int :...
035ef08434fa1ca781a6fb2f9eed3538b7d20c02
<|skeleton|> class Solution: def findPaths(self, m, n, N, i, j): """:type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int""" <|body_0|> def findPaths(self, m, n, N, i, j): """:type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findPaths(self, m, n, N, i, j): """:type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int""" dp = [[[0] * n for _ in range(m)] for _ in range(N + 1)] for s in range(1, N + 1): for x in range(m): for y in range(n): ...
the_stack_v2_python_sparse
leetcode_python/Dynamic_Programming/out-of-boundary-paths.py
yennanliu/CS_basics
train
64
ef5b7cf85a12f231ba18e16859e72ff226528d31
[ "self.avg = trial_stats()\nself.min = trial_stats()\nself.max = trial_stats()\nself.ts = list()\nfor x in range(t):\n self.ts.append(trial_stats())", "a = trial_stats()\nmin = trial_stats()\nmax = trial_stats()\nmin.ts_copy(self.ts[0])\nmax.ts_copy(self.ts[0])\nfor x in self.ts:\n if x.cpuhrs_charged < min....
<|body_start_0|> self.avg = trial_stats() self.min = trial_stats() self.max = trial_stats() self.ts = list() for x in range(t): self.ts.append(trial_stats()) <|end_body_0|> <|body_start_1|> a = trial_stats() min = trial_stats() max = trial_sta...
keeps track of all the trials for a particular experiment variation (distinct combination of config files, resource files and command line options)
trial_tracker
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class trial_tracker: """keeps track of all the trials for a particular experiment variation (distinct combination of config files, resource files and command line options)""" def __init__(self, t): """create a new trial_tracker object with ``t`` trials""" <|body_0|> def minmax...
stack_v2_sparse_classes_36k_train_020403
19,091
permissive
[ { "docstring": "create a new trial_tracker object with ``t`` trials", "name": "__init__", "signature": "def __init__(self, t)" }, { "docstring": "calculates the min, max and avg over the trials", "name": "minmaxavg", "signature": "def minmaxavg(self)" } ]
2
stack_v2_sparse_classes_30k_train_018347
Implement the Python class `trial_tracker` described below. Class description: keeps track of all the trials for a particular experiment variation (distinct combination of config files, resource files and command line options) Method signatures and docstrings: - def __init__(self, t): create a new trial_tracker objec...
Implement the Python class `trial_tracker` described below. Class description: keeps track of all the trials for a particular experiment variation (distinct combination of config files, resource files and command line options) Method signatures and docstrings: - def __init__(self, t): create a new trial_tracker objec...
6f02737d4754731a25dd33759594402ea7f4cfba
<|skeleton|> class trial_tracker: """keeps track of all the trials for a particular experiment variation (distinct combination of config files, resource files and command line options)""" def __init__(self, t): """create a new trial_tracker object with ``t`` trials""" <|body_0|> def minmax...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class trial_tracker: """keeps track of all the trials for a particular experiment variation (distinct combination of config files, resource files and command line options)""" def __init__(self, t): """create a new trial_tracker object with ``t`` trials""" self.avg = trial_stats() self.m...
the_stack_v2_python_sparse
ipsframework/utils/RUS/run_exps.py
HPC-SimTools/IPS-framework
train
11
ef0bd32bee8cd011b3906adad6cbf5380274736c
[ "if channel is None:\n raise ChannelAuthenicationException(_('Channel authentication failed. Please revise your certificate.'))\nif not channel.enabled:\n raise ChannelAuthenicationException(_('Channel authentication failed. Channel is disable.'))", "session = session_services.get_session(ticket, False)\ncu...
<|body_start_0|> if channel is None: raise ChannelAuthenicationException(_('Channel authentication failed. Please revise your certificate.')) if not channel.enabled: raise ChannelAuthenicationException(_('Channel authentication failed. Channel is disable.')) <|end_body_0|> <|bod...
Handles channel authentication.
ChannelAuthenicator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChannelAuthenicator: """Handles channel authentication.""" def _verify_channel(self, channel, **options): """Verifies general conditions on the given channel @param channel: channel instance""" <|body_0|> def authenticate(self, ticket, certificate, **options): ""...
stack_v2_sparse_classes_36k_train_020404
3,773
no_license
[ { "docstring": "Verifies general conditions on the given channel @param channel: channel instance", "name": "_verify_channel", "signature": "def _verify_channel(self, channel, **options)" }, { "docstring": "Authenticates a certificate considering the given ticket. @param ticket: ticket @param ce...
3
stack_v2_sparse_classes_30k_train_009706
Implement the Python class `ChannelAuthenicator` described below. Class description: Handles channel authentication. Method signatures and docstrings: - def _verify_channel(self, channel, **options): Verifies general conditions on the given channel @param channel: channel instance - def authenticate(self, ticket, cer...
Implement the Python class `ChannelAuthenicator` described below. Class description: Handles channel authentication. Method signatures and docstrings: - def _verify_channel(self, channel, **options): Verifies general conditions on the given channel @param channel: channel instance - def authenticate(self, ticket, cer...
a2ee333d2a4fe9821f3d24ee15d458f226ffcde5
<|skeleton|> class ChannelAuthenicator: """Handles channel authentication.""" def _verify_channel(self, channel, **options): """Verifies general conditions on the given channel @param channel: channel instance""" <|body_0|> def authenticate(self, ticket, certificate, **options): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChannelAuthenicator: """Handles channel authentication.""" def _verify_channel(self, channel, **options): """Verifies general conditions on the given channel @param channel: channel instance""" if channel is None: raise ChannelAuthenicationException(_('Channel authentication f...
the_stack_v2_python_sparse
src/deltapy/security/channel/authenticator/authenticator.py
hamed1361554/sportmagazine-server
train
0
c9d10b381ed2ea6290aaedc117d814c3ed43cbc6
[ "if len(matrix) == 0 or len(matrix[0]) == 0:\n return 0\ndp = [0] * len(matrix[0])\nmax_rect = 0\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == '1':\n dp[j] = dp[j] + 1\n else:\n dp[j] = 0\n area = self.largestRectangleArea(dp)\n ...
<|body_start_0|> if len(matrix) == 0 or len(matrix[0]) == 0: return 0 dp = [0] * len(matrix[0]) max_rect = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == '1': dp[j] = dp[j] + 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: """m = len of rows n = len of colums Time Complexity = O(m*n) Space Complexity = O(n)""" <|body_0|> def largestRectangleArea(self, heights: List[int]) -> int: """Time Complexity = O(n) Space Comple...
stack_v2_sparse_classes_36k_train_020405
2,315
no_license
[ { "docstring": "m = len of rows n = len of colums Time Complexity = O(m*n) Space Complexity = O(n)", "name": "maximalRectangle", "signature": "def maximalRectangle(self, matrix: List[List[str]]) -> int" }, { "docstring": "Time Complexity = O(n) Space Complexity = O(n)", "name": "largestRecta...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maximalRectangle(self, matrix: List[List[str]]) -> int: m = len of rows n = len of colums Time Complexity = O(m*n) Space Complexity = O(n) - def largestRectangleArea(self, he...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maximalRectangle(self, matrix: List[List[str]]) -> int: m = len of rows n = len of colums Time Complexity = O(m*n) Space Complexity = O(n) - def largestRectangleArea(self, he...
8e116c21f91c87a9dc8526d8be93c443e79469bf
<|skeleton|> class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: """m = len of rows n = len of colums Time Complexity = O(m*n) Space Complexity = O(n)""" <|body_0|> def largestRectangleArea(self, heights: List[int]) -> int: """Time Complexity = O(n) Space Comple...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: """m = len of rows n = len of colums Time Complexity = O(m*n) Space Complexity = O(n)""" if len(matrix) == 0 or len(matrix[0]) == 0: return 0 dp = [0] * len(matrix[0]) max_rect = 0 for i i...
the_stack_v2_python_sparse
Hard/85_hard_maximal-rectangle.py
sarahgonsalves223/DSA_Python
train
2
8fb19d8590fe4071c00fc36b6ce2f053654701ce
[ "empty = UniqueKeyFunction.FLAG_EMPTY_REGISTER\ncollision = UniqueKeyFunction.FLAG_COLLIDED_REGISTER\nif x == empty and y == empty:\n return empty\nif x == collision or y == collision:\n return collision\nif x == empty:\n return y\nif y == empty:\n return x\nif x == y:\n return x\nreturn collision", ...
<|body_start_0|> empty = UniqueKeyFunction.FLAG_EMPTY_REGISTER collision = UniqueKeyFunction.FLAG_COLLIDED_REGISTER if x == empty and y == empty: return empty if x == collision or y == collision: return collision if x == empty: return y ...
ValueFunction to track the state of unique key of a register.
UniqueKeyFunction
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UniqueKeyFunction: """ValueFunction to track the state of unique key of a register.""" def __call__(self, x, y): """ValueFunction to track the state of unique key of a register. Args: x: A state of unique key. It can be either a real key (hashed ID) indicating the unique key in the r...
stack_v2_sparse_classes_36k_train_020406
13,872
permissive
[ { "docstring": "ValueFunction to track the state of unique key of a register. Args: x: A state of unique key. It can be either a real key (hashed ID) indicating the unique key in the register, or FLAG_EMPTY_REGISTER indicating that the register is empty, or FLAG_COLLIDED_REGISTER indicating that the register al...
2
stack_v2_sparse_classes_30k_train_016584
Implement the Python class `UniqueKeyFunction` described below. Class description: ValueFunction to track the state of unique key of a register. Method signatures and docstrings: - def __call__(self, x, y): ValueFunction to track the state of unique key of a register. Args: x: A state of unique key. It can be either ...
Implement the Python class `UniqueKeyFunction` described below. Class description: ValueFunction to track the state of unique key of a register. Method signatures and docstrings: - def __call__(self, x, y): ValueFunction to track the state of unique key of a register. Args: x: A state of unique key. It can be either ...
1727e9545a8f219b543c1b67da6b6653e36d931e
<|skeleton|> class UniqueKeyFunction: """ValueFunction to track the state of unique key of a register.""" def __call__(self, x, y): """ValueFunction to track the state of unique key of a register. Args: x: A state of unique key. It can be either a real key (hashed ID) indicating the unique key in the r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UniqueKeyFunction: """ValueFunction to track the state of unique key of a register.""" def __call__(self, x, y): """ValueFunction to track the state of unique key of a register. Args: x: A state of unique key. It can be either a real key (hashed ID) indicating the unique key in the register, or F...
the_stack_v2_python_sparse
src/estimators/any_sketch.py
world-federation-of-advertisers/cardinality_estimation_evaluation_framework
train
21
720214dd3834052e0e580b8015b734859e538679
[ "self.A: np.ndarray = A\nself.y: np.ndarray = y\nself.params: Union[np.ndarray, None] = params\nself.resids: Union[np.ndarray, None] = resids\nself.weights: Union[np.ndarray, None] = weights\nself.scale: Union[float, None] = scale\nself.method: Union[str, None] = method\nself.nobservations = self.y.size\nself.npred...
<|body_start_0|> self.A: np.ndarray = A self.y: np.ndarray = y self.params: Union[np.ndarray, None] = params self.resids: Union[np.ndarray, None] = resids self.weights: Union[np.ndarray, None] = weights self.scale: Union[float, None] = scale self.method: Union[str...
Class for holding regression data Attributes ---------- A : np.ndarray The predictors y : np.ndarray The observations params : np.ndarray, None, optional The model solution resids : np.ndarray, None, optional The residuals weights : np.ndarray, None, optional The weights scale : float The estimate of scale method : str...
RegressionData
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegressionData: """Class for holding regression data Attributes ---------- A : np.ndarray The predictors y : np.ndarray The observations params : np.ndarray, None, optional The model solution resids : np.ndarray, None, optional The residuals weights : np.ndarray, None, optional The weights scale ...
stack_v2_sparse_classes_36k_train_020407
5,467
permissive
[ { "docstring": "Initialise with predictors and observations Paramters --------- A : np.ndarray The predictors y : np.ndarray The observations params : np.ndarray, None, optional The model solution resids : np.ndarray, None, optional The residuals weights : np.ndarray, None, optional The weights scale : float Th...
5
null
Implement the Python class `RegressionData` described below. Class description: Class for holding regression data Attributes ---------- A : np.ndarray The predictors y : np.ndarray The observations params : np.ndarray, None, optional The model solution resids : np.ndarray, None, optional The residuals weights : np.nda...
Implement the Python class `RegressionData` described below. Class description: Class for holding regression data Attributes ---------- A : np.ndarray The predictors y : np.ndarray The observations params : np.ndarray, None, optional The model solution resids : np.ndarray, None, optional The residuals weights : np.nda...
a93040521fd6506929a59c363ee58b7ca073bac1
<|skeleton|> class RegressionData: """Class for holding regression data Attributes ---------- A : np.ndarray The predictors y : np.ndarray The observations params : np.ndarray, None, optional The model solution resids : np.ndarray, None, optional The residuals weights : np.ndarray, None, optional The weights scale ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RegressionData: """Class for holding regression data Attributes ---------- A : np.ndarray The predictors y : np.ndarray The observations params : np.ndarray, None, optional The model solution resids : np.ndarray, None, optional The residuals weights : np.ndarray, None, optional The weights scale : float The e...
the_stack_v2_python_sparse
resistics/regression/data.py
Nishikinor/resistics
train
0
66d960d1a2a86b0b6faadb3bd35bc097982ad4db
[ "ds_type = cfg['dataset'] + '_' + cfg['agent_setting'] + '_' + cfg['input_representation']\nspec_args = get_specific_args(cfg['dataset'], data_root, cfg['version'] if 'version' in cfg.keys() else None)[0]\ntest_set = initialize_dataset(ds_type, ['load_data', data_dir, cfg['test_set_args']] + spec_args)\nif 'scout' ...
<|body_start_0|> ds_type = cfg['dataset'] + '_' + cfg['agent_setting'] + '_' + cfg['input_representation'] spec_args = get_specific_args(cfg['dataset'], data_root, cfg['version'] if 'version' in cfg.keys() else None)[0] test_set = initialize_dataset(ds_type, ['load_data', data_dir, cfg['test_set...
Class for evaluating trained models
Evaluator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Evaluator: """Class for evaluating trained models""" def __init__(self, cfg: Dict, data_root: str, data_dir: str, checkpoint_path: str): """Initialize evaluator object :param cfg: Configuration parameters :param data_root: Root directory with data :param data_dir: Directory with extr...
stack_v2_sparse_classes_36k_train_020408
6,980
permissive
[ { "docstring": "Initialize evaluator object :param cfg: Configuration parameters :param data_root: Root directory with data :param data_dir: Directory with extracted, pre-processed data :param checkpoint_path: Path to checkpoint with trained weights", "name": "__init__", "signature": "def __init__(self,...
6
stack_v2_sparse_classes_30k_train_019065
Implement the Python class `Evaluator` described below. Class description: Class for evaluating trained models Method signatures and docstrings: - def __init__(self, cfg: Dict, data_root: str, data_dir: str, checkpoint_path: str): Initialize evaluator object :param cfg: Configuration parameters :param data_root: Root...
Implement the Python class `Evaluator` described below. Class description: Class for evaluating trained models Method signatures and docstrings: - def __init__(self, cfg: Dict, data_root: str, data_dir: str, checkpoint_path: str): Initialize evaluator object :param cfg: Configuration parameters :param data_root: Root...
6419894aa040adb9570b14493952a98c0a52f803
<|skeleton|> class Evaluator: """Class for evaluating trained models""" def __init__(self, cfg: Dict, data_root: str, data_dir: str, checkpoint_path: str): """Initialize evaluator object :param cfg: Configuration parameters :param data_root: Root directory with data :param data_dir: Directory with extr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Evaluator: """Class for evaluating trained models""" def __init__(self, cfg: Dict, data_root: str, data_dir: str, checkpoint_path: str): """Initialize evaluator object :param cfg: Configuration parameters :param data_root: Root directory with data :param data_dir: Directory with extracted, pre-pr...
the_stack_v2_python_sparse
train_eval/evaluator.py
sancarlim/Explainable-MP
train
17
5147d34ecfc6b527fd51933e7284ec4dc3a242ee
[ "self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]", "while len(self.x_values) < self.num_points:\n x_direction = choice([1, -1])\n x_distance = choice([0, 1, 2, 3, 4])\n x_step = x_direction * x_distance\n y_direction = choice([1, -1])\n y_distance = choice([0, 1, 2, 3, 4])\n ...
<|body_start_0|> self.num_points = num_points self.x_values = [0] self.y_values = [0] <|end_body_0|> <|body_start_1|> while len(self.x_values) < self.num_points: x_direction = choice([1, -1]) x_distance = choice([0, 1, 2, 3, 4]) x_step = x_direction *...
一个生成随机漫步数据的类
RandomWalk
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomWalk: """一个生成随机漫步数据的类""" def __init__(self, num_points=1000): """初始化随机漫步的属性""" <|body_0|> def fill_walk(self): """计算随机漫步包含的所有的点""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.num_points = num_points self.x_values = [0] ...
stack_v2_sparse_classes_36k_train_020409
1,958
no_license
[ { "docstring": "初始化随机漫步的属性", "name": "__init__", "signature": "def __init__(self, num_points=1000)" }, { "docstring": "计算随机漫步包含的所有的点", "name": "fill_walk", "signature": "def fill_walk(self)" } ]
2
stack_v2_sparse_classes_30k_train_006219
Implement the Python class `RandomWalk` described below. Class description: 一个生成随机漫步数据的类 Method signatures and docstrings: - def __init__(self, num_points=1000): 初始化随机漫步的属性 - def fill_walk(self): 计算随机漫步包含的所有的点
Implement the Python class `RandomWalk` described below. Class description: 一个生成随机漫步数据的类 Method signatures and docstrings: - def __init__(self, num_points=1000): 初始化随机漫步的属性 - def fill_walk(self): 计算随机漫步包含的所有的点 <|skeleton|> class RandomWalk: """一个生成随机漫步数据的类""" def __init__(self, num_points=1000): """...
2ca11f1df6444eb721da9f110d94af76c91b42ef
<|skeleton|> class RandomWalk: """一个生成随机漫步数据的类""" def __init__(self, num_points=1000): """初始化随机漫步的属性""" <|body_0|> def fill_walk(self): """计算随机漫步包含的所有的点""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomWalk: """一个生成随机漫步数据的类""" def __init__(self, num_points=1000): """初始化随机漫步的属性""" self.num_points = num_points self.x_values = [0] self.y_values = [0] def fill_walk(self): """计算随机漫步包含的所有的点""" while len(self.x_values) < self.num_points: x...
the_stack_v2_python_sparse
py-visualization/random_walk.py
newming/PythonLearn
train
0
2ec53fde41f2d896b232499807c47198f6e3799d
[ "d = {}\nans = i = 0\nfor j, c in enumerate(s):\n if c in d and d[c] >= i:\n i = d[c] + 1\n d[c] = j\n ans = max(ans, j - i + 1)\nreturn ans", "d = set()\nans = i = 0\nfor j, c in enumerate(s):\n while c in d:\n d.remove(s[i])\n i += 1\n d.add(c)\n ans = max(ans, j - i + 1)\...
<|body_start_0|> d = {} ans = i = 0 for j, c in enumerate(s): if c in d and d[c] >= i: i = d[c] + 1 d[c] = j ans = max(ans, j - i + 1) return ans <|end_body_0|> <|body_start_1|> d = set() ans = i = 0 for j, c in...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lengthOfLongestSubstring(self, s: str) -> int: """Sliding window 개선.""" <|body_0|> def lengthOfLongestSubstring1(self, s: str) -> int: """Sliding window""" <|body_1|> <|end_skeleton|> <|body_start_0|> d = {} ans = i = 0 ...
stack_v2_sparse_classes_36k_train_020410
673
no_license
[ { "docstring": "Sliding window 개선.", "name": "lengthOfLongestSubstring", "signature": "def lengthOfLongestSubstring(self, s: str) -> int" }, { "docstring": "Sliding window", "name": "lengthOfLongestSubstring1", "signature": "def lengthOfLongestSubstring1(self, s: str) -> int" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLongestSubstring(self, s: str) -> int: Sliding window 개선. - def lengthOfLongestSubstring1(self, s: str) -> int: Sliding window
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLongestSubstring(self, s: str) -> int: Sliding window 개선. - def lengthOfLongestSubstring1(self, s: str) -> int: Sliding window <|skeleton|> class Solution: def ...
c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1
<|skeleton|> class Solution: def lengthOfLongestSubstring(self, s: str) -> int: """Sliding window 개선.""" <|body_0|> def lengthOfLongestSubstring1(self, s: str) -> int: """Sliding window""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: """Sliding window 개선.""" d = {} ans = i = 0 for j, c in enumerate(s): if c in d and d[c] >= i: i = d[c] + 1 d[c] = j ans = max(ans, j - i + 1) return ans ...
the_stack_v2_python_sparse
Leetcode/3.py
hanwgyu/algorithm_problem_solving
train
5
b6356a866194bef1500ffd86dc866a3851d5cfff
[ "def restoreSplittedIpAddresses(s):\n memo = {}\n if s in memo:\n return memo[s]\n if len(s) == 0:\n return [[]]\n elif len(s) == 1:\n return [[s]]\n ret = []\n if len(s) >= 3 and s[0] != '0' and (int(s[:3]) < 256):\n ret.extend([[s[:3]] + sub for sub in restoreSplitted...
<|body_start_0|> def restoreSplittedIpAddresses(s): memo = {} if s in memo: return memo[s] if len(s) == 0: return [[]] elif len(s) == 1: return [[s]] ret = [] if len(s) >= 3 and s[0] != '0' an...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def restoreIpAddresses(self, s): """May 06, 2018 03:02""" <|body_0|> def restoreIpAddresses(self, s: str) -> List[str]: """Mar 05, 2023 23:02""" <|body_1|> <|end_skeleton|> <|body_start_0|> def restoreSplittedIpAddresses(s): me...
stack_v2_sparse_classes_36k_train_020411
3,039
no_license
[ { "docstring": "May 06, 2018 03:02", "name": "restoreIpAddresses", "signature": "def restoreIpAddresses(self, s)" }, { "docstring": "Mar 05, 2023 23:02", "name": "restoreIpAddresses", "signature": "def restoreIpAddresses(self, s: str) -> List[str]" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def restoreIpAddresses(self, s): May 06, 2018 03:02 - def restoreIpAddresses(self, s: str) -> List[str]: Mar 05, 2023 23:02
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def restoreIpAddresses(self, s): May 06, 2018 03:02 - def restoreIpAddresses(self, s: str) -> List[str]: Mar 05, 2023 23:02 <|skeleton|> class Solution: def restoreIpAddres...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def restoreIpAddresses(self, s): """May 06, 2018 03:02""" <|body_0|> def restoreIpAddresses(self, s: str) -> List[str]: """Mar 05, 2023 23:02""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def restoreIpAddresses(self, s): """May 06, 2018 03:02""" def restoreSplittedIpAddresses(s): memo = {} if s in memo: return memo[s] if len(s) == 0: return [[]] elif len(s) == 1: return [[s...
the_stack_v2_python_sparse
leetcode/solved/93_Restore_IP_Addresses/solution.py
sungminoh/algorithms
train
0
51671e0eb5829e6c208b4dd7afd3867a921e3492
[ "p = hyperparams.Params()\nif not m:\n return p\ndesc = 'See comments for {msg} for description'.format(msg=m.full_name)\nfor f in m.fields:\n if f.containing_oneof:\n continue\n if omit and f.full_name in omit:\n continue\n if f.label == descriptor.FieldDescriptor.LABEL_REPEATED:\n ...
<|body_start_0|> p = hyperparams.Params() if not m: return p desc = 'See comments for {msg} for description'.format(msg=m.full_name) for f in m.fields: if f.containing_oneof: continue if omit and f.full_name in omit: con...
Generate default hyper params for dynamic config components.
Util
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Util: """Generate default hyper params for dynamic config components.""" def CreateParamsForMessage(cls, m, omit=None): """Proto to hyper params conversion. Method will define hyperparameters matching a protocol message. Each field added will match the proto field names. Nested messa...
stack_v2_sparse_classes_36k_train_020412
4,230
permissive
[ { "docstring": "Proto to hyper params conversion. Method will define hyperparameters matching a protocol message. Each field added will match the proto field names. Nested messages will be added recursively. Parameters will be initialized to None or the empty list. Note that one_of messages are skipped and no h...
3
stack_v2_sparse_classes_30k_train_010576
Implement the Python class `Util` described below. Class description: Generate default hyper params for dynamic config components. Method signatures and docstrings: - def CreateParamsForMessage(cls, m, omit=None): Proto to hyper params conversion. Method will define hyperparameters matching a protocol message. Each f...
Implement the Python class `Util` described below. Class description: Generate default hyper params for dynamic config components. Method signatures and docstrings: - def CreateParamsForMessage(cls, m, omit=None): Proto to hyper params conversion. Method will define hyperparameters matching a protocol message. Each f...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class Util: """Generate default hyper params for dynamic config components.""" def CreateParamsForMessage(cls, m, omit=None): """Proto to hyper params conversion. Method will define hyperparameters matching a protocol message. Each field added will match the proto field names. Nested messa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Util: """Generate default hyper params for dynamic config components.""" def CreateParamsForMessage(cls, m, omit=None): """Proto to hyper params conversion. Method will define hyperparameters matching a protocol message. Each field added will match the proto field names. Nested messages will be a...
the_stack_v2_python_sparse
cognate_inpaint_neighbors/neighbors/model/util.py
Jimmy-INL/google-research
train
1
4b5d352a66bb73ab2584b8d98c7027f01debcbe4
[ "repo_query = model.repository.get_user_starred_repositories(get_authenticated_user())\nrepos, next_page_token = model.modelutil.paginate(repo_query, RepositoryTable, page_token=page_token, limit=REPOS_PER_PAGE)\n\ndef repo_view(repo_obj):\n return {'namespace': repo_obj.namespace_user.username, 'name': repo_obj...
<|body_start_0|> repo_query = model.repository.get_user_starred_repositories(get_authenticated_user()) repos, next_page_token = model.modelutil.paginate(repo_query, RepositoryTable, page_token=page_token, limit=REPOS_PER_PAGE) def repo_view(repo_obj): return {'namespace': repo_obj.n...
Operations for creating and listing starred repositories.
StarredRepositoryList
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StarredRepositoryList: """Operations for creating and listing starred repositories.""" def get(self, page_token, parsed_args): """List all starred repositories.""" <|body_0|> def post(self): """Star a repository.""" <|body_1|> <|end_skeleton|> <|body_st...
stack_v2_sparse_classes_36k_train_020413
44,442
permissive
[ { "docstring": "List all starred repositories.", "name": "get", "signature": "def get(self, page_token, parsed_args)" }, { "docstring": "Star a repository.", "name": "post", "signature": "def post(self)" } ]
2
null
Implement the Python class `StarredRepositoryList` described below. Class description: Operations for creating and listing starred repositories. Method signatures and docstrings: - def get(self, page_token, parsed_args): List all starred repositories. - def post(self): Star a repository.
Implement the Python class `StarredRepositoryList` described below. Class description: Operations for creating and listing starred repositories. Method signatures and docstrings: - def get(self, page_token, parsed_args): List all starred repositories. - def post(self): Star a repository. <|skeleton|> class StarredRe...
e400a0c22c5f89dd35d571654b13d262b1f6e3b3
<|skeleton|> class StarredRepositoryList: """Operations for creating and listing starred repositories.""" def get(self, page_token, parsed_args): """List all starred repositories.""" <|body_0|> def post(self): """Star a repository.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StarredRepositoryList: """Operations for creating and listing starred repositories.""" def get(self, page_token, parsed_args): """List all starred repositories.""" repo_query = model.repository.get_user_starred_repositories(get_authenticated_user()) repos, next_page_token = model....
the_stack_v2_python_sparse
endpoints/api/user.py
quay/quay
train
2,363
2dbfc183a5864f6724f23a69cc44bc9a53a2156b
[ "res = {}\ntotal_capacity = 0.0\nfor rec in self:\n emp_bed = 0.0\n for bed in rec.bed_ids:\n if not bed.employee_id:\n emp_bed += 1\n rec.available_beds = emp_bed", "for rooms_rec in self:\n accomodation_id = rooms_rec.accommodation_id and rooms_rec.accommodation_id.id or False\n ...
<|body_start_0|> res = {} total_capacity = 0.0 for rec in self: emp_bed = 0.0 for bed in rec.bed_ids: if not bed.employee_id: emp_bed += 1 rec.available_beds = emp_bed <|end_body_0|> <|body_start_1|> for rooms_rec i...
room_room
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class room_room: def _beds_available(self): """This method is used to total calculate on available beds of employee -------------------------------------------------------------- @param self : Records set @multi : The decorator of multi""" <|body_0|> def check_bed_ids(self): ...
stack_v2_sparse_classes_36k_train_020414
24,603
no_license
[ { "docstring": "This method is used to total calculate on available beds of employee -------------------------------------------------------------- @param self : Records set @multi : The decorator of multi", "name": "_beds_available", "signature": "def _beds_available(self)" }, { "docstring": "T...
2
stack_v2_sparse_classes_30k_train_005217
Implement the Python class `room_room` described below. Class description: Implement the room_room class. Method signatures and docstrings: - def _beds_available(self): This method is used to total calculate on available beds of employee -------------------------------------------------------------- @param self : Rec...
Implement the Python class `room_room` described below. Class description: Implement the room_room class. Method signatures and docstrings: - def _beds_available(self): This method is used to total calculate on available beds of employee -------------------------------------------------------------- @param self : Rec...
46e15330b5d642053da61754247f3fbf9d02717e
<|skeleton|> class room_room: def _beds_available(self): """This method is used to total calculate on available beds of employee -------------------------------------------------------------- @param self : Records set @multi : The decorator of multi""" <|body_0|> def check_bed_ids(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class room_room: def _beds_available(self): """This method is used to total calculate on available beds of employee -------------------------------------------------------------- @param self : Records set @multi : The decorator of multi""" res = {} total_capacity = 0.0 for rec in sel...
the_stack_v2_python_sparse
core/sg_accommodation/models/accommodation_agreement.py
Muhammad-SF/Test
train
0
50d5c05c97933ecd8ce69e03b0618b7156dc5400
[ "self.root = TrieNode()\nfor word in words:\n self.insert(word)", "cur_node = self.root\nfor char in word:\n if char not in cur_node.children:\n cur_node.children[char] = TrieNode()\n cur_node = cur_node.children[char]\ncur_node.is_word = True" ]
<|body_start_0|> self.root = TrieNode() for word in words: self.insert(word) <|end_body_0|> <|body_start_1|> cur_node = self.root for char in word: if char not in cur_node.children: cur_node.children[char] = TrieNode() cur_node = cur_n...
Trie
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Trie: def __init__(self, words): """Initialize your data structure here.""" <|body_0|> def insert(self, word: str) -> None: """Inserts a word into the trie.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.root = TrieNode() for word in w...
stack_v2_sparse_classes_36k_train_020415
1,970
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self, words)" }, { "docstring": "Inserts a word into the trie.", "name": "insert", "signature": "def insert(self, word: str) -> None" } ]
2
null
Implement the Python class `Trie` described below. Class description: Implement the Trie class. Method signatures and docstrings: - def __init__(self, words): Initialize your data structure here. - def insert(self, word: str) -> None: Inserts a word into the trie.
Implement the Python class `Trie` described below. Class description: Implement the Trie class. Method signatures and docstrings: - def __init__(self, words): Initialize your data structure here. - def insert(self, word: str) -> None: Inserts a word into the trie. <|skeleton|> class Trie: def __init__(self, wor...
020bffbd14ca9993f1e678181ee7df761f1533de
<|skeleton|> class Trie: def __init__(self, words): """Initialize your data structure here.""" <|body_0|> def insert(self, word: str) -> None: """Inserts a word into the trie.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Trie: def __init__(self, words): """Initialize your data structure here.""" self.root = TrieNode() for word in words: self.insert(word) def insert(self, word: str) -> None: """Inserts a word into the trie.""" cur_node = self.root for char in wor...
the_stack_v2_python_sparse
leetcode/learn-cards/trie/05_word_search_II.py
Zahidsqldba07/coding-problems-2
train
0
f9c5bcea20a8d0bdd41c3c6b3dbd4eb347316576
[ "super().__init__()\nself.num_classes = classes_n\nself.linear = LinearPolicy(inp_n, hidden_size, hidden_size, num_layers - 1, activation_fn)\nlast_in_n = inp_n\nif num_layers > 1:\n self.linear = nn.Sequential(self.linear, activation_fn())\n last_in_n = hidden_size\nself.value = nn.Linear(last_in_n, out_n * ...
<|body_start_0|> super().__init__() self.num_classes = classes_n self.linear = LinearPolicy(inp_n, hidden_size, hidden_size, num_layers - 1, activation_fn) last_in_n = inp_n if num_layers > 1: self.linear = nn.Sequential(self.linear, activation_fn()) last_...
A simple multi-categorical policy.
MultiCategoricalPolicy
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiCategoricalPolicy: """A simple multi-categorical policy.""" def __init__(self, inp_n: int, out_n: int, classes_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module): """Creates the gaussian policy. Args: inp_n: The number of input units to the network. out_n: The ...
stack_v2_sparse_classes_36k_train_020416
6,947
permissive
[ { "docstring": "Creates the gaussian policy. Args: inp_n: The number of input units to the network. out_n: The number of independent categorical distributions. classes_n: The number of classes per category. hidden_size: The number of units in each hidden layer. num_layers: The number of layers before the gaussi...
2
null
Implement the Python class `MultiCategoricalPolicy` described below. Class description: A simple multi-categorical policy. Method signatures and docstrings: - def __init__(self, inp_n: int, out_n: int, classes_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module): Creates the gaussian policy. Args: inp...
Implement the Python class `MultiCategoricalPolicy` described below. Class description: A simple multi-categorical policy. Method signatures and docstrings: - def __init__(self, inp_n: int, out_n: int, classes_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module): Creates the gaussian policy. Args: inp...
cde3be1c69bfd76fe4a78fa529e851d0a78318c7
<|skeleton|> class MultiCategoricalPolicy: """A simple multi-categorical policy.""" def __init__(self, inp_n: int, out_n: int, classes_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module): """Creates the gaussian policy. Args: inp_n: The number of input units to the network. out_n: The ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiCategoricalPolicy: """A simple multi-categorical policy.""" def __init__(self, inp_n: int, out_n: int, classes_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module): """Creates the gaussian policy. Args: inp_n: The number of input units to the network. out_n: The number of ind...
the_stack_v2_python_sparse
hlrl/torch/policies/distribution.py
Chainso/HLRL
train
3
6f7b9a779abd8fe5f117f7610525cc19a0a63d52
[ "super().__init__()\nself._initialize_arguments(args)\nself.embedding = nn.Linear(self.input_dim, self.rnn_units)\ntorch.nn.init.normal_(self.embedding.weight)\nself.gat_layers = nn.ModuleList([gat_cell.GATGRUCell(args) for _ in range(self.num_rnn_layers)])\nself.dropout = nn.Dropout(self.dropout)\nself.tanh = nn.T...
<|body_start_0|> super().__init__() self._initialize_arguments(args) self.embedding = nn.Linear(self.input_dim, self.rnn_units) torch.nn.init.normal_(self.embedding.weight) self.gat_layers = nn.ModuleList([gat_cell.GATGRUCell(args) for _ in range(self.num_rnn_layers)]) se...
Implements GATRNN encoder model. Encodes the input time series sequence to the hidden vector.
Encoder
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Encoder: """Implements GATRNN encoder model. Encodes the input time series sequence to the hidden vector.""" def __init__(self, args): """Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, we only use model-related arguments here.""" <|bo...
stack_v2_sparse_classes_36k_train_020417
13,550
permissive
[ { "docstring": "Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, we only use model-related arguments here.", "name": "__init__", "signature": "def __init__(self, args)" }, { "docstring": "Encoder forward pass. Args: inputs: input one-step time series, with...
2
stack_v2_sparse_classes_30k_train_011042
Implement the Python class `Encoder` described below. Class description: Implements GATRNN encoder model. Encodes the input time series sequence to the hidden vector. Method signatures and docstrings: - def __init__(self, args): Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, ...
Implement the Python class `Encoder` described below. Class description: Implements GATRNN encoder model. Encodes the input time series sequence to the hidden vector. Method signatures and docstrings: - def __init__(self, args): Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, ...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class Encoder: """Implements GATRNN encoder model. Encodes the input time series sequence to the hidden vector.""" def __init__(self, args): """Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, we only use model-related arguments here.""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Encoder: """Implements GATRNN encoder model. Encodes the input time series sequence to the hidden vector.""" def __init__(self, args): """Instantiates the GATRNN encoder model. Args: args: python argparse.ArgumentParser class, we only use model-related arguments here.""" super().__init__(...
the_stack_v2_python_sparse
editable_graph_temporal/model/gat_model.py
Jimmy-INL/google-research
train
1
2df4ccc94811bbbea5d5bc9ef22f5f56b0c66963
[ "running_instances = session.query(FtaSolutionsAppAlarminstance).filter_by(status=status)\nrunning_instance_ids = [a.id for a in running_instances]\nlogger.info('running alarm[%s](%s): %s', status, running_instances.count(), running_instance_ids)\nredis_key = 'QOS_RUNNING_%s' % status\nhis_data = redis_cache.get(re...
<|body_start_0|> running_instances = session.query(FtaSolutionsAppAlarminstance).filter_by(status=status) running_instance_ids = [a.id for a in running_instances] logger.info('running alarm[%s](%s): %s', status, running_instances.count(), running_instance_ids) redis_key = 'QOS_RUNNING_%s...
Qos
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSL-1.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Qos: def check_blocked(self, status): """get block whether happened in sqecial topic by alarm_instance's status :param status: which status""" <|body_0|> def _mark_alarm_to_notice(self, status, tot_count, blocked_instance_ids): """mark alarm_instance status to 'for_n...
stack_v2_sparse_classes_36k_train_020418
7,722
permissive
[ { "docstring": "get block whether happened in sqecial topic by alarm_instance's status :param status: which status", "name": "check_blocked", "signature": "def check_blocked(self, status)" }, { "docstring": "mark alarm_instance status to 'for_notice' and pass solution :param status: which status...
4
null
Implement the Python class `Qos` described below. Class description: Implement the Qos class. Method signatures and docstrings: - def check_blocked(self, status): get block whether happened in sqecial topic by alarm_instance's status :param status: which status - def _mark_alarm_to_notice(self, status, tot_count, blo...
Implement the Python class `Qos` described below. Class description: Implement the Qos class. Method signatures and docstrings: - def check_blocked(self, status): get block whether happened in sqecial topic by alarm_instance's status :param status: which status - def _mark_alarm_to_notice(self, status, tot_count, blo...
a50a3c498c39b14e7df4a0a960c2a1499b1ec6bb
<|skeleton|> class Qos: def check_blocked(self, status): """get block whether happened in sqecial topic by alarm_instance's status :param status: which status""" <|body_0|> def _mark_alarm_to_notice(self, status, tot_count, blocked_instance_ids): """mark alarm_instance status to 'for_n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Qos: def check_blocked(self, status): """get block whether happened in sqecial topic by alarm_instance's status :param status: which status""" running_instances = session.query(FtaSolutionsAppAlarminstance).filter_by(status=status) running_instance_ids = [a.id for a in running_instance...
the_stack_v2_python_sparse
server/fta/qos/process.py
huang1125677925/fta
train
0
dc6bd3a04cd09990d622b8b0c07fda1f951001c0
[ "assert issubclass(work_session_model, WorkSession), 'You should define working session model properly'\nself._logger = logging.getLogger('vulyk.app')\nself.work_session = work_session_model", "try:\n existing = self.work_session.objects(user=user_id, task=task, task_type=task.task_type).modify(upsert=True, se...
<|body_start_0|> assert issubclass(work_session_model, WorkSession), 'You should define working session model properly' self._logger = logging.getLogger('vulyk.app') self.work_session = work_session_model <|end_body_0|> <|body_start_1|> try: existing = self.work_session.obje...
This class is responsible for accounting of work-sessions. Every time we give a task to user, a new session record is being created. If user skips the task, we mark it as skipped and delete the session. When user finishes the task, we close the session having added the timestamp of the event. Thus we're able to perform...
WorkSessionManager
[ "LicenseRef-scancode-proprietary-license", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WorkSessionManager: """This class is responsible for accounting of work-sessions. Every time we give a task to user, a new session record is being created. If user skips the task, we mark it as skipped and delete the session. When user finishes the task, we close the session having added the time...
stack_v2_sparse_classes_36k_train_020419
6,649
permissive
[ { "docstring": "Constructor. :param work_session_model: Underlying mongoDB Document subclass. :type work_session_model: Type", "name": "__init__", "signature": "def __init__(self, work_session_model: Type[U]) -> None" }, { "docstring": "Starts new WorkSession for given user. By default we use `d...
5
stack_v2_sparse_classes_30k_train_015906
Implement the Python class `WorkSessionManager` described below. Class description: This class is responsible for accounting of work-sessions. Every time we give a task to user, a new session record is being created. If user skips the task, we mark it as skipped and delete the session. When user finishes the task, we ...
Implement the Python class `WorkSessionManager` described below. Class description: This class is responsible for accounting of work-sessions. Every time we give a task to user, a new session record is being created. If user skips the task, we mark it as skipped and delete the session. When user finishes the task, we ...
dd89a1fdacc322a43090169aae9e36f03f1b55c2
<|skeleton|> class WorkSessionManager: """This class is responsible for accounting of work-sessions. Every time we give a task to user, a new session record is being created. If user skips the task, we mark it as skipped and delete the session. When user finishes the task, we close the session having added the time...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WorkSessionManager: """This class is responsible for accounting of work-sessions. Every time we give a task to user, a new session record is being created. If user skips the task, we mark it as skipped and delete the session. When user finishes the task, we close the session having added the timestamp of the ...
the_stack_v2_python_sparse
vulyk/ext/worksession.py
mrgambal/vulyk
train
34
44eb4f972be21afe0fea55ea0494c28252f1053d
[ "w = self.out.write\nif o.labels:\n w('# ')\n if o.labels:\n w(o.labels[0])\nw('\\n')\nself.visit_doc(o)\nself.visit_iHdlStatement(o.body)", "self.visit_doc(o)\nw = self.out.write\nfor is_last, i in iter_with_last(o.body):\n self.visit_iHdlStatement(i)\n if not is_last:\n w(',\\n')", "...
<|body_start_0|> w = self.out.write if o.labels: w('# ') if o.labels: w(o.labels[0]) w('\n') self.visit_doc(o) self.visit_iHdlStatement(o.body) <|end_body_0|> <|body_start_1|> self.visit_doc(o) w = self.out.write fo...
ToHwtStm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ToHwtStm: def visit_HdlStmProcess(self, o): """:type o: HdlStmProcess""" <|body_0|> def visit_HdlStmBlock(self, o): """:type o: HdlStmBlock""" <|body_1|> def visit_HdlStmIf(self, o): """:type stm: HdlStmIf if cond: ... else: ... will become c, cV...
stack_v2_sparse_classes_36k_train_020420
3,549
permissive
[ { "docstring": ":type o: HdlStmProcess", "name": "visit_HdlStmProcess", "signature": "def visit_HdlStmProcess(self, o)" }, { "docstring": ":type o: HdlStmBlock", "name": "visit_HdlStmBlock", "signature": "def visit_HdlStmBlock(self, o)" }, { "docstring": ":type stm: HdlStmIf if c...
5
stack_v2_sparse_classes_30k_train_008673
Implement the Python class `ToHwtStm` described below. Class description: Implement the ToHwtStm class. Method signatures and docstrings: - def visit_HdlStmProcess(self, o): :type o: HdlStmProcess - def visit_HdlStmBlock(self, o): :type o: HdlStmBlock - def visit_HdlStmIf(self, o): :type stm: HdlStmIf if cond: ... el...
Implement the Python class `ToHwtStm` described below. Class description: Implement the ToHwtStm class. Method signatures and docstrings: - def visit_HdlStmProcess(self, o): :type o: HdlStmProcess - def visit_HdlStmBlock(self, o): :type o: HdlStmBlock - def visit_HdlStmIf(self, o): :type stm: HdlStmIf if cond: ... el...
64c8c1deee923ffae17e70e0fb1ad763cb69608c
<|skeleton|> class ToHwtStm: def visit_HdlStmProcess(self, o): """:type o: HdlStmProcess""" <|body_0|> def visit_HdlStmBlock(self, o): """:type o: HdlStmBlock""" <|body_1|> def visit_HdlStmIf(self, o): """:type stm: HdlStmIf if cond: ... else: ... will become c, cV...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ToHwtStm: def visit_HdlStmProcess(self, o): """:type o: HdlStmProcess""" w = self.out.write if o.labels: w('# ') if o.labels: w(o.labels[0]) w('\n') self.visit_doc(o) self.visit_iHdlStatement(o.body) def visit_HdlStmB...
the_stack_v2_python_sparse
hdlConvertorAst/to/hwt/stm.py
mewais/hdlConvertorAst
train
0
abd5c1a29f7f6d7625c832f7e1b9434b41a5d1dd
[ "self.aliyunrequest.set_action_name('DescribeDBInstances')\nif not isinstance(config, list):\n return self.MResponse(code=20001, msg='config配置不正确', status=False)\nself.Mconfig(config)\nresponse = self.aliyunapiclient.do_action_with_exception(self.aliyunrequest)\nreturn response", "self.aliyunrequest.set_action...
<|body_start_0|> self.aliyunrequest.set_action_name('DescribeDBInstances') if not isinstance(config, list): return self.MResponse(code=20001, msg='config配置不正确', status=False) self.Mconfig(config) response = self.aliyunapiclient.do_action_with_exception(self.aliyunrequest) ...
查询Rds
ALiYunApiRds
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ALiYunApiRds: """查询Rds""" def DescribeDBInstances(self, config): """该接口用于查看实例列表或被RAM授权的实例列表。 :param config: :return:""" <|body_0|> def DescribeDBInstanceAttribute(self, config): """该接口用于查看指定实例的详细属性。 :param config: :return:""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_020421
7,651
no_license
[ { "docstring": "该接口用于查看实例列表或被RAM授权的实例列表。 :param config: :return:", "name": "DescribeDBInstances", "signature": "def DescribeDBInstances(self, config)" }, { "docstring": "该接口用于查看指定实例的详细属性。 :param config: :return:", "name": "DescribeDBInstanceAttribute", "signature": "def DescribeDBInstanc...
2
stack_v2_sparse_classes_30k_train_006624
Implement the Python class `ALiYunApiRds` described below. Class description: 查询Rds Method signatures and docstrings: - def DescribeDBInstances(self, config): 该接口用于查看实例列表或被RAM授权的实例列表。 :param config: :return: - def DescribeDBInstanceAttribute(self, config): 该接口用于查看指定实例的详细属性。 :param config: :return:
Implement the Python class `ALiYunApiRds` described below. Class description: 查询Rds Method signatures and docstrings: - def DescribeDBInstances(self, config): 该接口用于查看实例列表或被RAM授权的实例列表。 :param config: :return: - def DescribeDBInstanceAttribute(self, config): 该接口用于查看指定实例的详细属性。 :param config: :return: <|skeleton|> class...
401ad869298d55a6cb2f78442385f67f40b9db52
<|skeleton|> class ALiYunApiRds: """查询Rds""" def DescribeDBInstances(self, config): """该接口用于查看实例列表或被RAM授权的实例列表。 :param config: :return:""" <|body_0|> def DescribeDBInstanceAttribute(self, config): """该接口用于查看指定实例的详细属性。 :param config: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ALiYunApiRds: """查询Rds""" def DescribeDBInstances(self, config): """该接口用于查看实例列表或被RAM授权的实例列表。 :param config: :return:""" self.aliyunrequest.set_action_name('DescribeDBInstances') if not isinstance(config, list): return self.MResponse(code=20001, msg='config配置不正确', statu...
the_stack_v2_python_sparse
utils/maliyun/aliyunapi.py
Alotofwater/cookcmdb
train
8
ae9c066f9dac57118147a05f618b6acbc2d519e1
[ "authorized: bool = True\nif authorized:\n user = Users.objects.get(id=user_id)\n fields = {'email', 'password', 'name', 'phone', 'roles'}\n return jsonify(convert_doc(user, fields))\nelse:\n return forbidden()", "authorized: bool = True\nif authorized:\n data = request.get_json()\n put_user = U...
<|body_start_0|> authorized: bool = True if authorized: user = Users.objects.get(id=user_id) fields = {'email', 'password', 'name', 'phone', 'roles'} return jsonify(convert_doc(user, fields)) else: return forbidden() <|end_body_0|> <|body_start_1|...
Flask-resftul resource for returning db.user collection. :Example: >>> from flask import Flask >>> from flask_restful import Api >>> from app import default_config # Create flask app, config, and resftul api, then add UserApi route >>> app = Flask(__name__) >>> app.config.update(default_config) >>> api = Api(app=app) >...
UserApi
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserApi: """Flask-resftul resource for returning db.user collection. :Example: >>> from flask import Flask >>> from flask_restful import Api >>> from app import default_config # Create flask app, config, and resftul api, then add UserApi route >>> app = Flask(__name__) >>> app.config.update(defau...
stack_v2_sparse_classes_36k_train_020422
7,554
no_license
[ { "docstring": "GET response method for acquiring single user data. JSON Web Token is required. Authorization is required: Access(admin=true) or UserId = get_jwt_identity() :return: JSON object", "name": "get", "signature": "def get(self, user_id: str) -> Response" }, { "docstring": "PUT respons...
3
stack_v2_sparse_classes_30k_train_012540
Implement the Python class `UserApi` described below. Class description: Flask-resftul resource for returning db.user collection. :Example: >>> from flask import Flask >>> from flask_restful import Api >>> from app import default_config # Create flask app, config, and resftul api, then add UserApi route >>> app = Flas...
Implement the Python class `UserApi` described below. Class description: Flask-resftul resource for returning db.user collection. :Example: >>> from flask import Flask >>> from flask_restful import Api >>> from app import default_config # Create flask app, config, and resftul api, then add UserApi route >>> app = Flas...
7f44c736c95866aaf820627ea54d3f00b3ada779
<|skeleton|> class UserApi: """Flask-resftul resource for returning db.user collection. :Example: >>> from flask import Flask >>> from flask_restful import Api >>> from app import default_config # Create flask app, config, and resftul api, then add UserApi route >>> app = Flask(__name__) >>> app.config.update(defau...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserApi: """Flask-resftul resource for returning db.user collection. :Example: >>> from flask import Flask >>> from flask_restful import Api >>> from app import default_config # Create flask app, config, and resftul api, then add UserApi route >>> app = Flask(__name__) >>> app.config.update(default_config) >>...
the_stack_v2_python_sparse
backend/uimpactify/controller/user.py
ObaidaSaleh/E-learning-app
train
1
937622e61c69f1f7f5c29973e9b9c982bf1df3a2
[ "self._draw_line(major_length, '0')\nfor j in range(1, num_inches + 1):\n self._draw_interval(major_length - 1)\n self._draw_line(major_length, str(j))", "line = '-' * tick_length\nif tick_label:\n line += ' ' + tick_label\nprint(line)", "if center_length > 0:\n self._draw_interval(center_length - 1...
<|body_start_0|> self._draw_line(major_length, '0') for j in range(1, num_inches + 1): self._draw_interval(major_length - 1) self._draw_line(major_length, str(j)) <|end_body_0|> <|body_start_1|> line = '-' * tick_length if tick_label: line += ' ' + ti...
EnglishRuler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnglishRuler: def __init__(self, num_inches, major_length): """Draw English ruler with given number of inches, major tick length.""" <|body_0|> def _draw_line(self, tick_length, tick_label=''): """Draw one line with given tick length(followed by optional label)""" ...
stack_v2_sparse_classes_36k_train_020423
968
no_license
[ { "docstring": "Draw English ruler with given number of inches, major tick length.", "name": "__init__", "signature": "def __init__(self, num_inches, major_length)" }, { "docstring": "Draw one line with given tick length(followed by optional label)", "name": "_draw_line", "signature": "d...
3
null
Implement the Python class `EnglishRuler` described below. Class description: Implement the EnglishRuler class. Method signatures and docstrings: - def __init__(self, num_inches, major_length): Draw English ruler with given number of inches, major tick length. - def _draw_line(self, tick_length, tick_label=''): Draw ...
Implement the Python class `EnglishRuler` described below. Class description: Implement the EnglishRuler class. Method signatures and docstrings: - def __init__(self, num_inches, major_length): Draw English ruler with given number of inches, major tick length. - def _draw_line(self, tick_length, tick_label=''): Draw ...
5ea5bc298a385b97480500290dbd58063a3e4287
<|skeleton|> class EnglishRuler: def __init__(self, num_inches, major_length): """Draw English ruler with given number of inches, major tick length.""" <|body_0|> def _draw_line(self, tick_length, tick_label=''): """Draw one line with given tick length(followed by optional label)""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EnglishRuler: def __init__(self, num_inches, major_length): """Draw English ruler with given number of inches, major tick length.""" self._draw_line(major_length, '0') for j in range(1, num_inches + 1): self._draw_interval(major_length - 1) self._draw_line(major...
the_stack_v2_python_sparse
python/recursion/draw_ruler.py
HaidiChen/Coding
train
0
31c7d54cb2ebf974366c31050cedde8cf2113d27
[ "super(APL, self).__init__()\nself.a = nn.ParameterList([nn.Parameter(torch.tensor(0.2)) for _ in range(s)])\nself.b = nn.ParameterList([nn.Parameter(torch.tensor(0.5)) for _ in range(s)])\nself.s = s", "part_1 = torch.clamp_min(input, min=0.0)\npart_2 = 0\nfor i in range(self.s):\n part_2 += self.a[i] * torch...
<|body_start_0|> super(APL, self).__init__() self.a = nn.ParameterList([nn.Parameter(torch.tensor(0.2)) for _ in range(s)]) self.b = nn.ParameterList([nn.Parameter(torch.tensor(0.5)) for _ in range(s)]) self.s = s <|end_body_0|> <|body_start_1|> part_1 = torch.clamp_min(input, m...
APL
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class APL: def __init__(self, s=1): """Init method.""" <|body_0|> def forward(self, input): """Forward pass of the function.""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(APL, self).__init__() self.a = nn.ParameterList([nn.Parameter(torch....
stack_v2_sparse_classes_36k_train_020424
32,265
no_license
[ { "docstring": "Init method.", "name": "__init__", "signature": "def __init__(self, s=1)" }, { "docstring": "Forward pass of the function.", "name": "forward", "signature": "def forward(self, input)" } ]
2
stack_v2_sparse_classes_30k_train_016292
Implement the Python class `APL` described below. Class description: Implement the APL class. Method signatures and docstrings: - def __init__(self, s=1): Init method. - def forward(self, input): Forward pass of the function.
Implement the Python class `APL` described below. Class description: Implement the APL class. Method signatures and docstrings: - def __init__(self, s=1): Init method. - def forward(self, input): Forward pass of the function. <|skeleton|> class APL: def __init__(self, s=1): """Init method.""" <|...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class APL: def __init__(self, s=1): """Init method.""" <|body_0|> def forward(self, input): """Forward pass of the function.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class APL: def __init__(self, s=1): """Init method.""" super(APL, self).__init__() self.a = nn.ParameterList([nn.Parameter(torch.tensor(0.2)) for _ in range(s)]) self.b = nn.ParameterList([nn.Parameter(torch.tensor(0.5)) for _ in range(s)]) self.s = s def forward(self, i...
the_stack_v2_python_sparse
generated/test_digantamisra98_Echo.py
jansel/pytorch-jit-paritybench
train
35
09ceeff88db61da4ecf6a84878bedc5302bdf39a
[ "if self.request.version == 'v6':\n return StrikeSerializerV6\nelif self.request.version == 'v7':\n return StrikeSerializerV6", "if request.version == 'v6':\n return self.list_impl(request)\nelif request.version == 'v7':\n return self.list_impl(request)\nraise Http404()", "started = rest_util.parse_...
<|body_start_0|> if self.request.version == 'v6': return StrikeSerializerV6 elif self.request.version == 'v7': return StrikeSerializerV6 <|end_body_0|> <|body_start_1|> if request.version == 'v6': return self.list_impl(request) elif request.version ==...
This view is the endpoint for retrieving the list of all Strike process.
StrikesView
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StrikesView: """This view is the endpoint for retrieving the list of all Strike process.""" def get_serializer_class(self): """Returns the appropriate serializer based off the requests version of the REST API""" <|body_0|> def list(self, request): """Determine ap...
stack_v2_sparse_classes_36k_train_020425
30,689
permissive
[ { "docstring": "Returns the appropriate serializer based off the requests version of the REST API", "name": "get_serializer_class", "signature": "def get_serializer_class(self)" }, { "docstring": "Determine api version and call specific method :param request: the HTTP POST request :type request:...
5
stack_v2_sparse_classes_30k_train_020375
Implement the Python class `StrikesView` described below. Class description: This view is the endpoint for retrieving the list of all Strike process. Method signatures and docstrings: - def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API - def list(self, r...
Implement the Python class `StrikesView` described below. Class description: This view is the endpoint for retrieving the list of all Strike process. Method signatures and docstrings: - def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API - def list(self, r...
28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b
<|skeleton|> class StrikesView: """This view is the endpoint for retrieving the list of all Strike process.""" def get_serializer_class(self): """Returns the appropriate serializer based off the requests version of the REST API""" <|body_0|> def list(self, request): """Determine ap...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StrikesView: """This view is the endpoint for retrieving the list of all Strike process.""" def get_serializer_class(self): """Returns the appropriate serializer based off the requests version of the REST API""" if self.request.version == 'v6': return StrikeSerializerV6 ...
the_stack_v2_python_sparse
scale/ingest/views.py
kfconsultant/scale
train
0
0c750e7f49c004aa1289ccb48a5e217f86841afa
[ "dict_nums = set()\nfor i in range(k):\n if nums[i] in dict_nums:\n return True\n dict_nums.add(nums[i])\n print(i, k, dict_nums)\nfor i in range(k, len(nums)):\n if nums[i] in dict_nums:\n return True\n dict_nums.add(nums[i])\n print(i, k, dict_nums)\n dict_nums.discard(nums[i - ...
<|body_start_0|> dict_nums = set() for i in range(k): if nums[i] in dict_nums: return True dict_nums.add(nums[i]) print(i, k, dict_nums) for i in range(k, len(nums)): if nums[i] in dict_nums: return True ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" <|body_0|> def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_36k_train_020426
1,476
no_license
[ { "docstring": ":type nums: List[int] :type k: int :rtype: bool", "name": "containsNearbyDuplicate", "signature": "def containsNearbyDuplicate(self, nums, k)" }, { "docstring": ":type nums: List[int] :type k: int :rtype: bool", "name": "containsNearbyDuplicate", "signature": "def contain...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool - def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtyp...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool - def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtyp...
f3fc71f344cd758cfce77f16ab72992c99ab288e
<|skeleton|> class Solution: def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" <|body_0|> def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" dict_nums = set() for i in range(k): if nums[i] in dict_nums: return True dict_nums.add(nums[i]) print(i, k, dict_nums) ...
the_stack_v2_python_sparse
219_contain_duplicate.py
jennyChing/leetCode
train
2
661ef93ab5d89d74b9428ea2840a4849108ccc77
[ "if origin is None:\n origin = ((shape[0] - 1) / 2, (shape[1] - 1) / 2)\nif r_map is None:\n r_map = radial_grid(origin, shape)\nself.expected_shape = tuple(shape)\nif mask is not None:\n if mask.shape != self.expected_shape:\n raise ValueError('\"mask\" has incorrect shape. Expected: ' + str(self....
<|body_start_0|> if origin is None: origin = ((shape[0] - 1) / 2, (shape[1] - 1) / 2) if r_map is None: r_map = radial_grid(origin, shape) self.expected_shape = tuple(shape) if mask is not None: if mask.shape != self.expected_shape: rai...
Create a 1-dimensional histogram by binning a 2-dimensional image in radius.
RadialBinnedStatistic
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RadialBinnedStatistic: """Create a 1-dimensional histogram by binning a 2-dimensional image in radius.""" def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'): """Parameters: ----------- shape : tuple of ints of length 2. shape of image...
stack_v2_sparse_classes_36k_train_020427
33,902
permissive
[ { "docstring": "Parameters: ----------- shape : tuple of ints of length 2. shape of image. bins : int or sequence of scalars, optional If `bins` is an int, it defines the number of equal-width bins in the given range (10 by default). If `bins` is a sequence, it defines the bin edges, including the rightmost edg...
2
stack_v2_sparse_classes_30k_train_013305
Implement the Python class `RadialBinnedStatistic` described below. Class description: Create a 1-dimensional histogram by binning a 2-dimensional image in radius. Method signatures and docstrings: - def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'): Parameters: ----...
Implement the Python class `RadialBinnedStatistic` described below. Class description: Create a 1-dimensional histogram by binning a 2-dimensional image in radius. Method signatures and docstrings: - def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'): Parameters: ----...
0e54357c360b0784b8ee279a8ebf7f9fe011a3d6
<|skeleton|> class RadialBinnedStatistic: """Create a 1-dimensional histogram by binning a 2-dimensional image in radius.""" def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'): """Parameters: ----------- shape : tuple of ints of length 2. shape of image...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RadialBinnedStatistic: """Create a 1-dimensional histogram by binning a 2-dimensional image in radius.""" def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'): """Parameters: ----------- shape : tuple of ints of length 2. shape of image. bins : int ...
the_stack_v2_python_sparse
skbeam/core/accumulators/binned_statistic.py
scikit-beam/scikit-beam
train
77
8c6e74c58b3285e2bc1d8d138b963c51589903ce
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn OnPremisesAccidentalDeletionPrevention()", "from .on_premises_directory_synchronization_deletion_prevention_type import OnPremisesDirectorySynchronizationDeletionPreventionType\nfrom .on_premises_directory_synchronization_deletion_prev...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return OnPremisesAccidentalDeletionPrevention() <|end_body_0|> <|body_start_1|> from .on_premises_directory_synchronization_deletion_prevention_type import OnPremisesDirectorySynchronizationDeletionPre...
OnPremisesAccidentalDeletionPrevention
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OnPremisesAccidentalDeletionPrevention: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnPremisesAccidentalDeletionPrevention: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the...
stack_v2_sparse_classes_36k_train_020428
3,688
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: OnPremisesAccidentalDeletionPrevention", "name": "create_from_discriminator_value", "signature": "def create...
3
null
Implement the Python class `OnPremisesAccidentalDeletionPrevention` described below. Class description: Implement the OnPremisesAccidentalDeletionPrevention class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnPremisesAccidentalDeletionPrevention: C...
Implement the Python class `OnPremisesAccidentalDeletionPrevention` described below. Class description: Implement the OnPremisesAccidentalDeletionPrevention class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnPremisesAccidentalDeletionPrevention: C...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class OnPremisesAccidentalDeletionPrevention: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnPremisesAccidentalDeletionPrevention: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OnPremisesAccidentalDeletionPrevention: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnPremisesAccidentalDeletionPrevention: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator...
the_stack_v2_python_sparse
msgraph/generated/models/on_premises_accidental_deletion_prevention.py
microsoftgraph/msgraph-sdk-python
train
135
769b19f64c7ce3b098fb50f7b73e9fd684b445d1
[ "if not root:\n return 'N'\nleft = 'L' + self.serialize(root.left)\nright = 'R' + self.serialize(root.right)\nreturn '{}{}{}'.format(root.val, left, right)", "def helper(data):\n if data[0] == 'N':\n return (None, data)\n count = 1\n length = len(data)\n while count < length and (data[count]...
<|body_start_0|> if not root: return 'N' left = 'L' + self.serialize(root.left) right = 'R' + self.serialize(root.right) return '{}{}{}'.format(root.val, left, right) <|end_body_0|> <|body_start_1|> def helper(data): if data[0] == 'N': ret...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root: ...
stack_v2_sparse_classes_36k_train_020429
1,626
no_license
[ { "docstring": "Encodes a tree to a single string.", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Decodes your encoded data to tree.", "name": "deserialize", "signature": "def deserialize(self, data: str) -> TreeNode" } ]
2
stack_v2_sparse_classes_30k_test_001018
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. <|skeleton|> class Co...
c6fd7df7954e82688de8dc9b49e627ee5de7ddac
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" if not root: return 'N' left = 'L' + self.serialize(root.left) right = 'R' + self.serialize(root.right) return '{}{}{}'.format(root.val, left, right) def deseria...
the_stack_v2_python_sparse
DailyChallenge/10-09-2020_solution.py
Joseph-Lin-163/LeetCode
train
0
5dbdca47a80e85e3959504f8048bd57e739840a5
[ "if isinstance(key, int):\n return HIAlgorithm(key)\nif key not in HIAlgorithm._member_map_:\n extend_enum(HIAlgorithm, key, default)\nreturn HIAlgorithm[key]", "if not (isinstance(value, int) and 0 <= value <= 65535):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 10 <= value <= ...
<|body_start_0|> if isinstance(key, int): return HIAlgorithm(key) if key not in HIAlgorithm._member_map_: extend_enum(HIAlgorithm, key, default) return HIAlgorithm[key] <|end_body_0|> <|body_start_1|> if not (isinstance(value, int) and 0 <= value <= 65535): ...
[HIAlgorithm] HI Algorithm
HIAlgorithm
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HIAlgorithm: """[HIAlgorithm] HI Algorithm""" def get(key, default=-1): """Backport support for original codes.""" <|body_0|> def _missing_(cls, value): """Lookup function used when value is not found.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_020430
1,411
permissive
[ { "docstring": "Backport support for original codes.", "name": "get", "signature": "def get(key, default=-1)" }, { "docstring": "Lookup function used when value is not found.", "name": "_missing_", "signature": "def _missing_(cls, value)" } ]
2
null
Implement the Python class `HIAlgorithm` described below. Class description: [HIAlgorithm] HI Algorithm Method signatures and docstrings: - def get(key, default=-1): Backport support for original codes. - def _missing_(cls, value): Lookup function used when value is not found.
Implement the Python class `HIAlgorithm` described below. Class description: [HIAlgorithm] HI Algorithm Method signatures and docstrings: - def get(key, default=-1): Backport support for original codes. - def _missing_(cls, value): Lookup function used when value is not found. <|skeleton|> class HIAlgorithm: """...
90cd07d67df28d5c5ab0585bc60f467a78d9db33
<|skeleton|> class HIAlgorithm: """[HIAlgorithm] HI Algorithm""" def get(key, default=-1): """Backport support for original codes.""" <|body_0|> def _missing_(cls, value): """Lookup function used when value is not found.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HIAlgorithm: """[HIAlgorithm] HI Algorithm""" def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return HIAlgorithm(key) if key not in HIAlgorithm._member_map_: extend_enum(HIAlgorithm, key, default) return...
the_stack_v2_python_sparse
pcapkit/const/hip/hi_algorithm.py
stjordanis/PyPCAPKit
train
0
7381c5c01276b5e75019fb720543a79ae36f34b7
[ "root = BinaryTree.Node(10)\nroot.left = BinaryTree.Node(5)\nroot.left.left = BinaryTree.Node(3)\nroot.left.right = BinaryTree.Node(8)\nroot.left.left.left = BinaryTree.Node(1)\nroot.left.left.right = BinaryTree.Node(4)\nroot.right = BinaryTree.Node(15)\nroot.right.left = BinaryTree.Node(12)\nroot.right.right = Bin...
<|body_start_0|> root = BinaryTree.Node(10) root.left = BinaryTree.Node(5) root.left.left = BinaryTree.Node(3) root.left.right = BinaryTree.Node(8) root.left.left.left = BinaryTree.Node(1) root.left.left.right = BinaryTree.Node(4) root.right = BinaryTree.Node(15) ...
A rotation of a BinaryTree changes the structure of the tree without changing the order of the elements. The operation is used to balance a BinarySearchTree.
TestBinaryTreeSingleRotation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestBinaryTreeSingleRotation: """A rotation of a BinaryTree changes the structure of the tree without changing the order of the elements. The operation is used to balance a BinarySearchTree.""" def setup_method(self): """Build a tree with this structure 10 / 5 15 / \\ / 3 8 12 18 / \...
stack_v2_sparse_classes_36k_train_020431
4,225
no_license
[ { "docstring": "Build a tree with this structure 10 / 5 15 / \\\\ / 3 8 12 18 / \\\\ / 1 4 16 20 :return:", "name": "setup_method", "signature": "def setup_method(self)" }, { "docstring": "Test rotating the subtree starting at 5 to the right. i.e.: 5 3 / \\\\ / 3 8 ===> 1 5 / \\\\ / 1 4 4 8", ...
3
stack_v2_sparse_classes_30k_train_010372
Implement the Python class `TestBinaryTreeSingleRotation` described below. Class description: A rotation of a BinaryTree changes the structure of the tree without changing the order of the elements. The operation is used to balance a BinarySearchTree. Method signatures and docstrings: - def setup_method(self): Build ...
Implement the Python class `TestBinaryTreeSingleRotation` described below. Class description: A rotation of a BinaryTree changes the structure of the tree without changing the order of the elements. The operation is used to balance a BinarySearchTree. Method signatures and docstrings: - def setup_method(self): Build ...
f086ca1dba5f4ca329b5650b3f7b01dc9f89299d
<|skeleton|> class TestBinaryTreeSingleRotation: """A rotation of a BinaryTree changes the structure of the tree without changing the order of the elements. The operation is used to balance a BinarySearchTree.""" def setup_method(self): """Build a tree with this structure 10 / 5 15 / \\ / 3 8 12 18 / \...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestBinaryTreeSingleRotation: """A rotation of a BinaryTree changes the structure of the tree without changing the order of the elements. The operation is used to balance a BinarySearchTree.""" def setup_method(self): """Build a tree with this structure 10 / 5 15 / \\ / 3 8 12 18 / \\ / 1 4 16 20...
the_stack_v2_python_sparse
data_structures/binary_tree/test_binary_tree_rotation.py
hans25041/python_practice
train
0
eac6d1d01d5eba663486c666bad9578e197b6316
[ "super().__init__(name=name, **kwargs)\nself.num_classes = num_classes\nself.num_anchors = num_anchors\nself.num_filters = num_filters\nself.min_level = min_level\nself.max_level = max_level\nself.repeats = repeats\nself.is_training_bn = is_training_bn\nself.survival_prob = survival_prob\nself.conv_ops = []\nself.b...
<|body_start_0|> super().__init__(name=name, **kwargs) self.num_classes = num_classes self.num_anchors = num_anchors self.num_filters = num_filters self.min_level = min_level self.max_level = max_level self.repeats = repeats self.is_training_bn = is_traini...
Object class prediction network.
ClassNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClassNet: """Object class prediction network.""" def __init__(self, num_classes=90, num_anchors=9, num_filters=32, min_level=3, max_level=7, is_training_bn=False, repeats=4, survival_prob=None, name='class_net', **kwargs): """Initialize the ClassNet. Args: num_classes: number of clas...
stack_v2_sparse_classes_36k_train_020432
3,644
no_license
[ { "docstring": "Initialize the ClassNet. Args: num_classes: number of classes. num_anchors: number of anchors. num_filters: number of filters for \"intermediate\" layers. min_level: minimum level for features. max_level: maximum level for features. is_training_bn: True if we train the BatchNorm. repeats: number...
2
null
Implement the Python class `ClassNet` described below. Class description: Object class prediction network. Method signatures and docstrings: - def __init__(self, num_classes=90, num_anchors=9, num_filters=32, min_level=3, max_level=7, is_training_bn=False, repeats=4, survival_prob=None, name='class_net', **kwargs): I...
Implement the Python class `ClassNet` described below. Class description: Object class prediction network. Method signatures and docstrings: - def __init__(self, num_classes=90, num_anchors=9, num_filters=32, min_level=3, max_level=7, is_training_bn=False, repeats=4, survival_prob=None, name='class_net', **kwargs): I...
b7549701b0b1a7e4cc2c8275df2bc6c7a3253d24
<|skeleton|> class ClassNet: """Object class prediction network.""" def __init__(self, num_classes=90, num_anchors=9, num_filters=32, min_level=3, max_level=7, is_training_bn=False, repeats=4, survival_prob=None, name='class_net', **kwargs): """Initialize the ClassNet. Args: num_classes: number of clas...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClassNet: """Object class prediction network.""" def __init__(self, num_classes=90, num_anchors=9, num_filters=32, min_level=3, max_level=7, is_training_bn=False, repeats=4, survival_prob=None, name='class_net', **kwargs): """Initialize the ClassNet. Args: num_classes: number of classes. num_anch...
the_stack_v2_python_sparse
AIServer/ai_api/ai_models/layers/class_net.py
tfwcn/tensorflow2-machine-vision
train
1
2ad4bd94952d826732a91dbcc2b9fc4706212c9a
[ "for i in range(n):\n self.disjoint.append(i)\n self.ranking.append(0)", "if self.disjoint[value] != value:\n self.disjoint[value] = self.disjoint_find(self.disjoint[value])\nreturn self.disjoint[value]", "x_root = self.disjoint_find(x)\ny_root = self.disjoint_find(y)\nif self.ranking[x_root] < self.ra...
<|body_start_0|> for i in range(n): self.disjoint.append(i) self.ranking.append(0) <|end_body_0|> <|body_start_1|> if self.disjoint[value] != value: self.disjoint[value] = self.disjoint_find(self.disjoint[value]) return self.disjoint[value] <|end_body_1|> <|...
DisjointSet
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DisjointSet: def __init__(self, n): """Initialises a disjoint set of length `n`, starting from elements number 0 to number n-1""" <|body_0|> def disjoint_find(self, value): """Find a value in the disjoint set.""" <|body_1|> def disjoint_union(self, x, y)...
stack_v2_sparse_classes_36k_train_020433
1,603
permissive
[ { "docstring": "Initialises a disjoint set of length `n`, starting from elements number 0 to number n-1", "name": "__init__", "signature": "def __init__(self, n)" }, { "docstring": "Find a value in the disjoint set.", "name": "disjoint_find", "signature": "def disjoint_find(self, value)"...
3
null
Implement the Python class `DisjointSet` described below. Class description: Implement the DisjointSet class. Method signatures and docstrings: - def __init__(self, n): Initialises a disjoint set of length `n`, starting from elements number 0 to number n-1 - def disjoint_find(self, value): Find a value in the disjoin...
Implement the Python class `DisjointSet` described below. Class description: Implement the DisjointSet class. Method signatures and docstrings: - def __init__(self, n): Initialises a disjoint set of length `n`, starting from elements number 0 to number n-1 - def disjoint_find(self, value): Find a value in the disjoin...
4ae6ba54e90af14af236e03e435eb0402dcac787
<|skeleton|> class DisjointSet: def __init__(self, n): """Initialises a disjoint set of length `n`, starting from elements number 0 to number n-1""" <|body_0|> def disjoint_find(self, value): """Find a value in the disjoint set.""" <|body_1|> def disjoint_union(self, x, y)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DisjointSet: def __init__(self, n): """Initialises a disjoint set of length `n`, starting from elements number 0 to number n-1""" for i in range(n): self.disjoint.append(i) self.ranking.append(0) def disjoint_find(self, value): """Find a value in the disjoi...
the_stack_v2_python_sparse
data_structures/Disjoint_Set_Union/Python/disjoint_set.py
ZoranPandovski/al-go-rithms
train
1,421
64cc566df94973634fdce2554183e2f1eaa2924c
[ "if not prices:\n return 0\nn = len(prices)\nprofit = [[0, 0] for _ in range(n)]\nprofit[0][1] = -prices[0]\nfor i in range(1, n):\n profit[i][0] = max(profit[i - 1][0], profit[i - 1][1] + prices[i] - fee)\n profit[i][1] = max(profit[i - 1][1], profit[i - 1][0] - prices[i])\nreturn profit[n - 1][0]", "if...
<|body_start_0|> if not prices: return 0 n = len(prices) profit = [[0, 0] for _ in range(n)] profit[0][1] = -prices[0] for i in range(1, n): profit[i][0] = max(profit[i - 1][0], profit[i - 1][1] + prices[i] - fee) profit[i][1] = max(profit[i - ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit(self, prices, fee): """:type prices: List[int] :type fee: int :rtype: int""" <|body_0|> def maxProfit2(self, prices, fee): """:type prices: List[int] :type fee: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_020434
1,742
no_license
[ { "docstring": ":type prices: List[int] :type fee: int :rtype: int", "name": "maxProfit", "signature": "def maxProfit(self, prices, fee)" }, { "docstring": ":type prices: List[int] :type fee: int :rtype: int", "name": "maxProfit2", "signature": "def maxProfit2(self, prices, fee)" } ]
2
stack_v2_sparse_classes_30k_train_020198
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices, fee): :type prices: List[int] :type fee: int :rtype: int - def maxProfit2(self, prices, fee): :type prices: List[int] :type fee: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices, fee): :type prices: List[int] :type fee: int :rtype: int - def maxProfit2(self, prices, fee): :type prices: List[int] :type fee: int :rtype: int <|sk...
5450beff0115e74bd7ecaa5edb076e942fe4f046
<|skeleton|> class Solution: def maxProfit(self, prices, fee): """:type prices: List[int] :type fee: int :rtype: int""" <|body_0|> def maxProfit2(self, prices, fee): """:type prices: List[int] :type fee: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit(self, prices, fee): """:type prices: List[int] :type fee: int :rtype: int""" if not prices: return 0 n = len(prices) profit = [[0, 0] for _ in range(n)] profit[0][1] = -prices[0] for i in range(1, n): profit[i][0] ...
the_stack_v2_python_sparse
src/best_time_to_buy_and_sell_stock_with_transaction_fee_714.py
reflectc/leetcode_program
train
2
1df74e0fc8b2d32c8841d0bf0b709e50834e784b
[ "self.taskfile = Path(taskfile or xdg.save_data_path('taskwarrior') / 'tasklist.lst')\nself.separator = separator or ' '\nself.stop_alias = stop_alias\nself.resume_alias = resume_alias", "filename = Path(filename or xdg.save_data_path('taskwarrior') / 'config.json')\ndata = {}\nif filename.exists():\n data = j...
<|body_start_0|> self.taskfile = Path(taskfile or xdg.save_data_path('taskwarrior') / 'tasklist.lst') self.separator = separator or ' ' self.stop_alias = stop_alias self.resume_alias = resume_alias <|end_body_0|> <|body_start_1|> filename = Path(filename or xdg.save_data_path('t...
Config
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Config: def __init__(self, taskfile=None, separator=None, stop_alias=None, resume_alias=None): """Configuration for task tracker. - taskfile: storage file for task history. Default is $XDG_DATA_HOME/taskwarrior/tasklist.lst - separator: text separator between date/time field and task tit...
stack_v2_sparse_classes_36k_train_020435
13,935
permissive
[ { "docstring": "Configuration for task tracker. - taskfile: storage file for task history. Default is $XDG_DATA_HOME/taskwarrior/tasklist.lst - separator: text separator between date/time field and task title in the task file. Default is space. - stop_alias: Task title to put instead of default 'stop' action. B...
2
null
Implement the Python class `Config` described below. Class description: Implement the Config class. Method signatures and docstrings: - def __init__(self, taskfile=None, separator=None, stop_alias=None, resume_alias=None): Configuration for task tracker. - taskfile: storage file for task history. Default is $XDG_DATA...
Implement the Python class `Config` described below. Class description: Implement the Config class. Method signatures and docstrings: - def __init__(self, taskfile=None, separator=None, stop_alias=None, resume_alias=None): Configuration for task tracker. - taskfile: storage file for task history. Default is $XDG_DATA...
a7e880e189bfa4793f30ff928b049e4a182a38cd
<|skeleton|> class Config: def __init__(self, taskfile=None, separator=None, stop_alias=None, resume_alias=None): """Configuration for task tracker. - taskfile: storage file for task history. Default is $XDG_DATA_HOME/taskwarrior/tasklist.lst - separator: text separator between date/time field and task tit...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Config: def __init__(self, taskfile=None, separator=None, stop_alias=None, resume_alias=None): """Configuration for task tracker. - taskfile: storage file for task history. Default is $XDG_DATA_HOME/taskwarrior/tasklist.lst - separator: text separator between date/time field and task title in the task...
the_stack_v2_python_sparse
lib/clckwrkbdgr/taskwarrior/_base.py
clckwrkbdgr/dotfiles
train
2
9255d3e6c8a5225f3c6444051b220bf9674194dd
[ "stock_move_line = self.env['stock.move.line'].search([('reference', '=', self.name)])\nfor line in stock_move_line:\n if line.lot_id:\n stock = self.env['stock.quant'].search([('quantity', '>', 0), ('lot_id', '=', line.lot_id.id)])\n line.lot_id.qty_location = [(5, 0, 0)]\n if len(stock.ids...
<|body_start_0|> stock_move_line = self.env['stock.move.line'].search([('reference', '=', self.name)]) for line in stock_move_line: if line.lot_id: stock = self.env['stock.quant'].search([('quantity', '>', 0), ('lot_id', '=', line.lot_id.id)]) line.lot_id.qty_...
class_name: FlspMrpProductionFilterSn inherit: mrp.production Purpose: To change the stock.production.lot field qty_location when consumed in MO Date: Mar/29th/2021/M Author: Sami Byaruhanga
FlspMrpProductionFilterSn
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FlspMrpProductionFilterSn: """class_name: FlspMrpProductionFilterSn inherit: mrp.production Purpose: To change the stock.production.lot field qty_location when consumed in MO Date: Mar/29th/2021/M Author: Sami Byaruhanga""" def change_product_qty_in_lot_table(self): """Purpose: To ch...
stack_v2_sparse_classes_36k_train_020436
7,672
no_license
[ { "docstring": "Purpose: To change the location name on the lot Note: Did not call the method in lot coz, we had to filter the lots to those Used only in the manufacturing order. Did this to make the run time quicker", "name": "change_product_qty_in_lot_table", "signature": "def change_product_qty_in_lo...
2
stack_v2_sparse_classes_30k_train_020963
Implement the Python class `FlspMrpProductionFilterSn` described below. Class description: class_name: FlspMrpProductionFilterSn inherit: mrp.production Purpose: To change the stock.production.lot field qty_location when consumed in MO Date: Mar/29th/2021/M Author: Sami Byaruhanga Method signatures and docstrings: - ...
Implement the Python class `FlspMrpProductionFilterSn` described below. Class description: class_name: FlspMrpProductionFilterSn inherit: mrp.production Purpose: To change the stock.production.lot field qty_location when consumed in MO Date: Mar/29th/2021/M Author: Sami Byaruhanga Method signatures and docstrings: - ...
4a82cd5cfd1898c6da860cb68dff3a14e037bbad
<|skeleton|> class FlspMrpProductionFilterSn: """class_name: FlspMrpProductionFilterSn inherit: mrp.production Purpose: To change the stock.production.lot field qty_location when consumed in MO Date: Mar/29th/2021/M Author: Sami Byaruhanga""" def change_product_qty_in_lot_table(self): """Purpose: To ch...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FlspMrpProductionFilterSn: """class_name: FlspMrpProductionFilterSn inherit: mrp.production Purpose: To change the stock.production.lot field qty_location when consumed in MO Date: Mar/29th/2021/M Author: Sami Byaruhanga""" def change_product_qty_in_lot_table(self): """Purpose: To change the loca...
the_stack_v2_python_sparse
flsp_mrp_filter_sn/models/filter_sn_method.py
odoo-smg/firstlight
train
3
261ba21b73b130f8c349ecd3f1d041e19f7eaf79
[ "if command_id == 0:\n state = args[0] & 3\n self.async_send_signal(f'{self.unique_id}_{SIGNAL_ATTR_UPDATED}', 2, 'zone_status', state)\n self.debug('Updated alarm state: %s', state)\nelif command_id == 1:\n self.debug('Enroll requested')\n res = self._cluster.enroll_response(0, 0)\n asyncio.creat...
<|body_start_0|> if command_id == 0: state = args[0] & 3 self.async_send_signal(f'{self.unique_id}_{SIGNAL_ATTR_UPDATED}', 2, 'zone_status', state) self.debug('Updated alarm state: %s', state) elif command_id == 1: self.debug('Enroll requested') ...
Channel for the IASZone Zigbee cluster.
IASZoneChannel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IASZoneChannel: """Channel for the IASZone Zigbee cluster.""" def cluster_command(self, tsn, command_id, args): """Handle commands received to this cluster.""" <|body_0|> async def async_configure(self): """Configure IAS device.""" <|body_1|> def att...
stack_v2_sparse_classes_36k_train_020437
6,340
permissive
[ { "docstring": "Handle commands received to this cluster.", "name": "cluster_command", "signature": "def cluster_command(self, tsn, command_id, args)" }, { "docstring": "Configure IAS device.", "name": "async_configure", "signature": "async def async_configure(self)" }, { "docstr...
4
null
Implement the Python class `IASZoneChannel` described below. Class description: Channel for the IASZone Zigbee cluster. Method signatures and docstrings: - def cluster_command(self, tsn, command_id, args): Handle commands received to this cluster. - async def async_configure(self): Configure IAS device. - def attribu...
Implement the Python class `IASZoneChannel` described below. Class description: Channel for the IASZone Zigbee cluster. Method signatures and docstrings: - def cluster_command(self, tsn, command_id, args): Handle commands received to this cluster. - async def async_configure(self): Configure IAS device. - def attribu...
ed4ab403deaed9e8c95e0db728477fcb012bf4fa
<|skeleton|> class IASZoneChannel: """Channel for the IASZone Zigbee cluster.""" def cluster_command(self, tsn, command_id, args): """Handle commands received to this cluster.""" <|body_0|> async def async_configure(self): """Configure IAS device.""" <|body_1|> def att...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IASZoneChannel: """Channel for the IASZone Zigbee cluster.""" def cluster_command(self, tsn, command_id, args): """Handle commands received to this cluster.""" if command_id == 0: state = args[0] & 3 self.async_send_signal(f'{self.unique_id}_{SIGNAL_ATTR_UPDATED}',...
the_stack_v2_python_sparse
homeassistant/components/zha/core/channels/security.py
tchellomello/home-assistant
train
8
3e08e3929994d565f7766d1b9bbe5ec7b38bc323
[ "token, created = ICalToken.objects.get_or_create(user=request.user)\nif not created:\n token.regenerate()\nserializer = ICalTokenSerializer(token)\nreturn Response(serializer.data)", "token = ICalToken.objects.get_or_create(user=request.user)[0]\nserializer = ICalTokenSerializer(token)\nreturn Response(serial...
<|body_start_0|> token, created = ICalToken.objects.get_or_create(user=request.user) if not created: token.regenerate() serializer = ICalTokenSerializer(token) return Response(serializer.data) <|end_body_0|> <|body_start_1|> token = ICalToken.objects.get_or_create(us...
API Endpoint to get a token for ical-urls. To regenerate go to [regenerate](regenerate/).
ICalTokenViewset
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ICalTokenViewset: """API Endpoint to get a token for ical-urls. To regenerate go to [regenerate](regenerate/).""" def regenerate(self, request, *args, **kwargs): """Regenerate ICalToken.""" <|body_0|> def list(self, request): """Get ICalToken.""" <|body_1...
stack_v2_sparse_classes_36k_train_020438
6,167
permissive
[ { "docstring": "Regenerate ICalToken.", "name": "regenerate", "signature": "def regenerate(self, request, *args, **kwargs)" }, { "docstring": "Get ICalToken.", "name": "list", "signature": "def list(self, request)" } ]
2
null
Implement the Python class `ICalTokenViewset` described below. Class description: API Endpoint to get a token for ical-urls. To regenerate go to [regenerate](regenerate/). Method signatures and docstrings: - def regenerate(self, request, *args, **kwargs): Regenerate ICalToken. - def list(self, request): Get ICalToken...
Implement the Python class `ICalTokenViewset` described below. Class description: API Endpoint to get a token for ical-urls. To regenerate go to [regenerate](regenerate/). Method signatures and docstrings: - def regenerate(self, request, *args, **kwargs): Regenerate ICalToken. - def list(self, request): Get ICalToken...
2c1909fd84fe3b3e0a9d3792c4bcc51089ad5a87
<|skeleton|> class ICalTokenViewset: """API Endpoint to get a token for ical-urls. To regenerate go to [regenerate](regenerate/).""" def regenerate(self, request, *args, **kwargs): """Regenerate ICalToken.""" <|body_0|> def list(self, request): """Get ICalToken.""" <|body_1...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ICalTokenViewset: """API Endpoint to get a token for ical-urls. To regenerate go to [regenerate](regenerate/).""" def regenerate(self, request, *args, **kwargs): """Regenerate ICalToken.""" token, created = ICalToken.objects.get_or_create(user=request.user) if not created: ...
the_stack_v2_python_sparse
lego/apps/ical/viewsets.py
webkom/lego
train
53
7b5e374dde9bf5526b854f6cf27ff495af92c394
[ "super(GANLoss, self).__init__()\nself.register_buffer('real_label', torch.tensor(target_real_label))\nself.register_buffer('fake_label', torch.tensor(target_fake_label))\nself.gan_mode = gan_mode\nif gan_mode == 'lsgan':\n self.loss = nn.MSELoss()\nelif gan_mode == 'vanilla':\n self.loss = nn.BCEWithLogitsLo...
<|body_start_0|> super(GANLoss, self).__init__() self.register_buffer('real_label', torch.tensor(target_real_label)) self.register_buffer('fake_label', torch.tensor(target_fake_label)) self.gan_mode = gan_mode if gan_mode == 'lsgan': self.loss = nn.MSELoss() e...
Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input.
GANLoss
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GANLoss: """Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input.""" def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0): """Initialize the GANLoss class. Parameters: ga...
stack_v2_sparse_classes_36k_train_020439
16,766
no_license
[ { "docstring": "Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp. target_real_label (bool) - - label for a real image target_fake_label (bool) - - label of a fake image Note: Do not use sigmoid as the last layer of Discrimin...
3
stack_v2_sparse_classes_30k_train_005637
Implement the Python class `GANLoss` described below. Class description: Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. Method signatures and docstrings: - def __init__(self, gan_mode, target_real_label=1.0, target_fake...
Implement the Python class `GANLoss` described below. Class description: Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. Method signatures and docstrings: - def __init__(self, gan_mode, target_real_label=1.0, target_fake...
1af2ea3a0787a3f38742dceb39afc39d0825f370
<|skeleton|> class GANLoss: """Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input.""" def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0): """Initialize the GANLoss class. Parameters: ga...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GANLoss: """Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input.""" def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0): """Initialize the GANLoss class. Parameters: gan_mode (str) ...
the_stack_v2_python_sparse
hand_pose_estimators/CVPR2020_hpm3d/models/networks/blocks.py
Whiskysu/mm-hand
train
0
e2a27801a69639eba679dbdfe56715e4c90b2beb
[ "logger.info('Overriding class: Optimizer -> SSA.')\nsuper(SSA, self).__init__()\nself.build(params)\nlogger.info('Class overrided.')", "c1 = 2 * np.exp(-(4 * iteration / n_iterations) ** 2)\nfor i, _ in enumerate(space.agents):\n if i == 0:\n for j, (lb, ub) in enumerate(zip(space.agents[i].lb, space.a...
<|body_start_0|> logger.info('Overriding class: Optimizer -> SSA.') super(SSA, self).__init__() self.build(params) logger.info('Class overrided.') <|end_body_0|> <|body_start_1|> c1 = 2 * np.exp(-(4 * iteration / n_iterations) ** 2) for i, _ in enumerate(space.agents): ...
A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software (2017).
SSA
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SSA: """A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software (2017).""" def __init__(self...
stack_v2_sparse_classes_36k_train_020440
2,711
permissive
[ { "docstring": "Initialization method. Args: params (dict): Contains key-value parameters to the meta-heuristics.", "name": "__init__", "signature": "def __init__(self, params=None)" }, { "docstring": "Wraps Salp Swarm Algorithm over all agents and variables. Args: space (Space): Space containin...
2
stack_v2_sparse_classes_30k_test_000008
Implement the Python class `SSA` described below. Class description: A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Sof...
Implement the Python class `SSA` described below. Class description: A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Sof...
09e5485b9e30eca622ad404e85c22de0c42c8abd
<|skeleton|> class SSA: """A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software (2017).""" def __init__(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SSA: """A SSA class, inherited from Optimizer. This is the designed class to define SSA-related variables and methods. References: S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software (2017).""" def __init__(self, params=None...
the_stack_v2_python_sparse
opytimizer/optimizers/swarm/ssa.py
himanshuRepo/opytimizer
train
0
669d87757f3be036c1f9421489221e332c9a2d63
[ "insts = Tenant.objects.all()\nlist_insts = []\nfor tenant in insts:\n list_insts.append({'id': tenant.id, 'name': tenant.name, 'ctime': tenant.create_time, 'space_quota': TenantQuota.objects.get_or_none(tenant=tenant), 'space_usage': get_tenant_space_usage(tenant)})\nreturn api_response(data={'insts': list_inst...
<|body_start_0|> insts = Tenant.objects.all() list_insts = [] for tenant in insts: list_insts.append({'id': tenant.id, 'name': tenant.name, 'ctime': tenant.create_time, 'space_quota': TenantQuota.objects.get_or_none(tenant=tenant), 'space_usage': get_tenant_space_usage(tenant)}) ...
AdminTenants
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdminTenants: def get(self, request): """Get all tenants""" <|body_0|> def post(self, request): """Create a new tenant""" <|body_1|> <|end_skeleton|> <|body_start_0|> insts = Tenant.objects.all() list_insts = [] for tenant in insts: ...
stack_v2_sparse_classes_36k_train_020441
34,523
permissive
[ { "docstring": "Get all tenants", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Create a new tenant", "name": "post", "signature": "def post(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_013150
Implement the Python class `AdminTenants` described below. Class description: Implement the AdminTenants class. Method signatures and docstrings: - def get(self, request): Get all tenants - def post(self, request): Create a new tenant
Implement the Python class `AdminTenants` described below. Class description: Implement the AdminTenants class. Method signatures and docstrings: - def get(self, request): Get all tenants - def post(self, request): Create a new tenant <|skeleton|> class AdminTenants: def get(self, request): """Get all t...
13b3ed26a04248211ef91ca70dccc617be27a3c3
<|skeleton|> class AdminTenants: def get(self, request): """Get all tenants""" <|body_0|> def post(self, request): """Create a new tenant""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AdminTenants: def get(self, request): """Get all tenants""" insts = Tenant.objects.all() list_insts = [] for tenant in insts: list_insts.append({'id': tenant.id, 'name': tenant.name, 'ctime': tenant.create_time, 'space_quota': TenantQuota.objects.get_or_none(tenant=...
the_stack_v2_python_sparse
fhs/usr/share/python/syncwerk/restapi/restapi/api3/custom/admin/tenants.py
syncwerk/syncwerk-server-restapi
train
0
976e300d661289063a1535a41de42f0a899ae369
[ "customer = Customer.objects.all()\nserializer = CustomerSerializer(customer, many=True)\nreturn Response(serializer.data)", "print(request.data)\nusername = request.data['customer']['username']\nuserEmail = request.data['custEmail']\nprint(username)\nserializer = CustomerSerializer(data=request.data)\nif seriali...
<|body_start_0|> customer = Customer.objects.all() serializer = CustomerSerializer(customer, many=True) return Response(serializer.data) <|end_body_0|> <|body_start_1|> print(request.data) username = request.data['customer']['username'] userEmail = request.data['custEmai...
A class based view for creating and fetching Sstudent records
CustomerRecordView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomerRecordView: """A class based view for creating and fetching Sstudent records""" def get(self, format=None, referralString=None): """Get all the student records :param format: Format of the student records to return to :return: Returns a list of student records""" <|bo...
stack_v2_sparse_classes_36k_train_020442
3,763
no_license
[ { "docstring": "Get all the student records :param format: Format of the student records to return to :return: Returns a list of student records", "name": "get", "signature": "def get(self, format=None, referralString=None)" }, { "docstring": "Create a student record :param format: Format of the...
2
null
Implement the Python class `CustomerRecordView` described below. Class description: A class based view for creating and fetching Sstudent records Method signatures and docstrings: - def get(self, format=None, referralString=None): Get all the student records :param format: Format of the student records to return to :...
Implement the Python class `CustomerRecordView` described below. Class description: A class based view for creating and fetching Sstudent records Method signatures and docstrings: - def get(self, format=None, referralString=None): Get all the student records :param format: Format of the student records to return to :...
88e4e994a029527d9e6b9431155a81cd5774b63c
<|skeleton|> class CustomerRecordView: """A class based view for creating and fetching Sstudent records""" def get(self, format=None, referralString=None): """Get all the student records :param format: Format of the student records to return to :return: Returns a list of student records""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomerRecordView: """A class based view for creating and fetching Sstudent records""" def get(self, format=None, referralString=None): """Get all the student records :param format: Format of the student records to return to :return: Returns a list of student records""" customer = Custom...
the_stack_v2_python_sparse
myuser/views/customerView.py
anku580/Upfront---Backend
train
0
1f36ef73d6673e5cce8c454756a0c577f50400f7
[ "if flask.request.method == 'HEAD':\n ENFORCER.enforce_call(action='identity:check_token')\nelse:\n ENFORCER.enforce_call(action='identity:validate_token')\ntoken_id = flask.request.headers.get(authorization.SUBJECT_TOKEN_HEADER)\naccess_rules_support = flask.request.headers.get(authorization.ACCESS_RULES_HEA...
<|body_start_0|> if flask.request.method == 'HEAD': ENFORCER.enforce_call(action='identity:check_token') else: ENFORCER.enforce_call(action='identity:validate_token') token_id = flask.request.headers.get(authorization.SUBJECT_TOKEN_HEADER) access_rules_support = f...
AuthTokenResource
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthTokenResource: def get(self): """Validate a token. HEAD/GET /v3/auth/tokens""" <|body_0|> def post(self): """Issue a token. POST /v3/auth/tokens""" <|body_1|> def delete(self): """Revoke a token. DELETE /v3/auth/tokens""" <|body_2|> ...
stack_v2_sparse_classes_36k_train_020443
19,732
permissive
[ { "docstring": "Validate a token. HEAD/GET /v3/auth/tokens", "name": "get", "signature": "def get(self)" }, { "docstring": "Issue a token. POST /v3/auth/tokens", "name": "post", "signature": "def post(self)" }, { "docstring": "Revoke a token. DELETE /v3/auth/tokens", "name": ...
3
stack_v2_sparse_classes_30k_train_017933
Implement the Python class `AuthTokenResource` described below. Class description: Implement the AuthTokenResource class. Method signatures and docstrings: - def get(self): Validate a token. HEAD/GET /v3/auth/tokens - def post(self): Issue a token. POST /v3/auth/tokens - def delete(self): Revoke a token. DELETE /v3/a...
Implement the Python class `AuthTokenResource` described below. Class description: Implement the AuthTokenResource class. Method signatures and docstrings: - def get(self): Validate a token. HEAD/GET /v3/auth/tokens - def post(self): Issue a token. POST /v3/auth/tokens - def delete(self): Revoke a token. DELETE /v3/a...
03a0a8146a78682ede9eca12a5a7fdacde2035c8
<|skeleton|> class AuthTokenResource: def get(self): """Validate a token. HEAD/GET /v3/auth/tokens""" <|body_0|> def post(self): """Issue a token. POST /v3/auth/tokens""" <|body_1|> def delete(self): """Revoke a token. DELETE /v3/auth/tokens""" <|body_2|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AuthTokenResource: def get(self): """Validate a token. HEAD/GET /v3/auth/tokens""" if flask.request.method == 'HEAD': ENFORCER.enforce_call(action='identity:check_token') else: ENFORCER.enforce_call(action='identity:validate_token') token_id = flask.requ...
the_stack_v2_python_sparse
keystone/api/auth.py
sapcc/keystone
train
0
1478f8c47e76604624192b240102335b7d676374
[ "cur, k = (1, k - 1)\nwhile k:\n step, first, last = (0, cur, cur + 1)\n while first <= n:\n step += min(n + 1, last) - first\n first *= 10\n last *= 10\n if step <= k:\n cur += 1\n k -= step\n else:\n cur *= 10\n k -= 1\nreturn cur", "stack = list(rang...
<|body_start_0|> cur, k = (1, k - 1) while k: step, first, last = (0, cur, cur + 1) while first <= n: step += min(n + 1, last) - first first *= 10 last *= 10 if step <= k: cur += 1 k -= st...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findKthNumber(self, n, k): """:type n: int :type k: int :rtype: int""" <|body_0|> def findKthNumber2(self, n, k): """:type n: int :type k: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> cur, k = (1, k - 1) whil...
stack_v2_sparse_classes_36k_train_020444
2,115
no_license
[ { "docstring": ":type n: int :type k: int :rtype: int", "name": "findKthNumber", "signature": "def findKthNumber(self, n, k)" }, { "docstring": ":type n: int :type k: int :rtype: int", "name": "findKthNumber2", "signature": "def findKthNumber2(self, n, k)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findKthNumber(self, n, k): :type n: int :type k: int :rtype: int - def findKthNumber2(self, n, k): :type n: int :type k: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findKthNumber(self, n, k): :type n: int :type k: int :rtype: int - def findKthNumber2(self, n, k): :type n: int :type k: int :rtype: int <|skeleton|> class Solution: de...
635af6e22aa8eef8e7920a585d43a45a891a8157
<|skeleton|> class Solution: def findKthNumber(self, n, k): """:type n: int :type k: int :rtype: int""" <|body_0|> def findKthNumber2(self, n, k): """:type n: int :type k: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findKthNumber(self, n, k): """:type n: int :type k: int :rtype: int""" cur, k = (1, k - 1) while k: step, first, last = (0, cur, cur + 1) while first <= n: step += min(n + 1, last) - first first *= 10 ...
the_stack_v2_python_sparse
code440KthSmallestInLexicographicalOrder.py
cybelewang/leetcode-python
train
0
4494fe439490ad955a04fded2b118d0b0ddfe8b0
[ "access_token = attrs['access_token']\nopenid = check_save_user_openid(access_token)\nif not openid:\n raise serializers.ValidationError('openid失效')\nmobile = attrs['mobile']\nuser = None\ntry:\n user = User.objects.get(username=mobile)\nexcept User.DoesNotExist:\n pass\nelse:\n if not user.check_passwo...
<|body_start_0|> access_token = attrs['access_token'] openid = check_save_user_openid(access_token) if not openid: raise serializers.ValidationError('openid失效') mobile = attrs['mobile'] user = None try: user = User.objects.get(username=mobile) ...
QQUserSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QQUserSerializer: def validate(self, attrs): """多字段校验""" <|body_0|> def create(self, validated_data): """validated_data,就上面返回的attrs""" <|body_1|> <|end_skeleton|> <|body_start_0|> access_token = attrs['access_token'] openid = check_save_user...
stack_v2_sparse_classes_36k_train_020445
2,162
no_license
[ { "docstring": "多字段校验", "name": "validate", "signature": "def validate(self, attrs)" }, { "docstring": "validated_data,就上面返回的attrs", "name": "create", "signature": "def create(self, validated_data)" } ]
2
stack_v2_sparse_classes_30k_train_006860
Implement the Python class `QQUserSerializer` described below. Class description: Implement the QQUserSerializer class. Method signatures and docstrings: - def validate(self, attrs): 多字段校验 - def create(self, validated_data): validated_data,就上面返回的attrs
Implement the Python class `QQUserSerializer` described below. Class description: Implement the QQUserSerializer class. Method signatures and docstrings: - def validate(self, attrs): 多字段校验 - def create(self, validated_data): validated_data,就上面返回的attrs <|skeleton|> class QQUserSerializer: def validate(self, attr...
81b8cf5213937504828c0c41740859f32f3427f8
<|skeleton|> class QQUserSerializer: def validate(self, attrs): """多字段校验""" <|body_0|> def create(self, validated_data): """validated_data,就上面返回的attrs""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QQUserSerializer: def validate(self, attrs): """多字段校验""" access_token = attrs['access_token'] openid = check_save_user_openid(access_token) if not openid: raise serializers.ValidationError('openid失效') mobile = attrs['mobile'] user = None try:...
the_stack_v2_python_sparse
blogs/apps/oauth/serializers.py
iue-L/Personal-Blog
train
0
5205d572029108efc634f39bd6720b5a0692a170
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Proto file describing the keyword plan service. Service to manage keyword plans.
KeywordPlanServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KeywordPlanServiceServicer: """Proto file describing the keyword plan service. Service to manage keyword plans.""" def GetKeywordPlan(self, request, context): """Returns the requested plan in full detail.""" <|body_0|> def MutateKeywordPlans(self, request, context): ...
stack_v2_sparse_classes_36k_train_020446
14,732
permissive
[ { "docstring": "Returns the requested plan in full detail.", "name": "GetKeywordPlan", "signature": "def GetKeywordPlan(self, request, context)" }, { "docstring": "Creates, updates, or removes keyword plans. Operation statuses are returned.", "name": "MutateKeywordPlans", "signature": "d...
6
null
Implement the Python class `KeywordPlanServiceServicer` described below. Class description: Proto file describing the keyword plan service. Service to manage keyword plans. Method signatures and docstrings: - def GetKeywordPlan(self, request, context): Returns the requested plan in full detail. - def MutateKeywordPla...
Implement the Python class `KeywordPlanServiceServicer` described below. Class description: Proto file describing the keyword plan service. Service to manage keyword plans. Method signatures and docstrings: - def GetKeywordPlan(self, request, context): Returns the requested plan in full detail. - def MutateKeywordPla...
969eff5b6c3cec59d21191fa178cffb6270074c3
<|skeleton|> class KeywordPlanServiceServicer: """Proto file describing the keyword plan service. Service to manage keyword plans.""" def GetKeywordPlan(self, request, context): """Returns the requested plan in full detail.""" <|body_0|> def MutateKeywordPlans(self, request, context): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KeywordPlanServiceServicer: """Proto file describing the keyword plan service. Service to manage keyword plans.""" def GetKeywordPlan(self, request, context): """Returns the requested plan in full detail.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Meth...
the_stack_v2_python_sparse
google/ads/google_ads/v6/proto/services/keyword_plan_service_pb2_grpc.py
VincentFritzsche/google-ads-python
train
0
16ee59bd2aa7907a32a8c635c5f27a1f27830b51
[ "date_conv_fn = import_data.StateGDPDataLoader.date_to_obs_date\nself.assertEqual(date_conv_fn('2005:Q1'), '2005-03')\nself.assertEqual(date_conv_fn('2005:Q2'), '2005-06')\nself.assertEqual(date_conv_fn('2005:Q3'), '2005-09')\nself.assertEqual(date_conv_fn('2005:Q4'), '2005-12')\nself.assertEqual(date_conv_fn('1999...
<|body_start_0|> date_conv_fn = import_data.StateGDPDataLoader.date_to_obs_date self.assertEqual(date_conv_fn('2005:Q1'), '2005-03') self.assertEqual(date_conv_fn('2005:Q2'), '2005-06') self.assertEqual(date_conv_fn('2005:Q3'), '2005-09') self.assertEqual(date_conv_fn('2005:Q4'),...
USStateQuarterlyGDPImportTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class USStateQuarterlyGDPImportTest: def test_date_converter(self): """Tests the date converter function used to process raw data.""" <|body_0|> def test_geoid_converter(self): """Tests the geoid converter function used to process raw data.""" <|body_1|> def t...
stack_v2_sparse_classes_36k_train_020447
5,596
permissive
[ { "docstring": "Tests the date converter function used to process raw data.", "name": "test_date_converter", "signature": "def test_date_converter(self)" }, { "docstring": "Tests the geoid converter function used to process raw data.", "name": "test_geoid_converter", "signature": "def te...
4
stack_v2_sparse_classes_30k_train_008623
Implement the Python class `USStateQuarterlyGDPImportTest` described below. Class description: Implement the USStateQuarterlyGDPImportTest class. Method signatures and docstrings: - def test_date_converter(self): Tests the date converter function used to process raw data. - def test_geoid_converter(self): Tests the g...
Implement the Python class `USStateQuarterlyGDPImportTest` described below. Class description: Implement the USStateQuarterlyGDPImportTest class. Method signatures and docstrings: - def test_date_converter(self): Tests the date converter function used to process raw data. - def test_geoid_converter(self): Tests the g...
6b32c869f426a8a5ba1b99edd324cc0c77bbd4ad
<|skeleton|> class USStateQuarterlyGDPImportTest: def test_date_converter(self): """Tests the date converter function used to process raw data.""" <|body_0|> def test_geoid_converter(self): """Tests the geoid converter function used to process raw data.""" <|body_1|> def t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class USStateQuarterlyGDPImportTest: def test_date_converter(self): """Tests the date converter function used to process raw data.""" date_conv_fn = import_data.StateGDPDataLoader.date_to_obs_date self.assertEqual(date_conv_fn('2005:Q1'), '2005-03') self.assertEqual(date_conv_fn('200...
the_stack_v2_python_sparse
scripts/us_bea/states_gdp/import_data_test.py
wh1210/data
train
1
c8a4764cb5c2b65ee19853996dee12e3e9c46313
[ "super(RelationNetwork, self).__init__()\nself.query_dim = query_dim\nself.input_dim_g = self.query_dim\nself.hidden_dims_g = hidden_dims_g\nself.output_dim_g = output_dim_g\nself.drops_g = drops_g\nself.drop_prob_g = drop_prob_g\nself.input_dim_f = self.output_dim_g\nself.hidden_dims_f = hidden_dims_f\nself.output...
<|body_start_0|> super(RelationNetwork, self).__init__() self.query_dim = query_dim self.input_dim_g = self.query_dim self.hidden_dims_g = hidden_dims_g self.output_dim_g = output_dim_g self.drops_g = drops_g self.drop_prob_g = drop_prob_g self.input_dim_f...
RelationNetwork
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelationNetwork: def __init__(self, query_dim, hidden_dims_g, output_dim_g, drops_g, drop_prob_g, hidden_dims_f, output_dim_f, drops_f, drop_prob_f, batch_size, device): """:param object_dim: Equal to LSTM hidden dim. Dimension of the single object to be taken into consideration from g."...
stack_v2_sparse_classes_36k_train_020448
1,471
no_license
[ { "docstring": ":param object_dim: Equal to LSTM hidden dim. Dimension of the single object to be taken into consideration from g.", "name": "__init__", "signature": "def __init__(self, query_dim, hidden_dims_g, output_dim_g, drops_g, drop_prob_g, hidden_dims_f, output_dim_f, drops_f, drop_prob_f, batch...
2
stack_v2_sparse_classes_30k_train_015014
Implement the Python class `RelationNetwork` described below. Class description: Implement the RelationNetwork class. Method signatures and docstrings: - def __init__(self, query_dim, hidden_dims_g, output_dim_g, drops_g, drop_prob_g, hidden_dims_f, output_dim_f, drops_f, drop_prob_f, batch_size, device): :param obje...
Implement the Python class `RelationNetwork` described below. Class description: Implement the RelationNetwork class. Method signatures and docstrings: - def __init__(self, query_dim, hidden_dims_g, output_dim_g, drops_g, drop_prob_g, hidden_dims_f, output_dim_f, drops_f, drop_prob_f, batch_size, device): :param obje...
f4786230d9f82b46a3cb92468df47faefd5a2892
<|skeleton|> class RelationNetwork: def __init__(self, query_dim, hidden_dims_g, output_dim_g, drops_g, drop_prob_g, hidden_dims_f, output_dim_f, drops_f, drop_prob_f, batch_size, device): """:param object_dim: Equal to LSTM hidden dim. Dimension of the single object to be taken into consideration from g."...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RelationNetwork: def __init__(self, query_dim, hidden_dims_g, output_dim_g, drops_g, drop_prob_g, hidden_dims_f, output_dim_f, drops_f, drop_prob_f, batch_size, device): """:param object_dim: Equal to LSTM hidden dim. Dimension of the single object to be taken into consideration from g.""" sup...
the_stack_v2_python_sparse
src/models/RN_image_for_LSTM.py
nicosoto0/Relation-Network-PyTorch
train
0
1e3ec76c2f3a9b273067468fe1be299bc5bdce02
[ "edges = []\nnodesSet = set()\nfor i in range(len(words)):\n word = words[i]\n edgeFormed = False\n for j in range(len(word)):\n if edgeFormed == False and i > 0 and (j < len(words[i - 1])) and (words[i][j] != words[i - 1][j]):\n edges.append([words[i - 1][j], words[i][j]])\n e...
<|body_start_0|> edges = [] nodesSet = set() for i in range(len(words)): word = words[i] edgeFormed = False for j in range(len(word)): if edgeFormed == False and i > 0 and (j < len(words[i - 1])) and (words[i][j] != words[i - 1][j]): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def alienOrder(self, words): """:type words: List[str] :rtype: str""" <|body_0|> def topoSortInBFS(self, prerequisites, nodes): """:type prerequisites: List[List[string]] e.g. [[to1, from1], [to2, from2],...] :rtype: List[string]""" <|body_1|> <|en...
stack_v2_sparse_classes_36k_train_020449
5,695
no_license
[ { "docstring": ":type words: List[str] :rtype: str", "name": "alienOrder", "signature": "def alienOrder(self, words)" }, { "docstring": ":type prerequisites: List[List[string]] e.g. [[to1, from1], [to2, from2],...] :rtype: List[string]", "name": "topoSortInBFS", "signature": "def topoSor...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def alienOrder(self, words): :type words: List[str] :rtype: str - def topoSortInBFS(self, prerequisites, nodes): :type prerequisites: List[List[string]] e.g. [[to1, from1], [to2,...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def alienOrder(self, words): :type words: List[str] :rtype: str - def topoSortInBFS(self, prerequisites, nodes): :type prerequisites: List[List[string]] e.g. [[to1, from1], [to2,...
1bd17e867d1d557a6ebbbd99f693d5fbd9f5b61e
<|skeleton|> class Solution: def alienOrder(self, words): """:type words: List[str] :rtype: str""" <|body_0|> def topoSortInBFS(self, prerequisites, nodes): """:type prerequisites: List[List[string]] e.g. [[to1, from1], [to2, from2],...] :rtype: List[string]""" <|body_1|> <|en...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def alienOrder(self, words): """:type words: List[str] :rtype: str""" edges = [] nodesSet = set() for i in range(len(words)): word = words[i] edgeFormed = False for j in range(len(word)): if edgeFormed == False and i...
the_stack_v2_python_sparse
leetcode/269-alien-dictionary/main.py
shriharshs/AlgoDaily
train
0
1ee71852d01cf85e654656dcbe0520b9665d535f
[ "if self._number_of_objects >= 2:\n self.bind()\n GL.glDrawArrays(GL.GL_LINE_STRIP_ADJACENCY, 0, self._number_of_objects + 2)\n self.unbind()", "self._number_of_objects = path.number_of_points\nvertexes = np.zeros((self._number_of_objects + 2, 2), dtype=np.float32)\nvertexes[1:-1] = path.points\nvertexes...
<|body_start_0|> if self._number_of_objects >= 2: self.bind() GL.glDrawArrays(GL.GL_LINE_STRIP_ADJACENCY, 0, self._number_of_objects + 2) self.unbind() <|end_body_0|> <|body_start_1|> self._number_of_objects = path.number_of_points vertexes = np.zeros((self._...
Base class to draw segments primitives as line strips.
LineStripVertexArray
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LineStripVertexArray: """Base class to draw segments primitives as line strips.""" def draw(self): """Draw the vertex array as lines.""" <|body_0|> def set(self, path): """Set the vertex array from an iterable of segments.""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_020450
7,026
no_license
[ { "docstring": "Draw the vertex array as lines.", "name": "draw", "signature": "def draw(self)" }, { "docstring": "Set the vertex array from an iterable of segments.", "name": "set", "signature": "def set(self, path)" } ]
2
null
Implement the Python class `LineStripVertexArray` described below. Class description: Base class to draw segments primitives as line strips. Method signatures and docstrings: - def draw(self): Draw the vertex array as lines. - def set(self, path): Set the vertex array from an iterable of segments.
Implement the Python class `LineStripVertexArray` described below. Class description: Base class to draw segments primitives as line strips. Method signatures and docstrings: - def draw(self): Draw the vertex array as lines. - def set(self, path): Set the vertex array from an iterable of segments. <|skeleton|> class...
53203ba2f8a1a99683ee7e23ef7618d1956ebcd8
<|skeleton|> class LineStripVertexArray: """Base class to draw segments primitives as line strips.""" def draw(self): """Draw the vertex array as lines.""" <|body_0|> def set(self, path): """Set the vertex array from an iterable of segments.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LineStripVertexArray: """Base class to draw segments primitives as line strips.""" def draw(self): """Draw the vertex array as lines.""" if self._number_of_objects >= 2: self.bind() GL.glDrawArrays(GL.GL_LINE_STRIP_ADJACENCY, 0, self._number_of_objects + 2) ...
the_stack_v2_python_sparse
Elbrea/GraphicEngine/PrimitiveVertexArray.py
FabriceSalvaire/elbrea
train
0
97ba2c8dbb90199871ebead20570ddb79ccca4d5
[ "args = movie_list_parser.parse_args()\nname = args.get('name')\nmovie_lists = [movie_list.to_dict() for movie_list in db.get_movie_lists(name=name, session=session)]\nreturn jsonify(movie_lists)", "data = request.json\nname = data.get('name')\ntry:\n movie_list = db.get_list_by_exact_name(name=name, session=s...
<|body_start_0|> args = movie_list_parser.parse_args() name = args.get('name') movie_lists = [movie_list.to_dict() for movie_list in db.get_movie_lists(name=name, session=session)] return jsonify(movie_lists) <|end_body_0|> <|body_start_1|> data = request.json name = dat...
MovieListAPI
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovieListAPI: def get(self, session=None): """Gets movies lists""" <|body_0|> def post(self, session=None): """Create a new list""" <|body_1|> <|end_skeleton|> <|body_start_0|> args = movie_list_parser.parse_args() name = args.get('name') ...
stack_v2_sparse_classes_36k_train_020451
12,846
permissive
[ { "docstring": "Gets movies lists", "name": "get", "signature": "def get(self, session=None)" }, { "docstring": "Create a new list", "name": "post", "signature": "def post(self, session=None)" } ]
2
stack_v2_sparse_classes_30k_train_014614
Implement the Python class `MovieListAPI` described below. Class description: Implement the MovieListAPI class. Method signatures and docstrings: - def get(self, session=None): Gets movies lists - def post(self, session=None): Create a new list
Implement the Python class `MovieListAPI` described below. Class description: Implement the MovieListAPI class. Method signatures and docstrings: - def get(self, session=None): Gets movies lists - def post(self, session=None): Create a new list <|skeleton|> class MovieListAPI: def get(self, session=None): ...
ea95ff60041beaea9aacbc2d93549e3a6b981dc5
<|skeleton|> class MovieListAPI: def get(self, session=None): """Gets movies lists""" <|body_0|> def post(self, session=None): """Create a new list""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovieListAPI: def get(self, session=None): """Gets movies lists""" args = movie_list_parser.parse_args() name = args.get('name') movie_lists = [movie_list.to_dict() for movie_list in db.get_movie_lists(name=name, session=session)] return jsonify(movie_lists) def po...
the_stack_v2_python_sparse
flexget/components/managed_lists/lists/movie_list/api.py
BrutuZ/Flexget
train
1
7839938c10c11e00708856e0dc9081aa58c7c434
[ "try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\ntry:\n acc = acciones.read(org_fiscal_id, id)\nexcept EmptySetError:\n ns.abort(404, message=self.accion_not_found)\nexcept Exception as err:\n ns.abort(400, message=err)\nreturn acc", "try:\n verify_to...
<|body_start_0|> try: verify_token(request.headers) except Exception as err: ns.abort(401, message=err) try: acc = acciones.read(org_fiscal_id, id) except EmptySetError: ns.abort(404, message=self.accion_not_found) except Exception ...
Accion
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Accion: def get(self, org_fiscal_id, id): """Recuperar una Acción""" <|body_0|> def put(self, org_fiscal_id, id): """Actualizar una Acción""" <|body_1|> def delete(self, org_fiscal_id, id): """Eliminar una Acción""" <|body_2|> <|end_skel...
stack_v2_sparse_classes_36k_train_020452
6,129
no_license
[ { "docstring": "Recuperar una Acción", "name": "get", "signature": "def get(self, org_fiscal_id, id)" }, { "docstring": "Actualizar una Acción", "name": "put", "signature": "def put(self, org_fiscal_id, id)" }, { "docstring": "Eliminar una Acción", "name": "delete", "sign...
3
stack_v2_sparse_classes_30k_train_009064
Implement the Python class `Accion` described below. Class description: Implement the Accion class. Method signatures and docstrings: - def get(self, org_fiscal_id, id): Recuperar una Acción - def put(self, org_fiscal_id, id): Actualizar una Acción - def delete(self, org_fiscal_id, id): Eliminar una Acción
Implement the Python class `Accion` described below. Class description: Implement the Accion class. Method signatures and docstrings: - def get(self, org_fiscal_id, id): Recuperar una Acción - def put(self, org_fiscal_id, id): Actualizar una Acción - def delete(self, org_fiscal_id, id): Eliminar una Acción <|skeleto...
e00610fac26ef3ca078fd037c0649b70fa0e9a09
<|skeleton|> class Accion: def get(self, org_fiscal_id, id): """Recuperar una Acción""" <|body_0|> def put(self, org_fiscal_id, id): """Actualizar una Acción""" <|body_1|> def delete(self, org_fiscal_id, id): """Eliminar una Acción""" <|body_2|> <|end_skel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Accion: def get(self, org_fiscal_id, id): """Recuperar una Acción""" try: verify_token(request.headers) except Exception as err: ns.abort(401, message=err) try: acc = acciones.read(org_fiscal_id, id) except EmptySetError: ...
the_stack_v2_python_sparse
DOS/soa/service/genl/endpoints/acciones.py
Telematica/knight-rider
train
1
0610dc5dbcbf1f512f6285bdb1beff7f96cdd032
[ "self.db = db\nself.verbose = verbose\nself.notification_type = notification_type\nself.notification_origin = notification_origin\nself.process_id = process_id", "type_id = self.db.grep_id_from_lookup_table(id_field_name='NotificationTypeID', table_name='notification_types', where_field_name='Type', where_value=s...
<|body_start_0|> self.db = db self.verbose = verbose self.notification_type = notification_type self.notification_origin = notification_origin self.process_id = process_id <|end_body_0|> <|body_start_1|> type_id = self.db.grep_id_from_lookup_table(id_field_name='Notifica...
Notification
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Notification: def __init__(self, db, verbose, notification_type, notification_origin, process_id): """Constructor method for the Notification class. :param db : Database class object :type db : object :param verbose : whether to be verbose :type verbose : bool :param notification_type : ...
stack_v2_sparse_classes_36k_train_020453
2,669
no_license
[ { "docstring": "Constructor method for the Notification class. :param db : Database class object :type db : object :param verbose : whether to be verbose :type verbose : bool :param notification_type : notification type to use for the notification_spool table :type notification_type : str :param notification_or...
2
stack_v2_sparse_classes_30k_val_000715
Implement the Python class `Notification` described below. Class description: Implement the Notification class. Method signatures and docstrings: - def __init__(self, db, verbose, notification_type, notification_origin, process_id): Constructor method for the Notification class. :param db : Database class object :typ...
Implement the Python class `Notification` described below. Class description: Implement the Notification class. Method signatures and docstrings: - def __init__(self, db, verbose, notification_type, notification_origin, process_id): Constructor method for the Notification class. :param db : Database class object :typ...
f9df1b78cd96882009264d7fba122b294c7c6329
<|skeleton|> class Notification: def __init__(self, db, verbose, notification_type, notification_origin, process_id): """Constructor method for the Notification class. :param db : Database class object :type db : object :param verbose : whether to be verbose :type verbose : bool :param notification_type : ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Notification: def __init__(self, db, verbose, notification_type, notification_origin, process_id): """Constructor method for the Notification class. :param db : Database class object :type db : object :param verbose : whether to be verbose :type verbose : bool :param notification_type : notification t...
the_stack_v2_python_sparse
python/lib/database_lib/notification.py
gdevenyi/Loris-MRI
train
0
82b9754421ab4fae69abad4022d2f1e1b26ecf69
[ "self.heuristic = heuristic\nself.region = None\nself._locked = []\nself._resource_entity = {}\nself._entity_resource = {}\nfor key, entity in entity_config.statics.items():\n if entity.resource:\n self._entity_resource[key] = entity.resource.type", "if entity.id not in self._entity_resource:\n retur...
<|body_start_0|> self.heuristic = heuristic self.region = None self._locked = [] self._resource_entity = {} self._entity_resource = {} for key, entity in entity_config.statics.items(): if entity.resource: self._entity_resource[key] = entity.res...
Manages resources in the world and finds them. Member: heuristic -- Heuristic which calculates the distance of two points. region -- The region of the manager (data.world.region). _entity_resource -- Maps entity ids to resource types (dict). _locked -- List of locked entity (list): _resource_entity -- Maps resource typ...
ResourceManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResourceManager: """Manages resources in the world and finds them. Member: heuristic -- Heuristic which calculates the distance of two points. region -- The region of the manager (data.world.region). _entity_resource -- Maps entity ids to resource types (dict). _locked -- List of locked entity (l...
stack_v2_sparse_classes_36k_train_020454
7,472
no_license
[ { "docstring": "Test: >>> from ai import pathfinding >>> from data.config import entity as config >>> heuristic = pathfinding.EuclideanDistance() >>> entity_config = config.Entity() >>> entity = config.StaticEntity() >>> entity.resource = config.Resource() >>> entity.resource.type = 'resource1' >>> entity_confi...
5
stack_v2_sparse_classes_30k_train_011546
Implement the Python class `ResourceManager` described below. Class description: Manages resources in the world and finds them. Member: heuristic -- Heuristic which calculates the distance of two points. region -- The region of the manager (data.world.region). _entity_resource -- Maps entity ids to resource types (dic...
Implement the Python class `ResourceManager` described below. Class description: Manages resources in the world and finds them. Member: heuristic -- Heuristic which calculates the distance of two points. region -- The region of the manager (data.world.region). _entity_resource -- Maps entity ids to resource types (dic...
c38b43edb7ec54f18768564c42859195bc2477e4
<|skeleton|> class ResourceManager: """Manages resources in the world and finds them. Member: heuristic -- Heuristic which calculates the distance of two points. region -- The region of the manager (data.world.region). _entity_resource -- Maps entity ids to resource types (dict). _locked -- List of locked entity (l...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResourceManager: """Manages resources in the world and finds them. Member: heuristic -- Heuristic which calculates the distance of two points. region -- The region of the manager (data.world.region). _entity_resource -- Maps entity ids to resource types (dict). _locked -- List of locked entity (list): _resour...
the_stack_v2_python_sparse
python-prototype/data/world/resourcemanager.py
tea2code/fantasy-rts
train
0
a8e46204859361397a2393e6639a33754d3f4fff
[ "x, y, z = bfl_v\nself.x, self.y, self.z = (x, y, z)\nself.bfl_v = bfl_v\nself.verts = [[x + (v & 1), y + (v >> 1 & 1), z + (v >> 2 & 1)] for v in range(8)]\nself.cube_index = 0\nfor i in range(8):\n v = self.verts[INDEX[i]]\n value = volume[v[2]][v[1]][v[0]]\n if value < isolevel:\n self.cube_index...
<|body_start_0|> x, y, z = bfl_v self.x, self.y, self.z = (x, y, z) self.bfl_v = bfl_v self.verts = [[x + (v & 1), y + (v >> 1 & 1), z + (v >> 2 & 1)] for v in range(8)] self.cube_index = 0 for i in range(8): v = self.verts[INDEX[i]] value = volume...
Cube
[ "MIT", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Cube: def __init__(self, bfl_v: Tuple[int, int, int], volume: torch.Tensor, isolevel: float) -> None: """Initializes a cube given the bottom front left vertex coordinate and computes the cube configuration given vertex values and isolevel. Edge and vertex convention: v4_______e4_________...
stack_v2_sparse_classes_36k_train_020455
12,384
permissive
[ { "docstring": "Initializes a cube given the bottom front left vertex coordinate and computes the cube configuration given vertex values and isolevel. Edge and vertex convention: v4_______e4____________v5 /| /| / | / | e7/ | e5/ | /___|______e6_________/ | v7| | |v6 |e9 | | | | | |e8 |e10| e11| | | | | |______e...
3
null
Implement the Python class `Cube` described below. Class description: Implement the Cube class. Method signatures and docstrings: - def __init__(self, bfl_v: Tuple[int, int, int], volume: torch.Tensor, isolevel: float) -> None: Initializes a cube given the bottom front left vertex coordinate and computes the cube con...
Implement the Python class `Cube` described below. Class description: Implement the Cube class. Method signatures and docstrings: - def __init__(self, bfl_v: Tuple[int, int, int], volume: torch.Tensor, isolevel: float) -> None: Initializes a cube given the bottom front left vertex coordinate and computes the cube con...
a3d99cab6bf5eb69be8d5eb48895da6edd859565
<|skeleton|> class Cube: def __init__(self, bfl_v: Tuple[int, int, int], volume: torch.Tensor, isolevel: float) -> None: """Initializes a cube given the bottom front left vertex coordinate and computes the cube configuration given vertex values and isolevel. Edge and vertex convention: v4_______e4_________...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Cube: def __init__(self, bfl_v: Tuple[int, int, int], volume: torch.Tensor, isolevel: float) -> None: """Initializes a cube given the bottom front left vertex coordinate and computes the cube configuration given vertex values and isolevel. Edge and vertex convention: v4_______e4____________v5 /| /| / ...
the_stack_v2_python_sparse
pytorch3d/ops/marching_cubes.py
facebookresearch/pytorch3d
train
7,964
ddb64af9709111c0e60d971f5e7e71b9bd690403
[ "self.ptr = 0\nself.vecList = []\nfor v in vec:\n self.vecList.extend(v)", "val = self.vecList[self.ptr]\nself.ptr += 1\nreturn val", "if self.ptr == len(self.vecList):\n return False\nelse:\n return True" ]
<|body_start_0|> self.ptr = 0 self.vecList = [] for v in vec: self.vecList.extend(v) <|end_body_0|> <|body_start_1|> val = self.vecList[self.ptr] self.ptr += 1 return val <|end_body_1|> <|body_start_2|> if self.ptr == len(self.vecList): r...
Vector2D
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Vector2D: def __init__(self, vec): """:type vec: List[List[int]]""" <|body_0|> def next(self): """:rtype: int""" <|body_1|> def hasNext(self): """:rtype: bool""" <|body_2|> <|end_skeleton|> <|body_start_0|> self.ptr = 0 ...
stack_v2_sparse_classes_36k_train_020456
661
no_license
[ { "docstring": ":type vec: List[List[int]]", "name": "__init__", "signature": "def __init__(self, vec)" }, { "docstring": ":rtype: int", "name": "next", "signature": "def next(self)" }, { "docstring": ":rtype: bool", "name": "hasNext", "signature": "def hasNext(self)" }...
3
null
Implement the Python class `Vector2D` described below. Class description: Implement the Vector2D class. Method signatures and docstrings: - def __init__(self, vec): :type vec: List[List[int]] - def next(self): :rtype: int - def hasNext(self): :rtype: bool
Implement the Python class `Vector2D` described below. Class description: Implement the Vector2D class. Method signatures and docstrings: - def __init__(self, vec): :type vec: List[List[int]] - def next(self): :rtype: int - def hasNext(self): :rtype: bool <|skeleton|> class Vector2D: def __init__(self, vec): ...
48b43999fb7e2ed82d922e1f64ac76f8fabe4baa
<|skeleton|> class Vector2D: def __init__(self, vec): """:type vec: List[List[int]]""" <|body_0|> def next(self): """:rtype: int""" <|body_1|> def hasNext(self): """:rtype: bool""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Vector2D: def __init__(self, vec): """:type vec: List[List[int]]""" self.ptr = 0 self.vecList = [] for v in vec: self.vecList.extend(v) def next(self): """:rtype: int""" val = self.vecList[self.ptr] self.ptr += 1 return val ...
the_stack_v2_python_sparse
251.py
saleed/LeetCode
train
2
720ddb28d12da58cda11a10b8ba1f6ca94af5338
[ "if self.is_empty() or self.size()[1] < 1:\n raise ValueError('No X Axis available')\nreturn self._get_column(0)", "if self.is_empty() or self.size()[1] < 2:\n raise ValueError('No Y Axis available')\nreturn self._get_column(1)", "if self.is_empty() or self.size()[1] < 3:\n raise ValueError('No Z Axis ...
<|body_start_0|> if self.is_empty() or self.size()[1] < 1: raise ValueError('No X Axis available') return self._get_column(0) <|end_body_0|> <|body_start_1|> if self.is_empty() or self.size()[1] < 2: raise ValueError('No Y Axis available') return self._get_column...
RotationMatrix
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RotationMatrix: def x_vec(self): """Method returns a vector of the x axis values for the rotation matrix Raises: ValueError -- X axis values are missing from the matrix Returns: List[Integer] -- The vector of x-axis values""" <|body_0|> def y_vec(self): """Method ret...
stack_v2_sparse_classes_36k_train_020457
13,385
no_license
[ { "docstring": "Method returns a vector of the x axis values for the rotation matrix Raises: ValueError -- X axis values are missing from the matrix Returns: List[Integer] -- The vector of x-axis values", "name": "x_vec", "signature": "def x_vec(self)" }, { "docstring": "Method returns a vector ...
3
stack_v2_sparse_classes_30k_test_000763
Implement the Python class `RotationMatrix` described below. Class description: Implement the RotationMatrix class. Method signatures and docstrings: - def x_vec(self): Method returns a vector of the x axis values for the rotation matrix Raises: ValueError -- X axis values are missing from the matrix Returns: List[In...
Implement the Python class `RotationMatrix` described below. Class description: Implement the RotationMatrix class. Method signatures and docstrings: - def x_vec(self): Method returns a vector of the x axis values for the rotation matrix Raises: ValueError -- X axis values are missing from the matrix Returns: List[In...
bdbe85d4c2d4d47f946ad1c3683f6ea546be764e
<|skeleton|> class RotationMatrix: def x_vec(self): """Method returns a vector of the x axis values for the rotation matrix Raises: ValueError -- X axis values are missing from the matrix Returns: List[Integer] -- The vector of x-axis values""" <|body_0|> def y_vec(self): """Method ret...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RotationMatrix: def x_vec(self): """Method returns a vector of the x axis values for the rotation matrix Raises: ValueError -- X axis values are missing from the matrix Returns: List[Integer] -- The vector of x-axis values""" if self.is_empty() or self.size()[1] < 1: raise ValueErr...
the_stack_v2_python_sparse
matrix.py
tmantock/python
train
0
76782d495114de1f1b7006976adf26f57a44c34d
[ "Bullet.__init__(self, lifetime, alpha, beta, x, y)\nself.h = h\nself.w = tank_shell.get_width() / tank_shell.get_height() * self.h", "width = pygame.mask.from_surface(self.draw()).get_size()[0]\nheight = pygame.mask.from_surface(self.draw()).get_size()[1]\nself.ax = -self.alpha * self.vx - self.beta * self.vx * ...
<|body_start_0|> Bullet.__init__(self, lifetime, alpha, beta, x, y) self.h = h self.w = tank_shell.get_width() / tank_shell.get_height() * self.h <|end_body_0|> <|body_start_1|> width = pygame.mask.from_surface(self.draw()).get_size()[0] height = pygame.mask.from_surface(self.dr...
TankShell
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TankShell: def __init__(self, lifetime=shell_lifetime, h=shell_h, x=0, y=0, alpha=shell_alpha, beta=shell_beta): """Конструктор класса снарядов, которыми стреляет танк :param lifetime: время жизни снаряда в секундах :param alpha: параметр a в формуле силы трения F = -av - bv^2 :param bet...
stack_v2_sparse_classes_36k_train_020458
9,588
no_license
[ { "docstring": "Конструктор класса снарядов, которыми стреляет танк :param lifetime: время жизни снаряда в секундах :param alpha: параметр a в формуле силы трения F = -av - bv^2 :param beta: параметр b в формуле силы трения F = -av - bv^2 :param h: толщина снаряда :param x: начальная координата центра снаряда п...
3
stack_v2_sparse_classes_30k_train_014962
Implement the Python class `TankShell` described below. Class description: Implement the TankShell class. Method signatures and docstrings: - def __init__(self, lifetime=shell_lifetime, h=shell_h, x=0, y=0, alpha=shell_alpha, beta=shell_beta): Конструктор класса снарядов, которыми стреляет танк :param lifetime: время...
Implement the Python class `TankShell` described below. Class description: Implement the TankShell class. Method signatures and docstrings: - def __init__(self, lifetime=shell_lifetime, h=shell_h, x=0, y=0, alpha=shell_alpha, beta=shell_beta): Конструктор класса снарядов, которыми стреляет танк :param lifetime: время...
19d00443e953a487e762676d6682579a537f55f0
<|skeleton|> class TankShell: def __init__(self, lifetime=shell_lifetime, h=shell_h, x=0, y=0, alpha=shell_alpha, beta=shell_beta): """Конструктор класса снарядов, которыми стреляет танк :param lifetime: время жизни снаряда в секундах :param alpha: параметр a в формуле силы трения F = -av - bv^2 :param bet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TankShell: def __init__(self, lifetime=shell_lifetime, h=shell_h, x=0, y=0, alpha=shell_alpha, beta=shell_beta): """Конструктор класса снарядов, которыми стреляет танк :param lifetime: время жизни снаряда в секундах :param alpha: параметр a в формуле силы трения F = -av - bv^2 :param beta: параметр b ...
the_stack_v2_python_sparse
Лаба 8/modules/bullets.py
VladimirMolunov/molunov_infa_2021
train
0
b88668b8a5ae103983cf64389b1c0ac7cacf313f
[ "if max_iterations < 0:\n raise ValueError(f'Maximum iteration value must be positive, not {max_iterations}')\nself._MAX_ITERATIONS = max_iterations\nself._iteration_counter = 0", "self._iteration_counter += 1\nif self._iteration_counter > self._MAX_ITERATIONS:\n raise RuntimeError(f'Maximum of {self._MAX_I...
<|body_start_0|> if max_iterations < 0: raise ValueError(f'Maximum iteration value must be positive, not {max_iterations}') self._MAX_ITERATIONS = max_iterations self._iteration_counter = 0 <|end_body_0|> <|body_start_1|> self._iteration_counter += 1 if self._iterati...
Class to keep track of an iteration count
IterationCounter
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IterationCounter: """Class to keep track of an iteration count""" def __init__(self, max_iterations: int) -> None: """Creates an IterationCounter with a given amount of maximum iterations :param max_iterations: The maximum amount of iterations allowed :raises ValueError: If the value...
stack_v2_sparse_classes_36k_train_020459
1,000
permissive
[ { "docstring": "Creates an IterationCounter with a given amount of maximum iterations :param max_iterations: The maximum amount of iterations allowed :raises ValueError: If the value is negative", "name": "__init__", "signature": "def __init__(self, max_iterations: int) -> None" }, { "docstring"...
2
stack_v2_sparse_classes_30k_train_000929
Implement the Python class `IterationCounter` described below. Class description: Class to keep track of an iteration count Method signatures and docstrings: - def __init__(self, max_iterations: int) -> None: Creates an IterationCounter with a given amount of maximum iterations :param max_iterations: The maximum amou...
Implement the Python class `IterationCounter` described below. Class description: Class to keep track of an iteration count Method signatures and docstrings: - def __init__(self, max_iterations: int) -> None: Creates an IterationCounter with a given amount of maximum iterations :param max_iterations: The maximum amou...
59c9a35289fb29afedad0e3edd0519b67372ef9f
<|skeleton|> class IterationCounter: """Class to keep track of an iteration count""" def __init__(self, max_iterations: int) -> None: """Creates an IterationCounter with a given amount of maximum iterations :param max_iterations: The maximum amount of iterations allowed :raises ValueError: If the value...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IterationCounter: """Class to keep track of an iteration count""" def __init__(self, max_iterations: int) -> None: """Creates an IterationCounter with a given amount of maximum iterations :param max_iterations: The maximum amount of iterations allowed :raises ValueError: If the value is negative"...
the_stack_v2_python_sparse
hacker/hackvm/counter.py
Tenebrar/codebase
train
1
58993edcb981d0dff70b48a2ce8178787c1bc791
[ "super().__init__()\n\ndef block(in_feat, out_feat, normalize=True):\n layers = [torch.nn.Linear(in_feat, out_feat)]\n if normalize:\n layers.append(torch.nn.BatchNorm1d(out_feat, 0.8))\n layers.append(torch.nn.LeakyReLU(0.2, inplace=True))\n return layers\nself.model = torch.nn.Sequential(*block...
<|body_start_0|> super().__init__() def block(in_feat, out_feat, normalize=True): layers = [torch.nn.Linear(in_feat, out_feat)] if normalize: layers.append(torch.nn.BatchNorm1d(out_feat, 0.8)) layers.append(torch.nn.LeakyReLU(0.2, inplace=True)) ...
Very simple discriminator model
Generator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Generator: """Very simple discriminator model""" def __init__(self, latent_dim, img_shape): """Parameters ---------- latent_dim : int size of the latent dimension img_shape : tuple shape of generated images (including channels, excluding batch dimension)""" <|body_0|> de...
stack_v2_sparse_classes_36k_train_020460
2,584
permissive
[ { "docstring": "Parameters ---------- latent_dim : int size of the latent dimension img_shape : tuple shape of generated images (including channels, excluding batch dimension)", "name": "__init__", "signature": "def __init__(self, latent_dim, img_shape)" }, { "docstring": "Forwards a noise batch...
2
null
Implement the Python class `Generator` described below. Class description: Very simple discriminator model Method signatures and docstrings: - def __init__(self, latent_dim, img_shape): Parameters ---------- latent_dim : int size of the latent dimension img_shape : tuple shape of generated images (including channels,...
Implement the Python class `Generator` described below. Class description: Very simple discriminator model Method signatures and docstrings: - def __init__(self, latent_dim, img_shape): Parameters ---------- latent_dim : int size of the latent dimension img_shape : tuple shape of generated images (including channels,...
1078f5030b8aac2bf022daf5fa14d66f74c3c893
<|skeleton|> class Generator: """Very simple discriminator model""" def __init__(self, latent_dim, img_shape): """Parameters ---------- latent_dim : int size of the latent dimension img_shape : tuple shape of generated images (including channels, excluding batch dimension)""" <|body_0|> de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Generator: """Very simple discriminator model""" def __init__(self, latent_dim, img_shape): """Parameters ---------- latent_dim : int size of the latent dimension img_shape : tuple shape of generated images (including channels, excluding batch dimension)""" super().__init__() def...
the_stack_v2_python_sparse
dlutils/models/gans/gan/models.py
justusschock/dl-utils
train
15
2600bba18f39e4e9a14ae4ecb69ded51c385c635
[ "context = super().get_context_data(**kwargs)\norganization = Organization.objects.get(pk=self.request.GET.get('org'))\napplies_to_type_choices = self.get_applies_to_type_choices(organization)\nbasis_form = RightsForm(applies_to_type_choices=applies_to_type_choices, organization=organization)\ncontext['copyright_fo...
<|body_start_0|> context = super().get_context_data(**kwargs) organization = Organization.objects.get(pk=self.request.GET.get('org')) applies_to_type_choices = self.get_applies_to_type_choices(organization) basis_form = RightsForm(applies_to_type_choices=applies_to_type_choices, organiza...
Create Rights Statements.
RightsCreateView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RightsCreateView: """Create Rights Statements.""" def get_context_data(self, **kwargs): """Adds formsets to context data.""" <|body_0|> def form_valid(self, form): """Sets variables needed in formsets.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_020461
6,959
permissive
[ { "docstring": "Adds formsets to context data.", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" }, { "docstring": "Sets variables needed in formsets.", "name": "form_valid", "signature": "def form_valid(self, form)" } ]
2
stack_v2_sparse_classes_30k_train_009577
Implement the Python class `RightsCreateView` described below. Class description: Create Rights Statements. Method signatures and docstrings: - def get_context_data(self, **kwargs): Adds formsets to context data. - def form_valid(self, form): Sets variables needed in formsets.
Implement the Python class `RightsCreateView` described below. Class description: Create Rights Statements. Method signatures and docstrings: - def get_context_data(self, **kwargs): Adds formsets to context data. - def form_valid(self, form): Sets variables needed in formsets. <|skeleton|> class RightsCreateView: ...
896cff3566746001dd594baa2e85bf3256016efb
<|skeleton|> class RightsCreateView: """Create Rights Statements.""" def get_context_data(self, **kwargs): """Adds formsets to context data.""" <|body_0|> def form_valid(self, form): """Sets variables needed in formsets.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RightsCreateView: """Create Rights Statements.""" def get_context_data(self, **kwargs): """Adds formsets to context data.""" context = super().get_context_data(**kwargs) organization = Organization.objects.get(pk=self.request.GET.get('org')) applies_to_type_choices = self....
the_stack_v2_python_sparse
bag_transfer/rights/views.py
RockefellerArchiveCenter/aurora
train
24
d25a60fd706303e81a9eac9e4071776e34e9ba98
[ "self.surface = surface\nself.beans = beans\nself.__dict__.update(parameter_dict)\nself.x = None\nself.y = None\nself.x_off = None\nself.y_off = None\nself.vel = 3\nself.accel = -0.003\nself.width = self.surface.get_width()\nself.height = self.surface.get_height()\nself.color = pygame.Color(0, 0, 0, 0)", "if self...
<|body_start_0|> self.surface = surface self.beans = beans self.__dict__.update(parameter_dict) self.x = None self.y = None self.x_off = None self.y_off = None self.vel = 3 self.accel = -0.003 self.width = self.surface.get_width() s...
represents one colored line
Bean
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Bean: """represents one colored line""" def __init__(self, surface, beans, parameter_dict): """(pygame.Surface) surface - surface to draw on (list) beans - list of beans to remove self when velocity is 0 (dict) parameter_dict - dictionary of parameters""" <|body_0|> def ...
stack_v2_sparse_classes_36k_train_020462
3,495
no_license
[ { "docstring": "(pygame.Surface) surface - surface to draw on (list) beans - list of beans to remove self when velocity is 0 (dict) parameter_dict - dictionary of parameters", "name": "__init__", "signature": "def __init__(self, surface, beans, parameter_dict)" }, { "docstring": "draw line", ...
2
stack_v2_sparse_classes_30k_train_003237
Implement the Python class `Bean` described below. Class description: represents one colored line Method signatures and docstrings: - def __init__(self, surface, beans, parameter_dict): (pygame.Surface) surface - surface to draw on (list) beans - list of beans to remove self when velocity is 0 (dict) parameter_dict -...
Implement the Python class `Bean` described below. Class description: represents one colored line Method signatures and docstrings: - def __init__(self, surface, beans, parameter_dict): (pygame.Surface) surface - surface to draw on (list) beans - list of beans to remove self when velocity is 0 (dict) parameter_dict -...
1fd421195a2888c0588a49f5a043a1110eedcdbf
<|skeleton|> class Bean: """represents one colored line""" def __init__(self, surface, beans, parameter_dict): """(pygame.Surface) surface - surface to draw on (list) beans - list of beans to remove self when velocity is 0 (dict) parameter_dict - dictionary of parameters""" <|body_0|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Bean: """represents one colored line""" def __init__(self, surface, beans, parameter_dict): """(pygame.Surface) surface - surface to draw on (list) beans - list of beans to remove self when velocity is 0 (dict) parameter_dict - dictionary of parameters""" self.surface = surface se...
the_stack_v2_python_sparse
effects/CoffeeBean.py
gunny26/pygame
train
5
d58c3d0ba58abc3161954ae2dd6df303f0f3b343
[ "print(matrix_name, ':', file=file)\nmatr_print(self.repres_matr, file=file)\nprint(vector_name, ':', file=file)\nprint(self.repres_vect[0], file=file)\nprint('Average intensity:', self.avg_intensity, file=file)\nprint('Variation coefficient:', self.c_var, file=file)\nprint('=======END=======', '\\n', file=file)", ...
<|body_start_0|> print(matrix_name, ':', file=file) matr_print(self.repres_matr, file=file) print(vector_name, ':', file=file) print(self.repres_vect[0], file=file) print('Average intensity:', self.avg_intensity, file=file) print('Variation coefficient:', self.c_var, file...
PH stream class. Contains representation vector, representation matrix, representation matrix_0, stream control Markov chain dimensions, stream intensity, variation coefficient and correlation coefficient.
PHStream
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PHStream: """PH stream class. Contains representation vector, representation matrix, representation matrix_0, stream control Markov chain dimensions, stream intensity, variation coefficient and correlation coefficient.""" def print_characteristics(self, matrix_name, vector_name, file=sys.std...
stack_v2_sparse_classes_36k_train_020463
15,627
no_license
[ { "docstring": "Prints characteristics of PH stream: Matrix Vector Average intensity Variation coefficient Correlation coefficient :return: None", "name": "print_characteristics", "signature": "def print_characteristics(self, matrix_name, vector_name, file=sys.stdout)" }, { "docstring": "Constru...
2
stack_v2_sparse_classes_30k_train_010779
Implement the Python class `PHStream` described below. Class description: PH stream class. Contains representation vector, representation matrix, representation matrix_0, stream control Markov chain dimensions, stream intensity, variation coefficient and correlation coefficient. Method signatures and docstrings: - de...
Implement the Python class `PHStream` described below. Class description: PH stream class. Contains representation vector, representation matrix, representation matrix_0, stream control Markov chain dimensions, stream intensity, variation coefficient and correlation coefficient. Method signatures and docstrings: - de...
6173e0d279893f0da4f8ad09b824cd5897c4e5e7
<|skeleton|> class PHStream: """PH stream class. Contains representation vector, representation matrix, representation matrix_0, stream control Markov chain dimensions, stream intensity, variation coefficient and correlation coefficient.""" def print_characteristics(self, matrix_name, vector_name, file=sys.std...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PHStream: """PH stream class. Contains representation vector, representation matrix, representation matrix_0, stream control Markov chain dimensions, stream intensity, variation coefficient and correlation coefficient.""" def print_characteristics(self, matrix_name, vector_name, file=sys.stdout): ...
the_stack_v2_python_sparse
streams.py
pishchynski/magister_work
train
0
ff58b112c71fb75f708a16e9612ae1bf024cb9c9
[ "self._regex = regex\nself._intent = intent\nself._slots = slots", "match_objs = re.fullmatch(self._regex, text, re.IGNORECASE)\nif match_objs is None:\n return (None, None)\nelse:\n entities = []\n group = 1\n for slot in self._slots:\n entity = {'entity': slot, 'value': match_objs.group(group...
<|body_start_0|> self._regex = regex self._intent = intent self._slots = slots <|end_body_0|> <|body_start_1|> match_objs = re.fullmatch(self._regex, text, re.IGNORECASE) if match_objs is None: return (None, None) else: entities = [] g...
HcMatchItem
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HcMatchItem: def __init__(self, regex, intent, slots=[]): """:param regex: str, regular expression :param intent: str, intent name :param _slots: list, each slot name, ex: ['carno']""" <|body_0|> def match(self, text): """:param text: input meesage :return: (intent, ...
stack_v2_sparse_classes_36k_train_020464
7,023
no_license
[ { "docstring": ":param regex: str, regular expression :param intent: str, intent name :param _slots: list, each slot name, ex: ['carno']", "name": "__init__", "signature": "def __init__(self, regex, intent, slots=[])" }, { "docstring": ":param text: input meesage :return: (intent, [entity]) # ex...
2
stack_v2_sparse_classes_30k_train_000791
Implement the Python class `HcMatchItem` described below. Class description: Implement the HcMatchItem class. Method signatures and docstrings: - def __init__(self, regex, intent, slots=[]): :param regex: str, regular expression :param intent: str, intent name :param _slots: list, each slot name, ex: ['carno'] - def ...
Implement the Python class `HcMatchItem` described below. Class description: Implement the HcMatchItem class. Method signatures and docstrings: - def __init__(self, regex, intent, slots=[]): :param regex: str, regular expression :param intent: str, intent name :param _slots: list, each slot name, ex: ['carno'] - def ...
e8fc58cc6ac48e35dce97ae5817c0b7b573a2b6f
<|skeleton|> class HcMatchItem: def __init__(self, regex, intent, slots=[]): """:param regex: str, regular expression :param intent: str, intent name :param _slots: list, each slot name, ex: ['carno']""" <|body_0|> def match(self, text): """:param text: input meesage :return: (intent, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HcMatchItem: def __init__(self, regex, intent, slots=[]): """:param regex: str, regular expression :param intent: str, intent name :param _slots: list, each slot name, ex: ['carno']""" self._regex = regex self._intent = intent self._slots = slots def match(self, text): ...
the_stack_v2_python_sparse
hcbot/hc_featurizer.py
fenixchen/bot
train
0
35f10023a22bfdc7236cf747a45c183339c9831b
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jgrishey', 'jgrishey')\nstations = list(repo['jgrishey.redlineStations'].find(None, ['_id', 'lat', 'lon']))\nfor station in stations:\n url = 'http://api.geonames.org/findNearbyStreetsJSON?lat=%s&lng=...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('jgrishey', 'jgrishey') stations = list(repo['jgrishey.redlineStations'].find(None, ['_id', 'lat', 'lon'])) for station in stations: ur...
redlineStreets
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class redlineStreets: 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 everythin...
stack_v2_sparse_classes_36k_train_020465
4,285
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
stack_v2_sparse_classes_30k_train_005922
Implement the Python class `redlineStreets` described below. Class description: Implement the redlineStreets class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None,...
Implement the Python class `redlineStreets` described below. Class description: Implement the redlineStreets class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None,...
0df485d0469c5451ebdcd684bed2a0960ba3ab84
<|skeleton|> class redlineStreets: 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 everythin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class redlineStreets: 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('jgrishey', 'jgrishey') stati...
the_stack_v2_python_sparse
jgrishey/redlineStreets.py
lingyigu/course-2017-spr-proj
train
0
f53e8d47c874f62e63b8b4e7a2f1b6c2e94f4df6
[ "try:\n updated_exp_model = exp_services.populate_exp_model_fields(exp_model, migrated_exp)\n commit_message = 'Update exploration states schema version to %d.' % feconf.CURRENT_STATE_SCHEMA_VERSION\n models_to_put_values = []\n with datastore_services.get_ndb_context():\n models_to_put_values = ...
<|body_start_0|> try: updated_exp_model = exp_services.populate_exp_model_fields(exp_model, migrated_exp) commit_message = 'Update exploration states schema version to %d.' % feconf.CURRENT_STATE_SCHEMA_VERSION models_to_put_values = [] with datastore_services.get...
Job that migrates Exploration models.
MigrateExplorationJob
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MigrateExplorationJob: """Job that migrates Exploration models.""" def _update_exploration(exp_model: exp_models.ExplorationModel, migrated_exp: exp_domain.Exploration, exp_changes: Sequence[exp_domain.ExplorationChange]) -> result.Result[Tuple[base_models.BaseModel], Tuple[str, Exception]]:...
stack_v2_sparse_classes_36k_train_020466
28,752
permissive
[ { "docstring": "Generates newly updated exploration models. Args: exp_model: ExplorationModel. The exploration which should be updated. migrated_exp: Exploration. The migrated exploration domain object. exp_changes: Sequence(ExplorationChange). The exploration changes to apply. Returns: Sequence(BaseModel). Seq...
2
stack_v2_sparse_classes_30k_train_018577
Implement the Python class `MigrateExplorationJob` described below. Class description: Job that migrates Exploration models. Method signatures and docstrings: - def _update_exploration(exp_model: exp_models.ExplorationModel, migrated_exp: exp_domain.Exploration, exp_changes: Sequence[exp_domain.ExplorationChange]) ->...
Implement the Python class `MigrateExplorationJob` described below. Class description: Job that migrates Exploration models. Method signatures and docstrings: - def _update_exploration(exp_model: exp_models.ExplorationModel, migrated_exp: exp_domain.Exploration, exp_changes: Sequence[exp_domain.ExplorationChange]) ->...
d16fdf23d790eafd63812bd7239532256e30a21d
<|skeleton|> class MigrateExplorationJob: """Job that migrates Exploration models.""" def _update_exploration(exp_model: exp_models.ExplorationModel, migrated_exp: exp_domain.Exploration, exp_changes: Sequence[exp_domain.ExplorationChange]) -> result.Result[Tuple[base_models.BaseModel], Tuple[str, Exception]]:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MigrateExplorationJob: """Job that migrates Exploration models.""" def _update_exploration(exp_model: exp_models.ExplorationModel, migrated_exp: exp_domain.Exploration, exp_changes: Sequence[exp_domain.ExplorationChange]) -> result.Result[Tuple[base_models.BaseModel], Tuple[str, Exception]]: """G...
the_stack_v2_python_sparse
core/jobs/batch_jobs/exp_migration_jobs.py
oppia/oppia
train
6,172
b28584b8bbd98555f50b21a94c76f7dbfe38ef70
[ "super().__init__(hass, LOGGER, name=f'proxmox_coordinator_{host_name}_{container_id}', update_interval=timedelta(seconds=UPDATE_INTERVAL))\nself.hass = hass\nself.config_entry: ConfigEntry = self.config_entry\nself.proxmox = proxmox\nself.vm_id = container_id\nself.node_name: str", "def poll_api() -> dict[str, A...
<|body_start_0|> super().__init__(hass, LOGGER, name=f'proxmox_coordinator_{host_name}_{container_id}', update_interval=timedelta(seconds=UPDATE_INTERVAL)) self.hass = hass self.config_entry: ConfigEntry = self.config_entry self.proxmox = proxmox self.vm_id = container_id ...
Proxmox VE LXC data update coordinator.
ProxmoxLXCCoordinator
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProxmoxLXCCoordinator: """Proxmox VE LXC data update coordinator.""" def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, container_id: int) -> None: """Initialize the Proxmox LXC coordinator.""" <|body_0|> async def _async_update_data(self) -> Pr...
stack_v2_sparse_classes_36k_train_020467
15,228
permissive
[ { "docstring": "Initialize the Proxmox LXC coordinator.", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, container_id: int) -> None" }, { "docstring": "Update data for Proxmox LXC.", "name": "_async_update_data", "signature"...
2
null
Implement the Python class `ProxmoxLXCCoordinator` described below. Class description: Proxmox VE LXC data update coordinator. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, container_id: int) -> None: Initialize the Proxmox LXC coordinator. - async de...
Implement the Python class `ProxmoxLXCCoordinator` described below. Class description: Proxmox VE LXC data update coordinator. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, container_id: int) -> None: Initialize the Proxmox LXC coordinator. - async de...
8548d9999ddd54f13d6a307e013abcb8c897a74e
<|skeleton|> class ProxmoxLXCCoordinator: """Proxmox VE LXC data update coordinator.""" def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, container_id: int) -> None: """Initialize the Proxmox LXC coordinator.""" <|body_0|> async def _async_update_data(self) -> Pr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProxmoxLXCCoordinator: """Proxmox VE LXC data update coordinator.""" def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, container_id: int) -> None: """Initialize the Proxmox LXC coordinator.""" super().__init__(hass, LOGGER, name=f'proxmox_coordinator_{host_name}...
the_stack_v2_python_sparse
custom_components/proxmoxve/coordinator.py
bacco007/HomeAssistantConfig
train
98
712585e52a142d79ed465b0d7e1956605aeebbf5
[ "super().__init__(coordinator)\nself._region = region\nself._warning_index = slot_id - 1\nself._attr_name = f'Warning: {region_name} {slot_id}'\nself._attr_unique_id = f'{region}-{slot_id}'\nself._attr_device_class = BinarySensorDeviceClass.SAFETY", "if len(self.coordinator.data[self._region]) <= self._warning_in...
<|body_start_0|> super().__init__(coordinator) self._region = region self._warning_index = slot_id - 1 self._attr_name = f'Warning: {region_name} {slot_id}' self._attr_unique_id = f'{region}-{slot_id}' self._attr_device_class = BinarySensorDeviceClass.SAFETY <|end_body_0|...
Representation of an NINA warning.
NINAMessage
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NINAMessage: """Representation of an NINA warning.""" def __init__(self, coordinator: NINADataUpdateCoordinator, region: str, region_name: str, slot_id: int) -> None: """Initialize.""" <|body_0|> def is_on(self) -> bool: """Return the state of the sensor.""" ...
stack_v2_sparse_classes_36k_train_020468
2,968
permissive
[ { "docstring": "Initialize.", "name": "__init__", "signature": "def __init__(self, coordinator: NINADataUpdateCoordinator, region: str, region_name: str, slot_id: int) -> None" }, { "docstring": "Return the state of the sensor.", "name": "is_on", "signature": "def is_on(self) -> bool" ...
3
null
Implement the Python class `NINAMessage` described below. Class description: Representation of an NINA warning. Method signatures and docstrings: - def __init__(self, coordinator: NINADataUpdateCoordinator, region: str, region_name: str, slot_id: int) -> None: Initialize. - def is_on(self) -> bool: Return the state o...
Implement the Python class `NINAMessage` described below. Class description: Representation of an NINA warning. Method signatures and docstrings: - def __init__(self, coordinator: NINADataUpdateCoordinator, region: str, region_name: str, slot_id: int) -> None: Initialize. - def is_on(self) -> bool: Return the state o...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class NINAMessage: """Representation of an NINA warning.""" def __init__(self, coordinator: NINADataUpdateCoordinator, region: str, region_name: str, slot_id: int) -> None: """Initialize.""" <|body_0|> def is_on(self) -> bool: """Return the state of the sensor.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NINAMessage: """Representation of an NINA warning.""" def __init__(self, coordinator: NINADataUpdateCoordinator, region: str, region_name: str, slot_id: int) -> None: """Initialize.""" super().__init__(coordinator) self._region = region self._warning_index = slot_id - 1 ...
the_stack_v2_python_sparse
homeassistant/components/nina/binary_sensor.py
home-assistant/core
train
35,501
a2c38667236635c3e06674c183b0a89060446ce8
[ "if n <= 0:\n return False\nn = math.log2(n)\nif n == int(n):\n return True\nreturn False", "if n <= 0:\n return False\nreturn not n & n - 1" ]
<|body_start_0|> if n <= 0: return False n = math.log2(n) if n == int(n): return True return False <|end_body_0|> <|body_start_1|> if n <= 0: return False return not n & n - 1 <|end_body_1|>
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPowerOfTwo1(self, n): """:type n: int :rtype: bool""" <|body_0|> def isPowerOfTwo(self, n): """:type n: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if n <= 0: return False n = math.log2(n) ...
stack_v2_sparse_classes_36k_train_020469
560
no_license
[ { "docstring": ":type n: int :rtype: bool", "name": "isPowerOfTwo1", "signature": "def isPowerOfTwo1(self, n)" }, { "docstring": ":type n: int :rtype: bool", "name": "isPowerOfTwo", "signature": "def isPowerOfTwo(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_014149
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPowerOfTwo1(self, n): :type n: int :rtype: bool - def isPowerOfTwo(self, n): :type n: int :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPowerOfTwo1(self, n): :type n: int :rtype: bool - def isPowerOfTwo(self, n): :type n: int :rtype: bool <|skeleton|> class Solution: def isPowerOfTwo1(self, n): ...
70bdd75b6af2e1811c1beab22050c01d28d7373e
<|skeleton|> class Solution: def isPowerOfTwo1(self, n): """:type n: int :rtype: bool""" <|body_0|> def isPowerOfTwo(self, n): """:type n: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPowerOfTwo1(self, n): """:type n: int :rtype: bool""" if n <= 0: return False n = math.log2(n) if n == int(n): return True return False def isPowerOfTwo(self, n): """:type n: int :rtype: bool""" if n <= 0: ...
the_stack_v2_python_sparse
python/leetcode/231_Power_of_Two.py
bobcaoge/my-code
train
0
e69fe8db29fdeb13d71d438577ecc61ab3c011ff
[ "super(MainWindow, self).__init__(parent)\nself.setupUi(self)\nself.MAC = ''", "try:\n self.MAC = self.lineEdit_mac.text()\n if self.MAC == '':\n QMessageBox.warning(self, '提示', '请输入机器码!')\n else:\n ENCRY = set_config.encode('ncKZwpx0woLClw==', self.MAC + 'X84W-Q8KC-JWP8-6F7R')\n sel...
<|body_start_0|> super(MainWindow, self).__init__(parent) self.setupUi(self) self.MAC = '' <|end_body_0|> <|body_start_1|> try: self.MAC = self.lineEdit_mac.text() if self.MAC == '': QMessageBox.warning(self, '提示', '请输入机器码!') else: ...
Class documentation goes here.
MainWindow
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MainWindow: """Class documentation goes here.""" def __init__(self, parent=None): """Constructor @param parent reference to the parent widget @type QWidget""" <|body_0|> def on_pushButton_clicked(self): """Slot documentation goes here.""" <|body_1|> <|en...
stack_v2_sparse_classes_36k_train_020470
1,385
no_license
[ { "docstring": "Constructor @param parent reference to the parent widget @type QWidget", "name": "__init__", "signature": "def __init__(self, parent=None)" }, { "docstring": "Slot documentation goes here.", "name": "on_pushButton_clicked", "signature": "def on_pushButton_clicked(self)" ...
2
stack_v2_sparse_classes_30k_train_013064
Implement the Python class `MainWindow` described below. Class description: Class documentation goes here. Method signatures and docstrings: - def __init__(self, parent=None): Constructor @param parent reference to the parent widget @type QWidget - def on_pushButton_clicked(self): Slot documentation goes here.
Implement the Python class `MainWindow` described below. Class description: Class documentation goes here. Method signatures and docstrings: - def __init__(self, parent=None): Constructor @param parent reference to the parent widget @type QWidget - def on_pushButton_clicked(self): Slot documentation goes here. <|ske...
6ec9027b679bbb707436b9a4095d995265b266c8
<|skeleton|> class MainWindow: """Class documentation goes here.""" def __init__(self, parent=None): """Constructor @param parent reference to the parent widget @type QWidget""" <|body_0|> def on_pushButton_clicked(self): """Slot documentation goes here.""" <|body_1|> <|en...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MainWindow: """Class documentation goes here.""" def __init__(self, parent=None): """Constructor @param parent reference to the parent widget @type QWidget""" super(MainWindow, self).__init__(parent) self.setupUi(self) self.MAC = '' def on_pushButton_clicked(self): ...
the_stack_v2_python_sparse
src/registor/SoftRegistor.py
fzero17/college_wish
train
0
6565dd37f814dd602ed8b9dbf4480676f157da9f
[ "choices = super(ChildModelPluginPolymorphicParentModelAdmin, self).get_child_type_choices(request, action)\nplugins = self.child_model_plugin_class.get_plugins()\nlabels = {}\nsort_priorities = {}\nif plugins:\n for plugin in plugins:\n pk = plugin.content_type.pk\n labels[pk] = capfirst(plugin.ve...
<|body_start_0|> choices = super(ChildModelPluginPolymorphicParentModelAdmin, self).get_child_type_choices(request, action) plugins = self.child_model_plugin_class.get_plugins() labels = {} sort_priorities = {} if plugins: for plugin in plugins: pk = p...
Get child models and choice labels from registered plugins.
ChildModelPluginPolymorphicParentModelAdmin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChildModelPluginPolymorphicParentModelAdmin: """Get child models and choice labels from registered plugins.""" def get_child_type_choices(self, request, action): """Override choice labels with ``verbose_name`` from plugins and sort.""" <|body_0|> def get_child_models(sel...
stack_v2_sparse_classes_36k_train_020471
9,643
permissive
[ { "docstring": "Override choice labels with ``verbose_name`` from plugins and sort.", "name": "get_child_type_choices", "signature": "def get_child_type_choices(self, request, action)" }, { "docstring": "Get child models from registered plugins. Fallback to the child model admin and its base mod...
2
stack_v2_sparse_classes_30k_train_001221
Implement the Python class `ChildModelPluginPolymorphicParentModelAdmin` described below. Class description: Get child models and choice labels from registered plugins. Method signatures and docstrings: - def get_child_type_choices(self, request, action): Override choice labels with ``verbose_name`` from plugins and ...
Implement the Python class `ChildModelPluginPolymorphicParentModelAdmin` described below. Class description: Get child models and choice labels from registered plugins. Method signatures and docstrings: - def get_child_type_choices(self, request, action): Override choice labels with ``verbose_name`` from plugins and ...
c507ea5b1864303732c53ad7c5800571fca5fa94
<|skeleton|> class ChildModelPluginPolymorphicParentModelAdmin: """Get child models and choice labels from registered plugins.""" def get_child_type_choices(self, request, action): """Override choice labels with ``verbose_name`` from plugins and sort.""" <|body_0|> def get_child_models(sel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChildModelPluginPolymorphicParentModelAdmin: """Get child models and choice labels from registered plugins.""" def get_child_type_choices(self, request, action): """Override choice labels with ``verbose_name`` from plugins and sort.""" choices = super(ChildModelPluginPolymorphicParentMode...
the_stack_v2_python_sparse
icekit/admin_tools/polymorphic.py
ic-labs/django-icekit
train
53
32f7c3700045023f2e50252a59b90f773f490e69
[ "self.x = x\nself.y = y\nself.width = width\nself.length = length\nself.psi = psi", "aligned_covariance = np.array([[self.length.to_value(u.m) ** 2, 0], [0, self.width.to_value(u.m) ** 2]])\nrotation = linalg.rotation_matrix_2d(self.psi)\nrotated_covariance = rotation @ aligned_covariance @ rotation.T\nreturn mul...
<|body_start_0|> self.x = x self.y = y self.width = width self.length = length self.psi = psi <|end_body_0|> <|body_start_1|> aligned_covariance = np.array([[self.length.to_value(u.m) ** 2, 0], [0, self.width.to_value(u.m) ** 2]]) rotation = linalg.rotation_matri...
Gaussian
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Gaussian: def __init__(self, x, y, length, width, psi): """Create 2D Gaussian model for a shower image in a camera. Parameters ---------- centroid : u.Quantity[length, shape=(2, )] position of the centroid of the shower in camera coordinates width: u.Quantity[length] width of shower (min...
stack_v2_sparse_classes_36k_train_020472
12,327
permissive
[ { "docstring": "Create 2D Gaussian model for a shower image in a camera. Parameters ---------- centroid : u.Quantity[length, shape=(2, )] position of the centroid of the shower in camera coordinates width: u.Quantity[length] width of shower (minor axis) length: u.Quantity[length] length of shower (major axis) p...
2
stack_v2_sparse_classes_30k_train_017129
Implement the Python class `Gaussian` described below. Class description: Implement the Gaussian class. Method signatures and docstrings: - def __init__(self, x, y, length, width, psi): Create 2D Gaussian model for a shower image in a camera. Parameters ---------- centroid : u.Quantity[length, shape=(2, )] position o...
Implement the Python class `Gaussian` described below. Class description: Implement the Gaussian class. Method signatures and docstrings: - def __init__(self, x, y, length, width, psi): Create 2D Gaussian model for a shower image in a camera. Parameters ---------- centroid : u.Quantity[length, shape=(2, )] position o...
10b058f8dcc166177d1eb5b2af638ca37722a021
<|skeleton|> class Gaussian: def __init__(self, x, y, length, width, psi): """Create 2D Gaussian model for a shower image in a camera. Parameters ---------- centroid : u.Quantity[length, shape=(2, )] position of the centroid of the shower in camera coordinates width: u.Quantity[length] width of shower (min...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Gaussian: def __init__(self, x, y, length, width, psi): """Create 2D Gaussian model for a shower image in a camera. Parameters ---------- centroid : u.Quantity[length, shape=(2, )] position of the centroid of the shower in camera coordinates width: u.Quantity[length] width of shower (minor axis) lengt...
the_stack_v2_python_sparse
ctapipe/image/toymodel.py
cta-sst-1m/ctapipe
train
1
6a143293e3b168d679bc5c10d4ec7f30d379c03d
[ "super(FuncAwsGuarddutyPoller, self).__init__(opts)\nself.options = opts.get('fn_aws_guardduty', {})\nself.opts = opts\nif int(self.options.get('aws_gd_polling_interval', POLLING_INTERVAL_DEFAULT)) == 0:\n LOG.info('Polling for findings in AWS GuardDuty not enabled')\nelse:\n validate_fields(config.REQUIRED_C...
<|body_start_0|> super(FuncAwsGuarddutyPoller, self).__init__(opts) self.options = opts.get('fn_aws_guardduty', {}) self.opts = opts if int(self.options.get('aws_gd_polling_interval', POLLING_INTERVAL_DEFAULT)) == 0: LOG.info('Polling for findings in AWS GuardDuty not enabled...
Component that polls for new findings from AWS GuardDuty
FuncAwsGuarddutyPoller
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FuncAwsGuarddutyPoller: """Component that polls for new findings from AWS GuardDuty""" def __init__(self, opts): """constructor provides access to the configuration options""" <|body_0|> def _reload(self, event, opts): """Configuration options have changed, save ...
stack_v2_sparse_classes_36k_train_020473
3,403
permissive
[ { "docstring": "constructor provides access to the configuration options", "name": "__init__", "signature": "def __init__(self, opts)" }, { "docstring": "Configuration options have changed, save new values", "name": "_reload", "signature": "def _reload(self, event, opts)" }, { "d...
3
stack_v2_sparse_classes_30k_train_021595
Implement the Python class `FuncAwsGuarddutyPoller` described below. Class description: Component that polls for new findings from AWS GuardDuty Method signatures and docstrings: - def __init__(self, opts): constructor provides access to the configuration options - def _reload(self, event, opts): Configuration option...
Implement the Python class `FuncAwsGuarddutyPoller` described below. Class description: Component that polls for new findings from AWS GuardDuty Method signatures and docstrings: - def __init__(self, opts): constructor provides access to the configuration options - def _reload(self, event, opts): Configuration option...
6878c78b94eeca407998a41ce8db2cc00f2b6758
<|skeleton|> class FuncAwsGuarddutyPoller: """Component that polls for new findings from AWS GuardDuty""" def __init__(self, opts): """constructor provides access to the configuration options""" <|body_0|> def _reload(self, event, opts): """Configuration options have changed, save ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FuncAwsGuarddutyPoller: """Component that polls for new findings from AWS GuardDuty""" def __init__(self, opts): """constructor provides access to the configuration options""" super(FuncAwsGuarddutyPoller, self).__init__(opts) self.options = opts.get('fn_aws_guardduty', {}) ...
the_stack_v2_python_sparse
fn_aws_guardduty/fn_aws_guardduty/components/func_aws_guardduty_poller.py
ibmresilient/resilient-community-apps
train
81
c4bc54e21865a71d235cf4882725cc5ead0a15dd
[ "self.domain_id = domain_id\nself.view_box_id = view_box_id\nself.view_box_name = view_box_name", "if dictionary is None:\n return None\ndomain_id = dictionary.get('domainId')\nview_box_id = dictionary.get('viewBoxId')\nview_box_name = dictionary.get('viewBoxName')\nreturn cls(domain_id, view_box_id, view_box_...
<|body_start_0|> self.domain_id = domain_id self.view_box_id = view_box_id self.view_box_name = view_box_name <|end_body_0|> <|body_start_1|> if dictionary is None: return None domain_id = dictionary.get('domainId') view_box_id = dictionary.get('viewBoxId') ...
Implementation of the 'CloudDomainList' model. CloudDomainList specfies the cloud domain information associated with the vault. Attributes: domain_id (long|int): Specifies the Id of the cloud domain. view_box_id (long|int): Specifies the Id of the ViewBox related to the cloud domain. view_box_name (string): Specifies t...
CloudDomainList
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CloudDomainList: """Implementation of the 'CloudDomainList' model. CloudDomainList specfies the cloud domain information associated with the vault. Attributes: domain_id (long|int): Specifies the Id of the cloud domain. view_box_id (long|int): Specifies the Id of the ViewBox related to the cloud ...
stack_v2_sparse_classes_36k_train_020474
1,966
permissive
[ { "docstring": "Constructor for the CloudDomainList class", "name": "__init__", "signature": "def __init__(self, domain_id=None, view_box_id=None, view_box_name=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representatio...
2
null
Implement the Python class `CloudDomainList` described below. Class description: Implementation of the 'CloudDomainList' model. CloudDomainList specfies the cloud domain information associated with the vault. Attributes: domain_id (long|int): Specifies the Id of the cloud domain. view_box_id (long|int): Specifies the ...
Implement the Python class `CloudDomainList` described below. Class description: Implementation of the 'CloudDomainList' model. CloudDomainList specfies the cloud domain information associated with the vault. Attributes: domain_id (long|int): Specifies the Id of the cloud domain. view_box_id (long|int): Specifies the ...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class CloudDomainList: """Implementation of the 'CloudDomainList' model. CloudDomainList specfies the cloud domain information associated with the vault. Attributes: domain_id (long|int): Specifies the Id of the cloud domain. view_box_id (long|int): Specifies the Id of the ViewBox related to the cloud ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CloudDomainList: """Implementation of the 'CloudDomainList' model. CloudDomainList specfies the cloud domain information associated with the vault. Attributes: domain_id (long|int): Specifies the Id of the cloud domain. view_box_id (long|int): Specifies the Id of the ViewBox related to the cloud domain. view_...
the_stack_v2_python_sparse
cohesity_management_sdk/models/cloud_domain_list.py
cohesity/management-sdk-python
train
24
b3e3dc7b4762f3e9cfb754075e2c7e87da584f02
[ "model.compile(optimizer=optimizer, loss=loss, metrics=metrics)\nself._model = model\nself._optimizer = optimizer\nself._loss = loss\nself._metrics = metrics\nif not pathlib.Path(str(out_dir)).is_dir():\n raise ValueError('Invalid output dir')\nself.out_dir = str(out_dir)\nself.tmp_dir = pathlib.Path(out_dir).jo...
<|body_start_0|> model.compile(optimizer=optimizer, loss=loss, metrics=metrics) self._model = model self._optimizer = optimizer self._loss = loss self._metrics = metrics if not pathlib.Path(str(out_dir)).is_dir(): raise ValueError('Invalid output dir') ...
KerasBaseTrainer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KerasBaseTrainer: def __init__(self, model: keras.Model, loss: keras.losses.Loss, optimizer: keras.optimizers.Optimizer, out_dir: str, metrics: keras.metrics.Metric=None): """Create a KerasBaseTrainner instance Args: model (keras.Model): the target model to be trained loss (keras.losses....
stack_v2_sparse_classes_36k_train_020475
4,536
no_license
[ { "docstring": "Create a KerasBaseTrainner instance Args: model (keras.Model): the target model to be trained loss (keras.losses.Loss): the loss to optimizer optimizer (keras.optimizers.Optimizer): the optimizer to use out_dir (str): the directory to store the trained model metrics (keras.metrics.Metric): The m...
2
stack_v2_sparse_classes_30k_train_014425
Implement the Python class `KerasBaseTrainer` described below. Class description: Implement the KerasBaseTrainer class. Method signatures and docstrings: - def __init__(self, model: keras.Model, loss: keras.losses.Loss, optimizer: keras.optimizers.Optimizer, out_dir: str, metrics: keras.metrics.Metric=None): Create a...
Implement the Python class `KerasBaseTrainer` described below. Class description: Implement the KerasBaseTrainer class. Method signatures and docstrings: - def __init__(self, model: keras.Model, loss: keras.losses.Loss, optimizer: keras.optimizers.Optimizer, out_dir: str, metrics: keras.metrics.Metric=None): Create a...
5da5317cedd380c244f20a96213e883d6ef29de2
<|skeleton|> class KerasBaseTrainer: def __init__(self, model: keras.Model, loss: keras.losses.Loss, optimizer: keras.optimizers.Optimizer, out_dir: str, metrics: keras.metrics.Metric=None): """Create a KerasBaseTrainner instance Args: model (keras.Model): the target model to be trained loss (keras.losses....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KerasBaseTrainer: def __init__(self, model: keras.Model, loss: keras.losses.Loss, optimizer: keras.optimizers.Optimizer, out_dir: str, metrics: keras.metrics.Metric=None): """Create a KerasBaseTrainner instance Args: model (keras.Model): the target model to be trained loss (keras.losses.Loss): the los...
the_stack_v2_python_sparse
Trainers/basetrainer.py
MingRuey/mlbox
train
2
cf47a5c55e7ad58a77c79bfc9b7911ca3185b42b
[ "super(FPN, self).__init__()\nself.inner_blocks = []\nself.layer_blocks = []\nself.asff = use_asff\nfor idx, in_channels in enumerate(in_channels_list, 1):\n inner_block = 'fpn_inner{}'.format(idx)\n layer_block = 'fpn_layer{}'.format(idx)\n if in_channels == 0:\n continue\n inner_block_module = ...
<|body_start_0|> super(FPN, self).__init__() self.inner_blocks = [] self.layer_blocks = [] self.asff = use_asff for idx, in_channels in enumerate(in_channels_list, 1): inner_block = 'fpn_inner{}'.format(idx) layer_block = 'fpn_layer{}'.format(idx) ...
Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive
FPN
[ "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference", "GPL-1.0-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FPN: """Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive""" def __init__(self, in_channels_list, out_channels, top_blocks=None, use_asff=False): """Arguments: in_channels_list (list...
stack_v2_sparse_classes_36k_train_020476
5,822
permissive
[ { "docstring": "Arguments: in_channels_list (list[int]): number of channels for each feature map that will be fed out_channels (int): number of channels of the FPN representation top_blocks (nn.Module or None): if provided, an extra operation will be performed on the output of the last (smallest resolution) FPN...
2
null
Implement the Python class `FPN` described below. Class description: Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive Method signatures and docstrings: - def __init__(self, in_channels_list, out_channels, top_blocks...
Implement the Python class `FPN` described below. Class description: Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive Method signatures and docstrings: - def __init__(self, in_channels_list, out_channels, top_blocks...
92acc188d3a0f634de58463b6676e70df83ef808
<|skeleton|> class FPN: """Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive""" def __init__(self, in_channels_list, out_channels, top_blocks=None, use_asff=False): """Arguments: in_channels_list (list...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FPN: """Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive""" def __init__(self, in_channels_list, out_channels, top_blocks=None, use_asff=False): """Arguments: in_channels_list (list[int]): numbe...
the_stack_v2_python_sparse
PyTorch/built-in/cv/detection/DAL_ID2732_for_PyTorch/models/fpn.py
Ascend/ModelZoo-PyTorch
train
23
fa2af28e286bf670d1e12dd7e26469bcd7ebe88d
[ "self.dim = dim\nself.y_pos = y_pos\nself.bars = bars\nself.speed = speed\nself.palette = palette\nself.sin = sin\nself.surface = pygame.Surface((dim[0], dim[1]), flags=pygame.SRCALPHA)\nbar_height = 10\nself.bar_surface = pygame.Surface((dim[0], bar_height), flags=pygame.SRCALPHA)\nfor index, degree in enumerate(r...
<|body_start_0|> self.dim = dim self.y_pos = y_pos self.bars = bars self.speed = speed self.palette = palette self.sin = sin self.surface = pygame.Surface((dim[0], dim[1]), flags=pygame.SRCALPHA) bar_height = 10 self.bar_surface = pygame.Surface((d...
some simple horizontal raster bar
HorizontalRasterBar
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HorizontalRasterBar: """some simple horizontal raster bar""" def __init__(self, dim: tuple, y_pos: int, bars: int=5, speed: int=2, palette: list=PALETTE, sin: list=SIN): """:param dim: dimensio of surface to draw on :param y_pos: central y position :param bars: how many bars to draw ...
stack_v2_sparse_classes_36k_train_020477
5,116
no_license
[ { "docstring": ":param dim: dimensio of surface to draw on :param y_pos: central y position :param bars: how many bars to draw :param speed: speed per frame, 1 euqal one pixel per frame :param palette: palette to use 256 colors :param sin: pre calculated sins for 360 degrees", "name": "__init__", "signa...
2
null
Implement the Python class `HorizontalRasterBar` described below. Class description: some simple horizontal raster bar Method signatures and docstrings: - def __init__(self, dim: tuple, y_pos: int, bars: int=5, speed: int=2, palette: list=PALETTE, sin: list=SIN): :param dim: dimensio of surface to draw on :param y_po...
Implement the Python class `HorizontalRasterBar` described below. Class description: some simple horizontal raster bar Method signatures and docstrings: - def __init__(self, dim: tuple, y_pos: int, bars: int=5, speed: int=2, palette: list=PALETTE, sin: list=SIN): :param dim: dimensio of surface to draw on :param y_po...
1fd421195a2888c0588a49f5a043a1110eedcdbf
<|skeleton|> class HorizontalRasterBar: """some simple horizontal raster bar""" def __init__(self, dim: tuple, y_pos: int, bars: int=5, speed: int=2, palette: list=PALETTE, sin: list=SIN): """:param dim: dimensio of surface to draw on :param y_pos: central y position :param bars: how many bars to draw ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HorizontalRasterBar: """some simple horizontal raster bar""" def __init__(self, dim: tuple, y_pos: int, bars: int=5, speed: int=2, palette: list=PALETTE, sin: list=SIN): """:param dim: dimensio of surface to draw on :param y_pos: central y position :param bars: how many bars to draw :param speed:...
the_stack_v2_python_sparse
effects/RasterBar.py
gunny26/pygame
train
5
90ab7761202af71f3e852efa8dbd0160d65c917d
[ "\"\"\"For Frequency Prescalar-0\"\"\"\nbus.write_byte_data(PCA9531_DEFAULT_ADDRESS, PCA9531_REG_PSC0, PCA9531_PSC0_USERDEFINED)\n'For Frequency Prescalar-1'\nbus.write_byte_data(PCA9531_DEFAULT_ADDRESS, PCA9531_REG_PSC1, PCA9531_PSC1_USERDEFINED)", "\"\"\"For PWM Register-0\"\"\"\nbus.write_byte_data(PCA9531_DEF...
<|body_start_0|> """For Frequency Prescalar-0""" bus.write_byte_data(PCA9531_DEFAULT_ADDRESS, PCA9531_REG_PSC0, PCA9531_PSC0_USERDEFINED) 'For Frequency Prescalar-1' bus.write_byte_data(PCA9531_DEFAULT_ADDRESS, PCA9531_REG_PSC1, PCA9531_PSC1_USERDEFINED) <|end_body_0|> <|body_start_1|> ...
PCA9531
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PCA9531: def set_frequency(self): """Select the Frequency Prescalar Configuration from the given provided value""" <|body_0|> def set_pulse_width(self): """Select the PWM Register Configuration from the given provided value""" <|body_1|> def set_led_sele...
stack_v2_sparse_classes_36k_train_020478
2,574
no_license
[ { "docstring": "Select the Frequency Prescalar Configuration from the given provided value", "name": "set_frequency", "signature": "def set_frequency(self)" }, { "docstring": "Select the PWM Register Configuration from the given provided value", "name": "set_pulse_width", "signature": "d...
3
stack_v2_sparse_classes_30k_train_012902
Implement the Python class `PCA9531` described below. Class description: Implement the PCA9531 class. Method signatures and docstrings: - def set_frequency(self): Select the Frequency Prescalar Configuration from the given provided value - def set_pulse_width(self): Select the PWM Register Configuration from the give...
Implement the Python class `PCA9531` described below. Class description: Implement the PCA9531 class. Method signatures and docstrings: - def set_frequency(self): Select the Frequency Prescalar Configuration from the given provided value - def set_pulse_width(self): Select the PWM Register Configuration from the give...
769c9ecc9171d65512e4cdca4c167872217a904a
<|skeleton|> class PCA9531: def set_frequency(self): """Select the Frequency Prescalar Configuration from the given provided value""" <|body_0|> def set_pulse_width(self): """Select the PWM Register Configuration from the given provided value""" <|body_1|> def set_led_sele...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PCA9531: def set_frequency(self): """Select the Frequency Prescalar Configuration from the given provided value""" """For Frequency Prescalar-0""" bus.write_byte_data(PCA9531_DEFAULT_ADDRESS, PCA9531_REG_PSC0, PCA9531_PSC0_USERDEFINED) 'For Frequency Prescalar-1' bus.wr...
the_stack_v2_python_sparse
PCA9530.py
ncdcommunity/PYTHON_LIBRARY
train
0
51bbbe92928c0a3bcf15ca2f5d1496bc5b86b743
[ "provider_wellknown = self._check_oidc_issuer_exists(kwargs['provider'])\nid_oidc_config = requests.get(provider_wellknown)\nuserinfo_url = id_oidc_config.json()['userinfo_endpoint']\nuserinfo = requests.get(userinfo_url, headers={'Authorization': 'Bearer ' + token})\nif userinfo.status_code != 200:\n raise APIE...
<|body_start_0|> provider_wellknown = self._check_oidc_issuer_exists(kwargs['provider']) id_oidc_config = requests.get(provider_wellknown) userinfo_url = id_oidc_config.json()['userinfo_endpoint'] userinfo = requests.get(userinfo_url, headers={'Authorization': 'Bearer ' + token}) ...
Token handler working on tokens from OIDC providers.
OidcTokenHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OidcTokenHandler: """Token handler working on tokens from OIDC providers.""" def verify_token(self, token: str, **kwargs: Any) -> Dict[str, Any]: """Verify OIDC token. Args: token: The OIDC authentication token (of type access-token) **kwargs: Auxiliary arguments key 'provider' needs...
stack_v2_sparse_classes_36k_train_020479
5,042
permissive
[ { "docstring": "Verify OIDC token. Args: token: The OIDC authentication token (of type access-token) **kwargs: Auxiliary arguments key 'provider' needs to be set: The used OIDC provider ID (must be supported by backend) Raises: :class:`~gateway.dependencies.APIException`: If the token is not valid. Returns: The...
2
null
Implement the Python class `OidcTokenHandler` described below. Class description: Token handler working on tokens from OIDC providers. Method signatures and docstrings: - def verify_token(self, token: str, **kwargs: Any) -> Dict[str, Any]: Verify OIDC token. Args: token: The OIDC authentication token (of type access-...
Implement the Python class `OidcTokenHandler` described below. Class description: Token handler working on tokens from OIDC providers. Method signatures and docstrings: - def verify_token(self, token: str, **kwargs: Any) -> Dict[str, Any]: Verify OIDC token. Args: token: The OIDC authentication token (of type access-...
822dbd3ccee25180cc48efd2f891504b6b5edc14
<|skeleton|> class OidcTokenHandler: """Token handler working on tokens from OIDC providers.""" def verify_token(self, token: str, **kwargs: Any) -> Dict[str, Any]: """Verify OIDC token. Args: token: The OIDC authentication token (of type access-token) **kwargs: Auxiliary arguments key 'provider' needs...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OidcTokenHandler: """Token handler working on tokens from OIDC providers.""" def verify_token(self, token: str, **kwargs: Any) -> Dict[str, Any]: """Verify OIDC token. Args: token: The OIDC authentication token (of type access-token) **kwargs: Auxiliary arguments key 'provider' needs to be set: T...
the_stack_v2_python_sparse
gateway/gateway/dependencies/token_handler.py
Open-EO/openeo-eodc-driver
train
3
10a539a6d8025d83108e6775aec7be13720dc64b
[ "sample = np.array(sample)\ndata = np.array(data)\nsample = [sample[sample[:, 0] == 0][:, 1:], sample[sample[:, 0] == 1][:, 1:]]\nn_e = sample[0].shape[0]\nn_c = sample[1].shape[0]\ndata = [data[:n_e].reshape((n_e, -1)), data[n_e:].reshape((n_c, -1))]\nself.model_c = Kriging(sample[1], data[1])\nidx_cross_doe = np....
<|body_start_0|> sample = np.array(sample) data = np.array(data) sample = [sample[sample[:, 0] == 0][:, 1:], sample[sample[:, 0] == 1][:, 1:]] n_e = sample[0].shape[0] n_c = sample[1].shape[0] data = [data[:n_e].reshape((n_e, -1)), data[n_e:].reshape((n_c, -1))] s...
Multifidelity algorithm using Evofusion.
Evofusion
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Evofusion: """Multifidelity algorithm using Evofusion.""" def __init__(self, sample, data): """Create the predictor. Data are arranged as decreasing fidelity. Hence, ``sample[0]`` corresponds to the highest fidelity. :param array_like sample: The sample used to generate the data. (fi...
stack_v2_sparse_classes_36k_train_020480
2,344
permissive
[ { "docstring": "Create the predictor. Data are arranged as decreasing fidelity. Hence, ``sample[0]`` corresponds to the highest fidelity. :param array_like sample: The sample used to generate the data. (fidelity, n_samples, n_features) :param array_like data: The observed data. (fidelity, n_samples, [n_features...
2
stack_v2_sparse_classes_30k_test_000519
Implement the Python class `Evofusion` described below. Class description: Multifidelity algorithm using Evofusion. Method signatures and docstrings: - def __init__(self, sample, data): Create the predictor. Data are arranged as decreasing fidelity. Hence, ``sample[0]`` corresponds to the highest fidelity. :param arr...
Implement the Python class `Evofusion` described below. Class description: Multifidelity algorithm using Evofusion. Method signatures and docstrings: - def __init__(self, sample, data): Create the predictor. Data are arranged as decreasing fidelity. Hence, ``sample[0]`` corresponds to the highest fidelity. :param arr...
559e1c4574865694e47f52bb202c560fc6252d2d
<|skeleton|> class Evofusion: """Multifidelity algorithm using Evofusion.""" def __init__(self, sample, data): """Create the predictor. Data are arranged as decreasing fidelity. Hence, ``sample[0]`` corresponds to the highest fidelity. :param array_like sample: The sample used to generate the data. (fi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Evofusion: """Multifidelity algorithm using Evofusion.""" def __init__(self, sample, data): """Create the predictor. Data are arranged as decreasing fidelity. Hence, ``sample[0]`` corresponds to the highest fidelity. :param array_like sample: The sample used to generate the data. (fidelity, n_sam...
the_stack_v2_python_sparse
batman/surrogate/multifidelity.py
tupui/batman
train
2
8b9dec243778e9ddb755b983bd518a3f9c168178
[ "DBFormatter.__init__(self, logger, dbinterface)\nself.create = {}\nself.constraints = {}\nself.inserts = {}\nself.indexes = {}", "for i in sorted(self.create.keys()):\n try:\n self.dbi.processData(self.create[i], conn=conn, transaction=transaction)\n except Exception as e:\n msg = WMEXCEPTION...
<|body_start_0|> DBFormatter.__init__(self, logger, dbinterface) self.create = {} self.constraints = {} self.inserts = {} self.indexes = {} <|end_body_0|> <|body_start_1|> for i in sorted(self.create.keys()): try: self.dbi.processData(self.cre...
_DBCreator_ Generic class for creating database tables.
DBCreator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DBCreator: """_DBCreator_ Generic class for creating database tables.""" def __init__(self, logger, dbinterface): """_init_ Call the constructor of the parent class and create empty dictionaries to hold table create statements, constraint statements and insert statements.""" ...
stack_v2_sparse_classes_36k_train_020481
3,666
permissive
[ { "docstring": "_init_ Call the constructor of the parent class and create empty dictionaries to hold table create statements, constraint statements and insert statements.", "name": "__init__", "signature": "def __init__(self, logger, dbinterface)" }, { "docstring": "_execute_ Generic method to ...
3
null
Implement the Python class `DBCreator` described below. Class description: _DBCreator_ Generic class for creating database tables. Method signatures and docstrings: - def __init__(self, logger, dbinterface): _init_ Call the constructor of the parent class and create empty dictionaries to hold table create statements,...
Implement the Python class `DBCreator` described below. Class description: _DBCreator_ Generic class for creating database tables. Method signatures and docstrings: - def __init__(self, logger, dbinterface): _init_ Call the constructor of the parent class and create empty dictionaries to hold table create statements,...
de110ccf6fc63ef5589b4e871ef4d51d5bce7a25
<|skeleton|> class DBCreator: """_DBCreator_ Generic class for creating database tables.""" def __init__(self, logger, dbinterface): """_init_ Call the constructor of the parent class and create empty dictionaries to hold table create statements, constraint statements and insert statements.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DBCreator: """_DBCreator_ Generic class for creating database tables.""" def __init__(self, logger, dbinterface): """_init_ Call the constructor of the parent class and create empty dictionaries to hold table create statements, constraint statements and insert statements.""" DBFormatter._...
the_stack_v2_python_sparse
src/python/WMCore/Database/DBCreator.py
vkuznet/WMCore
train
0
60351c5539a2c0347c18b9f37b9002f77e5524b1
[ "self.selector = selector\nself.K = ParallelMean(1)\nself.C = ParallelMean(2)\nself.count = 0\nself.input_m_is_weighted = input_m_is_weighted", "data = _DataWrapper(data, '')\nsel = self.selector(data, *args, **kwargs)\nw = data['weight']\nK = data['m']\ng1 = data['g1']\ng2 = data['g2']\nn = g1[sel].size\nself.co...
<|body_start_0|> self.selector = selector self.K = ParallelMean(1) self.C = ParallelMean(2) self.count = 0 self.input_m_is_weighted = input_m_is_weighted <|end_body_0|> <|body_start_1|> data = _DataWrapper(data, '') sel = self.selector(data, *args, **kwargs) ...
This class builds up the total calibration factors for lensfit-convention shears from each chunk of data it is given. Note here we derive the c-terms from the data (in constrast to averaging values derived from simulations and stored in the catalog.) At the end an MPI communicator can be supplied to collect together th...
LensfitCalculator
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LensfitCalculator: """This class builds up the total calibration factors for lensfit-convention shears from each chunk of data it is given. Note here we derive the c-terms from the data (in constrast to averaging values derived from simulations and stored in the catalog.) At the end an MPI commun...
stack_v2_sparse_classes_36k_train_020482
27,539
permissive
[ { "docstring": "Initialize the Calibrator using the function you will use to select objects. That function should take at least one argument, the chunk of data to select on. The selector can take further *args and **kwargs, passed in when adding data. Parameters ---------- selector: function Function that selec...
3
null
Implement the Python class `LensfitCalculator` described below. Class description: This class builds up the total calibration factors for lensfit-convention shears from each chunk of data it is given. Note here we derive the c-terms from the data (in constrast to averaging values derived from simulations and stored in...
Implement the Python class `LensfitCalculator` described below. Class description: This class builds up the total calibration factors for lensfit-convention shears from each chunk of data it is given. Note here we derive the c-terms from the data (in constrast to averaging values derived from simulations and stored in...
addbfbe6c4dc0df208ce4f7ba4cb0a7588a932e3
<|skeleton|> class LensfitCalculator: """This class builds up the total calibration factors for lensfit-convention shears from each chunk of data it is given. Note here we derive the c-terms from the data (in constrast to averaging values derived from simulations and stored in the catalog.) At the end an MPI commun...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LensfitCalculator: """This class builds up the total calibration factors for lensfit-convention shears from each chunk of data it is given. Note here we derive the c-terms from the data (in constrast to averaging values derived from simulations and stored in the catalog.) At the end an MPI communicator can be...
the_stack_v2_python_sparse
txpipe/utils/calibration_tools.py
LSSTDESC/TXPipe
train
17
7e77df16a663ed6ff725875b8d2746d7cd9ba258
[ "args = rejected_parser.parse_args()\npage = args['page']\nper_page = args['per_page']\nsort_by = args['sort_by']\nsort_order = args['order']\nif per_page > 100:\n per_page = 100\ndescending = sort_order == 'desc'\nif per_page > 100:\n per_page = 100\nstart = per_page * (page - 1)\nstop = start + per_page\nkw...
<|body_start_0|> args = rejected_parser.parse_args() page = args['page'] per_page = args['per_page'] sort_by = args['sort_by'] sort_order = args['order'] if per_page > 100: per_page = 100 descending = sort_order == 'desc' if per_page > 100: ...
Rejected
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Rejected: def get(self, session=None): """List all rejected entries""" <|body_0|> def delete(self, session=None): """Clears all rejected entries""" <|body_1|> <|end_skeleton|> <|body_start_0|> args = rejected_parser.parse_args() page = args[...
stack_v2_sparse_classes_36k_train_020483
5,092
permissive
[ { "docstring": "List all rejected entries", "name": "get", "signature": "def get(self, session=None)" }, { "docstring": "Clears all rejected entries", "name": "delete", "signature": "def delete(self, session=None)" } ]
2
stack_v2_sparse_classes_30k_train_007818
Implement the Python class `Rejected` described below. Class description: Implement the Rejected class. Method signatures and docstrings: - def get(self, session=None): List all rejected entries - def delete(self, session=None): Clears all rejected entries
Implement the Python class `Rejected` described below. Class description: Implement the Rejected class. Method signatures and docstrings: - def get(self, session=None): List all rejected entries - def delete(self, session=None): Clears all rejected entries <|skeleton|> class Rejected: def get(self, session=None...
ea95ff60041beaea9aacbc2d93549e3a6b981dc5
<|skeleton|> class Rejected: def get(self, session=None): """List all rejected entries""" <|body_0|> def delete(self, session=None): """Clears all rejected entries""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Rejected: def get(self, session=None): """List all rejected entries""" args = rejected_parser.parse_args() page = args['page'] per_page = args['per_page'] sort_by = args['sort_by'] sort_order = args['order'] if per_page > 100: per_page = 100 ...
the_stack_v2_python_sparse
flexget/components/rejected/api.py
BrutuZ/Flexget
train
1
e53249b91cdb40e0d5df0b434537893931fc2614
[ "tf.reset_default_graph()\ntf.set_random_seed(1908)\nself.logPath = logPath\nself.layerNum = len(size)\nself.size = size", "prevSize = self.input.shape[1].value\nprevOut = self.input\nsize = self.size\nlayer = 1\nfor currentSize in size[:-1]:\n weights = tf.Variable(tf.truncated_normal([prevSize, currentSize],...
<|body_start_0|> tf.reset_default_graph() tf.set_random_seed(1908) self.logPath = logPath self.layerNum = len(size) self.size = size <|end_body_0|> <|body_start_1|> prevSize = self.input.shape[1].value prevOut = self.input size = self.size layer =...
ANN
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ANN: def __init__(self, size, logPath): """创建一个神经网络""" <|body_0|> def defineANN(self): """定义神经网络的结构""" <|body_1|> def defineLoss(self): """定义神经网络的损失函数""" <|body_2|> def SGD(self, X, Y, learningRate, miniBatchFraction, epoch): ...
stack_v2_sparse_classes_36k_train_020484
4,178
permissive
[ { "docstring": "创建一个神经网络", "name": "__init__", "signature": "def __init__(self, size, logPath)" }, { "docstring": "定义神经网络的结构", "name": "defineANN", "signature": "def defineANN(self)" }, { "docstring": "定义神经网络的损失函数", "name": "defineLoss", "signature": "def defineLoss(self)...
6
null
Implement the Python class `ANN` described below. Class description: Implement the ANN class. Method signatures and docstrings: - def __init__(self, size, logPath): 创建一个神经网络 - def defineANN(self): 定义神经网络的结构 - def defineLoss(self): 定义神经网络的损失函数 - def SGD(self, X, Y, learningRate, miniBatchFraction, epoch): 使用随机梯度下降法训练模...
Implement the Python class `ANN` described below. Class description: Implement the ANN class. Method signatures and docstrings: - def __init__(self, size, logPath): 创建一个神经网络 - def defineANN(self): 定义神经网络的结构 - def defineLoss(self): 定义神经网络的损失函数 - def SGD(self, X, Y, learningRate, miniBatchFraction, epoch): 使用随机梯度下降法训练模...
38e239dcf0fbe4b98ca11534ff419af72417a272
<|skeleton|> class ANN: def __init__(self, size, logPath): """创建一个神经网络""" <|body_0|> def defineANN(self): """定义神经网络的结构""" <|body_1|> def defineLoss(self): """定义神经网络的损失函数""" <|body_2|> def SGD(self, X, Y, learningRate, miniBatchFraction, epoch): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ANN: def __init__(self, size, logPath): """创建一个神经网络""" tf.reset_default_graph() tf.set_random_seed(1908) self.logPath = logPath self.layerNum = len(size) self.size = size def defineANN(self): """定义神经网络的结构""" prevSize = self.input.shape[1].va...
the_stack_v2_python_sparse
ch12-ann/mlp.py
GaoX2015/intro_ds
train
0
e3109d9c413e5bac266b67ac773a6b4a42774e26
[ "ser_path = get_project_path() + '/nltk_libs/english.all.3class.distsim.crf.ser'\njar_path = get_project_path() + '/nltk_libs/stanford-ner-3.8.0.jar'\nself.st = StanfordNERTagger(ser_path, jar_path)", "cleaned_text = CleanComments.filter_special_characters(comment=text)\nwords = cleaned_text.strip().split()\ntags...
<|body_start_0|> ser_path = get_project_path() + '/nltk_libs/english.all.3class.distsim.crf.ser' jar_path = get_project_path() + '/nltk_libs/stanford-ner-3.8.0.jar' self.st = StanfordNERTagger(ser_path, jar_path) <|end_body_0|> <|body_start_1|> cleaned_text = CleanComments.filter_specia...
StfNERTagger
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StfNERTagger: def __init__(self): """Open client for Stanford NERTagger :return: protocol open""" <|body_0|> def identify_person_types(self, text: str) -> list: """Users Stanford NERTagger to identify person types. It cleans-up some unwanted chars to have better accu...
stack_v2_sparse_classes_36k_train_020485
1,218
permissive
[ { "docstring": "Open client for Stanford NERTagger :return: protocol open", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Users Stanford NERTagger to identify person types. It cleans-up some unwanted chars to have better accuracy :param text: text to identify types :re...
2
stack_v2_sparse_classes_30k_train_003110
Implement the Python class `StfNERTagger` described below. Class description: Implement the StfNERTagger class. Method signatures and docstrings: - def __init__(self): Open client for Stanford NERTagger :return: protocol open - def identify_person_types(self, text: str) -> list: Users Stanford NERTagger to identify p...
Implement the Python class `StfNERTagger` described below. Class description: Implement the StfNERTagger class. Method signatures and docstrings: - def __init__(self): Open client for Stanford NERTagger :return: protocol open - def identify_person_types(self, text: str) -> list: Users Stanford NERTagger to identify p...
c98eb8c483a05af938a2f6f49d8ea803f5711572
<|skeleton|> class StfNERTagger: def __init__(self): """Open client for Stanford NERTagger :return: protocol open""" <|body_0|> def identify_person_types(self, text: str) -> list: """Users Stanford NERTagger to identify person types. It cleans-up some unwanted chars to have better accu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StfNERTagger: def __init__(self): """Open client for Stanford NERTagger :return: protocol open""" ser_path = get_project_path() + '/nltk_libs/english.all.3class.distsim.crf.ser' jar_path = get_project_path() + '/nltk_libs/stanford-ner-3.8.0.jar' self.st = StanfordNERTagger(ser_...
the_stack_v2_python_sparse
engage-analytics/utils/stanford/ner_tagger.py
oliveriopt/mood-analytics
train
0
754ebe17a3dc9e867784fc8ddc336a10630ac4d6
[ "logger = logging.getLogger(__name__)\nlogger.debug('Retrieving Coinmarketcap tickers...')\nclient = coinmarketcap.Market()\nticker_resp = client.ticker(limit=500)\nreturn ticker_resp", "ticker_resp = self.get_ticker()\ncm_prices = {}\nfor coin in ticker_resp:\n cm_prices.update({coin['symbol']: coin['price_us...
<|body_start_0|> logger = logging.getLogger(__name__) logger.debug('Retrieving Coinmarketcap tickers...') client = coinmarketcap.Market() ticker_resp = client.ticker(limit=500) return ticker_resp <|end_body_0|> <|body_start_1|> ticker_resp = self.get_ticker() cm_...
wrapper class on top of coinmarketcap
Coinmarketcap
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Coinmarketcap: """wrapper class on top of coinmarketcap""" def get_ticker(self): """method to get coinmarketcap tickers Args: None Returns: ticker_resp: list of dict, each dict contains each coin's data e.g. [{'24h_volume_usd': '2119330000.0', 'available_supply': '96373480.0', 'cache...
stack_v2_sparse_classes_36k_train_020486
1,919
permissive
[ { "docstring": "method to get coinmarketcap tickers Args: None Returns: ticker_resp: list of dict, each dict contains each coin's data e.g. [{'24h_volume_usd': '2119330000.0', 'available_supply': '96373480.0', 'cached': False, 'id': 'ethereum', 'last_updated': '1513423457', 'market_cap_usd': '67667289797.0', 'm...
2
stack_v2_sparse_classes_30k_train_018862
Implement the Python class `Coinmarketcap` described below. Class description: wrapper class on top of coinmarketcap Method signatures and docstrings: - def get_ticker(self): method to get coinmarketcap tickers Args: None Returns: ticker_resp: list of dict, each dict contains each coin's data e.g. [{'24h_volume_usd':...
Implement the Python class `Coinmarketcap` described below. Class description: wrapper class on top of coinmarketcap Method signatures and docstrings: - def get_ticker(self): method to get coinmarketcap tickers Args: None Returns: ticker_resp: list of dict, each dict contains each coin's data e.g. [{'24h_volume_usd':...
2a38e2bfc1c068015b4cc603d52ee01266337363
<|skeleton|> class Coinmarketcap: """wrapper class on top of coinmarketcap""" def get_ticker(self): """method to get coinmarketcap tickers Args: None Returns: ticker_resp: list of dict, each dict contains each coin's data e.g. [{'24h_volume_usd': '2119330000.0', 'available_supply': '96373480.0', 'cache...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Coinmarketcap: """wrapper class on top of coinmarketcap""" def get_ticker(self): """method to get coinmarketcap tickers Args: None Returns: ticker_resp: list of dict, each dict contains each coin's data e.g. [{'24h_volume_usd': '2119330000.0', 'available_supply': '96373480.0', 'cached': False, 'i...
the_stack_v2_python_sparse
api/coinmarketcap.py
tingyao7798/crpyto-portfolio
train
1
02871a036f4dae2fa43418e8cf2cf5035d26335f
[ "super(SentimentClassifierElmanRNN, self).__init__()\nif pretrained_embedding_matrix is None:\n self.embeddings = nn.Embedding(embedding_dim=embedding_size, num_embeddings=num_embeddings, padding_idx=padding_idx)\nelse:\n pretrained_embedding_matrix = torch.from_numpy(pretrained_embedding_matrix).float()\n ...
<|body_start_0|> super(SentimentClassifierElmanRNN, self).__init__() if pretrained_embedding_matrix is None: self.embeddings = nn.Embedding(embedding_dim=embedding_size, num_embeddings=num_embeddings, padding_idx=padding_idx) else: pretrained_embedding_matrix = torch.from...
A RNN to extract feature representation and 2-layer multilayer perceptron to do the classification
SentimentClassifierElmanRNN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SentimentClassifierElmanRNN: """A RNN to extract feature representation and 2-layer multilayer perceptron to do the classification""" def __init__(self, embedding_size, num_embeddings, rnn_hidden_dim, output_dim, pretrained_embedding_matrix=None, padding_idx=0, batch_first=True): """...
stack_v2_sparse_classes_36k_train_020487
6,018
no_license
[ { "docstring": "Args: embedding_size (int): the size of the embedding vector num_embeddings (int): the number of words to embed rnn_hidden_dim (int): the size of the RNN's hidden state output_dim (int): the size of the prediction vector pretrained_embedding_matrix (numpy.array): previously trained word embeddin...
3
null
Implement the Python class `SentimentClassifierElmanRNN` described below. Class description: A RNN to extract feature representation and 2-layer multilayer perceptron to do the classification Method signatures and docstrings: - def __init__(self, embedding_size, num_embeddings, rnn_hidden_dim, output_dim, pretrained_...
Implement the Python class `SentimentClassifierElmanRNN` described below. Class description: A RNN to extract feature representation and 2-layer multilayer perceptron to do the classification Method signatures and docstrings: - def __init__(self, embedding_size, num_embeddings, rnn_hidden_dim, output_dim, pretrained_...
43a453a03060c2adf6bf16302d5138cfa77a30d1
<|skeleton|> class SentimentClassifierElmanRNN: """A RNN to extract feature representation and 2-layer multilayer perceptron to do the classification""" def __init__(self, embedding_size, num_embeddings, rnn_hidden_dim, output_dim, pretrained_embedding_matrix=None, padding_idx=0, batch_first=True): """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SentimentClassifierElmanRNN: """A RNN to extract feature representation and 2-layer multilayer perceptron to do the classification""" def __init__(self, embedding_size, num_embeddings, rnn_hidden_dim, output_dim, pretrained_embedding_matrix=None, padding_idx=0, batch_first=True): """Args: embeddi...
the_stack_v2_python_sparse
workshops/sentiment2020/Solution/ModelElmanRNN.py
Petlja/PSIML
train
17
7b28e7e044957305f0979dc8cbe2a06ec8c7f8c2
[ "self._hass = hass\nself._client = client\nself._config = config", "if not self._hass.config.is_allowed_path(path):\n _LOGGER.error('Path does not exist or is not allowed: %s', path)\n return\nparsed_url = urlparse(path)\nfilename = os.path.basename(parsed_url.path)\ntry:\n await self._client.files_uploa...
<|body_start_0|> self._hass = hass self._client = client self._config = config <|end_body_0|> <|body_start_1|> if not self._hass.config.is_allowed_path(path): _LOGGER.error('Path does not exist or is not allowed: %s', path) return parsed_url = urlparse(pa...
Define the Slack notification logic.
SlackNotificationService
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SlackNotificationService: """Define the Slack notification logic.""" def __init__(self, hass: HomeAssistant, client: WebClient, config: dict[str, str]) -> None: """Initialize.""" <|body_0|> async def _async_send_local_file_message(self, path: str, targets: list[str], mes...
stack_v2_sparse_classes_36k_train_020488
9,238
permissive
[ { "docstring": "Initialize.", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant, client: WebClient, config: dict[str, str]) -> None" }, { "docstring": "Upload a local file (with message) to Slack.", "name": "_async_send_local_file_message", "signature": "async def ...
5
null
Implement the Python class `SlackNotificationService` described below. Class description: Define the Slack notification logic. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, client: WebClient, config: dict[str, str]) -> None: Initialize. - async def _async_send_local_file_message(self, pa...
Implement the Python class `SlackNotificationService` described below. Class description: Define the Slack notification logic. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, client: WebClient, config: dict[str, str]) -> None: Initialize. - async def _async_send_local_file_message(self, pa...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class SlackNotificationService: """Define the Slack notification logic.""" def __init__(self, hass: HomeAssistant, client: WebClient, config: dict[str, str]) -> None: """Initialize.""" <|body_0|> async def _async_send_local_file_message(self, path: str, targets: list[str], mes...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SlackNotificationService: """Define the Slack notification logic.""" def __init__(self, hass: HomeAssistant, client: WebClient, config: dict[str, str]) -> None: """Initialize.""" self._hass = hass self._client = client self._config = config async def _async_send_local...
the_stack_v2_python_sparse
homeassistant/components/slack/notify.py
home-assistant/core
train
35,501
2f570fbd2246bf9fe154ba17abc8c1d82904d10d
[ "self.child_vec = child_vec\nself.device_id = device_id\nself.device_length = device_length\nself.stripe_size = stripe_size\nself.thin_pool_chunk_size = thin_pool_chunk_size\nself.mtype = mtype", "if dictionary is None:\n return None\nchild_vec = None\nif dictionary.get('childVec') != None:\n child_vec = li...
<|body_start_0|> self.child_vec = child_vec self.device_id = device_id self.device_length = device_length self.stripe_size = stripe_size self.thin_pool_chunk_size = thin_pool_chunk_size self.mtype = mtype <|end_body_0|> <|body_start_1|> if dictionary is None: ...
Implementation of the 'DeviceTree' model. A logical volume is built on a tree where leaves are the slices of partitions (PartitionSlice) defined below and intermediate nodes are assembled by combining nodes in some mode (linear layout, striped, mirrored, RAID etc). A DeviceTree is a block device formed by combining one...
DeviceTree
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeviceTree: """Implementation of the 'DeviceTree' model. A logical volume is built on a tree where leaves are the slices of partitions (PartitionSlice) defined below and intermediate nodes are assembled by combining nodes in some mode (linear layout, striped, mirrored, RAID etc). A DeviceTree is ...
stack_v2_sparse_classes_36k_train_020489
3,683
permissive
[ { "docstring": "Constructor for the DeviceTree class", "name": "__init__", "signature": "def __init__(self, child_vec=None, device_id=None, device_length=None, stripe_size=None, thin_pool_chunk_size=None, mtype=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: d...
2
null
Implement the Python class `DeviceTree` described below. Class description: Implementation of the 'DeviceTree' model. A logical volume is built on a tree where leaves are the slices of partitions (PartitionSlice) defined below and intermediate nodes are assembled by combining nodes in some mode (linear layout, striped...
Implement the Python class `DeviceTree` described below. Class description: Implementation of the 'DeviceTree' model. A logical volume is built on a tree where leaves are the slices of partitions (PartitionSlice) defined below and intermediate nodes are assembled by combining nodes in some mode (linear layout, striped...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class DeviceTree: """Implementation of the 'DeviceTree' model. A logical volume is built on a tree where leaves are the slices of partitions (PartitionSlice) defined below and intermediate nodes are assembled by combining nodes in some mode (linear layout, striped, mirrored, RAID etc). A DeviceTree is ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeviceTree: """Implementation of the 'DeviceTree' model. A logical volume is built on a tree where leaves are the slices of partitions (PartitionSlice) defined below and intermediate nodes are assembled by combining nodes in some mode (linear layout, striped, mirrored, RAID etc). A DeviceTree is a block devic...
the_stack_v2_python_sparse
cohesity_management_sdk/models/device_tree.py
cohesity/management-sdk-python
train
24
cd0bf1c726cb48b9a5f180f46a4b19ffdecd52bc
[ "super(MultiHeadAttention, self).__init__()\nself.dm = dm\nself.h = h\nself.depth = dm // h\nself.Wq = tf.keras.layers.Dense(dm)\nself.Wk = tf.keras.layers.Dense(dm)\nself.Wv = tf.keras.layers.Dense(dm)\nself.linear = tf.keras.layers.Dense(dm)", "batch_size = tf.shape(Q)[0]\nq = self.Wq(Q)\nk = self.Wk(K)\nv = se...
<|body_start_0|> super(MultiHeadAttention, self).__init__() self.dm = dm self.h = h self.depth = dm // h self.Wq = tf.keras.layers.Dense(dm) self.Wk = tf.keras.layers.Dense(dm) self.Wv = tf.keras.layers.Dense(dm) self.linear = tf.keras.layers.Dense(dm) <|e...
Perform multi head attention
MultiHeadAttention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiHeadAttention: """Perform multi head attention""" def __init__(self, dm, h): """initialization""" <|body_0|> def call(self, Q, K, V, mask): """call function""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(MultiHeadAttention, self).__i...
stack_v2_sparse_classes_36k_train_020490
1,358
no_license
[ { "docstring": "initialization", "name": "__init__", "signature": "def __init__(self, dm, h)" }, { "docstring": "call function", "name": "call", "signature": "def call(self, Q, K, V, mask)" } ]
2
stack_v2_sparse_classes_30k_train_019715
Implement the Python class `MultiHeadAttention` described below. Class description: Perform multi head attention Method signatures and docstrings: - def __init__(self, dm, h): initialization - def call(self, Q, K, V, mask): call function
Implement the Python class `MultiHeadAttention` described below. Class description: Perform multi head attention Method signatures and docstrings: - def __init__(self, dm, h): initialization - def call(self, Q, K, V, mask): call function <|skeleton|> class MultiHeadAttention: """Perform multi head attention""" ...
16dc37d1c6dc00a271053b60724c51763914029a
<|skeleton|> class MultiHeadAttention: """Perform multi head attention""" def __init__(self, dm, h): """initialization""" <|body_0|> def call(self, Q, K, V, mask): """call function""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiHeadAttention: """Perform multi head attention""" def __init__(self, dm, h): """initialization""" super(MultiHeadAttention, self).__init__() self.dm = dm self.h = h self.depth = dm // h self.Wq = tf.keras.layers.Dense(dm) self.Wk = tf.keras.lay...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/6-multihead_attention.py
jaycer95/holbertonschool-machine_learning
train
0
74fab9a531cb2a49dd4404f5fa3a50e8af9eb83f
[ "super().__init__(key, value)\nself.age = age\nself.freq = freq", "self.value = value\nself.age = 0\nself.freq += 1" ]
<|body_start_0|> super().__init__(key, value) self.age = age self.freq = freq <|end_body_0|> <|body_start_1|> self.value = value self.age = 0 self.freq += 1 <|end_body_1|>
Least Frequently Used Inherits from CacheItem
LFUCacheItem
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LFUCacheItem: """Least Frequently Used Inherits from CacheItem""" def __init__(self, key, value, age, freq): """Constructor""" <|body_0|> def updateItem(self, value): """Update a cache item""" <|body_1|> <|end_skeleton|> <|body_start_0|> super()...
stack_v2_sparse_classes_36k_train_020491
3,562
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, key, value, age, freq)" }, { "docstring": "Update a cache item", "name": "updateItem", "signature": "def updateItem(self, value)" } ]
2
stack_v2_sparse_classes_30k_train_001379
Implement the Python class `LFUCacheItem` described below. Class description: Least Frequently Used Inherits from CacheItem Method signatures and docstrings: - def __init__(self, key, value, age, freq): Constructor - def updateItem(self, value): Update a cache item
Implement the Python class `LFUCacheItem` described below. Class description: Least Frequently Used Inherits from CacheItem Method signatures and docstrings: - def __init__(self, key, value, age, freq): Constructor - def updateItem(self, value): Update a cache item <|skeleton|> class LFUCacheItem: """Least Frequ...
ece925eabc1d1e22055f1b4d3f052b571e1c4400
<|skeleton|> class LFUCacheItem: """Least Frequently Used Inherits from CacheItem""" def __init__(self, key, value, age, freq): """Constructor""" <|body_0|> def updateItem(self, value): """Update a cache item""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LFUCacheItem: """Least Frequently Used Inherits from CacheItem""" def __init__(self, key, value, age, freq): """Constructor""" super().__init__(key, value) self.age = age self.freq = freq def updateItem(self, value): """Update a cache item""" self.valu...
the_stack_v2_python_sparse
0x03-caching/100-lfu_cache.py
zacwoll/holbertonschool-web_back_end
train
0
a0554d2ddbd412dedde8bf2210634a9f14447df1
[ "pre = None\ncur = head\nwhile cur:\n tmp = cur.next\n cur.next = pre\n pre = cur\n cur = tmp\nreturn pre", "n_l1, n_l2 = (self.reverseList(l1), self.reverseList(l2))\ncarry = 0\ndummy = cur = ListNode(0)\nwhile n_l1 or n_l2:\n if not n_l1:\n val1 = 0\n else:\n val1 = n_l1.val\n ...
<|body_start_0|> pre = None cur = head while cur: tmp = cur.next cur.next = pre pre = cur cur = tmp return pre <|end_body_0|> <|body_start_1|> n_l1, n_l2 = (self.reverseList(l1), self.reverseList(l2)) carry = 0 dumm...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def addTwoNumbers(self, l1, l2): """:type l1: ListNode :type l2: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> pre = None ...
stack_v2_sparse_classes_36k_train_020492
1,941
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "reverseList", "signature": "def reverseList(self, head)" }, { "docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode", "name": "addTwoNumbers", "signature": "def addTwoNumbers(self, l1, l2)" } ]
2
stack_v2_sparse_classes_30k_test_000091
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList(self, head): :type head: ListNode :rtype: ListNode - def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList(self, head): :type head: ListNode :rtype: ListNode - def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode <|skeleton|> class S...
6e18c5d257840489cc3fb1079ae3804c743982a4
<|skeleton|> class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def addTwoNumbers(self, l1, l2): """:type l1: ListNode :type l2: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" pre = None cur = head while cur: tmp = cur.next cur.next = pre pre = cur cur = tmp return pre def addTwoNumbers(self, l1, l2): ...
the_stack_v2_python_sparse
剑指 Offer II 025. 链表中的两数相加.py
yangyuxiang1996/leetcode
train
0
32d598e58f8f82c3fbb964e0abfa66e118a9db9d
[ "self.assert_divisible_channels(out_channels, steps)\nblocks = []\nblocks.extend([STDCBlock(in_channels, out_channels, stride=stride, steps=steps, stdc_downsample_mode=stdc_downsample_mode), *[STDCBlock(out_channels, out_channels, stride=1, steps=steps, stdc_downsample_mode=stdc_downsample_mode) for _ in range(num_...
<|body_start_0|> self.assert_divisible_channels(out_channels, steps) blocks = [] blocks.extend([STDCBlock(in_channels, out_channels, stride=stride, steps=steps, stdc_downsample_mode=stdc_downsample_mode), *[STDCBlock(out_channels, out_channels, stride=1, steps=steps, stdc_downsample_mode=stdc_do...
STDC stage with STDCBlock as building block.
STDCStage
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class STDCStage: """STDC stage with STDCBlock as building block.""" def build_stage(self, in_channels: int, out_channels: int, stride: int, num_blocks: int, steps: int, stdc_downsample_mode: str, **kwargs): """:param steps: The total number of convs in this module, 1 conv 1x1 and (steps - ...
stack_v2_sparse_classes_36k_train_020493
13,292
permissive
[ { "docstring": ":param steps: The total number of convs in this module, 1 conv 1x1 and (steps - 1) conv3x3. :param stdc_downsample_mode: downsample mode in stdc block, supported `avg_pool` for average-pooling and `dw_conv` for depthwise-convolution. :return:", "name": "build_stage", "signature": "def bu...
2
null
Implement the Python class `STDCStage` described below. Class description: STDC stage with STDCBlock as building block. Method signatures and docstrings: - def build_stage(self, in_channels: int, out_channels: int, stride: int, num_blocks: int, steps: int, stdc_downsample_mode: str, **kwargs): :param steps: The total...
Implement the Python class `STDCStage` described below. Class description: STDC stage with STDCBlock as building block. Method signatures and docstrings: - def build_stage(self, in_channels: int, out_channels: int, stride: int, num_blocks: int, steps: int, stdc_downsample_mode: str, **kwargs): :param steps: The total...
7240726cf6425b53a26ed2faec03672f30fee6be
<|skeleton|> class STDCStage: """STDC stage with STDCBlock as building block.""" def build_stage(self, in_channels: int, out_channels: int, stride: int, num_blocks: int, steps: int, stdc_downsample_mode: str, **kwargs): """:param steps: The total number of convs in this module, 1 conv 1x1 and (steps - ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class STDCStage: """STDC stage with STDCBlock as building block.""" def build_stage(self, in_channels: int, out_channels: int, stride: int, num_blocks: int, steps: int, stdc_downsample_mode: str, **kwargs): """:param steps: The total number of convs in this module, 1 conv 1x1 and (steps - 1) conv3x3. :...
the_stack_v2_python_sparse
src/super_gradients/training/models/segmentation_models/unet/unet_encoder.py
Deci-AI/super-gradients
train
3,237
9230f03ce85eefc6084e7623f79f47360e3dedad
[ "threshold_diffs = np.diff(threshold_ranges)\nif any((diff < 1e-05 for diff in threshold_diffs)):\n raise ValueError('Plugin cannot distinguish between thresholds at {} {}'.format(threshold_ranges, threshold_units))\nself.threshold_ranges = threshold_ranges\nself.threshold_units = threshold_units", "thresh_coo...
<|body_start_0|> threshold_diffs = np.diff(threshold_ranges) if any((diff < 1e-05 for diff in threshold_diffs)): raise ValueError('Plugin cannot distinguish between thresholds at {} {}'.format(threshold_ranges, threshold_units)) self.threshold_ranges = threshold_ranges self.t...
Calculate the probability of occurrence between thresholds
OccurrenceBetweenThresholds
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OccurrenceBetweenThresholds: """Calculate the probability of occurrence between thresholds""" def __init__(self, threshold_ranges: List[List[float]], threshold_units: str) -> None: """Initialise the class. Threshold ranges must be specified in a unit that is NOT sensitive to differen...
stack_v2_sparse_classes_36k_train_020494
8,945
permissive
[ { "docstring": "Initialise the class. Threshold ranges must be specified in a unit that is NOT sensitive to differences at the 1e-5 (float32) precision level. Args: threshold_ranges: List of 2-item iterables specifying thresholds between which probabilities should be calculated threshold_units: Units in which t...
6
stack_v2_sparse_classes_30k_train_019877
Implement the Python class `OccurrenceBetweenThresholds` described below. Class description: Calculate the probability of occurrence between thresholds Method signatures and docstrings: - def __init__(self, threshold_ranges: List[List[float]], threshold_units: str) -> None: Initialise the class. Threshold ranges must...
Implement the Python class `OccurrenceBetweenThresholds` described below. Class description: Calculate the probability of occurrence between thresholds Method signatures and docstrings: - def __init__(self, threshold_ranges: List[List[float]], threshold_units: str) -> None: Initialise the class. Threshold ranges must...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class OccurrenceBetweenThresholds: """Calculate the probability of occurrence between thresholds""" def __init__(self, threshold_ranges: List[List[float]], threshold_units: str) -> None: """Initialise the class. Threshold ranges must be specified in a unit that is NOT sensitive to differen...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OccurrenceBetweenThresholds: """Calculate the probability of occurrence between thresholds""" def __init__(self, threshold_ranges: List[List[float]], threshold_units: str) -> None: """Initialise the class. Threshold ranges must be specified in a unit that is NOT sensitive to differences at the 1e...
the_stack_v2_python_sparse
improver/between_thresholds.py
metoppv/improver
train
101
9318ffbc8f7bf0945097c6001525212440b0dd75
[ "self.vals = defaultdict(set)\nself.max_val, self.min_val = (-float('inf'), float('inf'))\nself.keys = dict()", "if key in self.keys:\n self.keys[key] += 1\nelse:\n self.keys[key] = 1\nv = self.keys[key]\nself.vals[v].add(key)\nself.max_val = max(self.max_val, v)", "if key in self.keys:\n v = self.keys...
<|body_start_0|> self.vals = defaultdict(set) self.max_val, self.min_val = (-float('inf'), float('inf')) self.keys = dict() <|end_body_0|> <|body_start_1|> if key in self.keys: self.keys[key] += 1 else: self.keys[key] = 1 v = self.keys[key] ...
wrong answer
AllOne
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AllOne: """wrong answer""" def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key: str) -> None: """Inserts a new key <Key> with value 1. Or increments an existing key by 1.""" <|body_1|> def dec(self, key: str) -...
stack_v2_sparse_classes_36k_train_020495
13,920
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1.", "name": "inc", "signature": "def inc(self, key: str) -> None" }, { "docstrin...
5
null
Implement the Python class `AllOne` described below. Class description: wrong answer Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1. - def dec(self, key: str) -> No...
Implement the Python class `AllOne` described below. Class description: wrong answer Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1. - def dec(self, key: str) -> No...
f96a2273c6831a8035e1adacfa452f73c599ae16
<|skeleton|> class AllOne: """wrong answer""" def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key: str) -> None: """Inserts a new key <Key> with value 1. Or increments an existing key by 1.""" <|body_1|> def dec(self, key: str) -...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AllOne: """wrong answer""" def __init__(self): """Initialize your data structure here.""" self.vals = defaultdict(set) self.max_val, self.min_val = (-float('inf'), float('inf')) self.keys = dict() def inc(self, key: str) -> None: """Inserts a new key <Key> wit...
the_stack_v2_python_sparse
Python/432_AllOonDataStructure.py
here0009/LeetCode
train
1
04e76d99aa01f474b95896903f436e1b893e0276
[ "try:\n need = Need.objects.get(pk=pk)\n serializer = NeedSerializer(need, context={'request': request})\n return Response(serializer.data)\nexcept Exception as ex:\n return HttpResponseServerError(ex)", "needs = Need.objects.all()\nserializer = NeedSerializer(needs, many=True, context={'request': req...
<|body_start_0|> try: need = Need.objects.get(pk=pk) serializer = NeedSerializer(need, context={'request': request}) return Response(serializer.data) except Exception as ex: return HttpResponseServerError(ex) <|end_body_0|> <|body_start_1|> needs ...
Journey Needs
NeedsViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NeedsViewSet: """Journey Needs""" def retrieve(self, request, pk=None): """Handle GET requests for single need returns: Response -- JSON serialized need""" <|body_0|> def list(self, request): """Handle GET requests to get all needs Returns: Response -- JSON seria...
stack_v2_sparse_classes_36k_train_020496
2,729
no_license
[ { "docstring": "Handle GET requests for single need returns: Response -- JSON serialized need", "name": "retrieve", "signature": "def retrieve(self, request, pk=None)" }, { "docstring": "Handle GET requests to get all needs Returns: Response -- JSON serialized list of needs", "name": "list",...
5
stack_v2_sparse_classes_30k_train_018534
Implement the Python class `NeedsViewSet` described below. Class description: Journey Needs Method signatures and docstrings: - def retrieve(self, request, pk=None): Handle GET requests for single need returns: Response -- JSON serialized need - def list(self, request): Handle GET requests to get all needs Returns: R...
Implement the Python class `NeedsViewSet` described below. Class description: Journey Needs Method signatures and docstrings: - def retrieve(self, request, pk=None): Handle GET requests for single need returns: Response -- JSON serialized need - def list(self, request): Handle GET requests to get all needs Returns: R...
bd996853f6bd9a95d15115248300e6d801c0dc47
<|skeleton|> class NeedsViewSet: """Journey Needs""" def retrieve(self, request, pk=None): """Handle GET requests for single need returns: Response -- JSON serialized need""" <|body_0|> def list(self, request): """Handle GET requests to get all needs Returns: Response -- JSON seria...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NeedsViewSet: """Journey Needs""" def retrieve(self, request, pk=None): """Handle GET requests for single need returns: Response -- JSON serialized need""" try: need = Need.objects.get(pk=pk) serializer = NeedSerializer(need, context={'request': request}) ...
the_stack_v2_python_sparse
capstoneapi/views/need.py
jeaninebeckle/backend-capstone-api
train
0
9ecf5be9dab65c1850dee52e34715500c48ff671
[ "super(PointNetInstanceSeg, self).__init__()\nself.max_op = ms.ops.ArgMaxWithValue(axis=2, keep_dims=True)\nself.concat = ms.ops.Concat(1)\nself.wconv1 = WarpConv1d(n_channel, 64, kernel_size=1, BN=True, use_activity=True)\nself.wconv2 = WarpConv1d(64, 64, kernel_size=1, BN=True, use_activity=True)\nself.wconv3 = W...
<|body_start_0|> super(PointNetInstanceSeg, self).__init__() self.max_op = ms.ops.ArgMaxWithValue(axis=2, keep_dims=True) self.concat = ms.ops.Concat(1) self.wconv1 = WarpConv1d(n_channel, 64, kernel_size=1, BN=True, use_activity=True) self.wconv2 = WarpConv1d(64, 64, kernel_size...
PointNetInstanceSeg
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PointNetInstanceSeg: def __init__(self, n_classes=3, n_channel=4): """v1 3D Instance Segmentation PointNet @input: (B,C(4),N) @return: logits: [bs,n,2] :param n_classes:3""" <|body_0|> def construct(self, pts: ms.Tensor, one_hot_vec: ms.Tensor): """:param pts: [bs,4,...
stack_v2_sparse_classes_36k_train_020497
19,684
permissive
[ { "docstring": "v1 3D Instance Segmentation PointNet @input: (B,C(4),N) @return: logits: [bs,n,2] :param n_classes:3", "name": "__init__", "signature": "def __init__(self, n_classes=3, n_channel=4)" }, { "docstring": ":param pts: [bs,4,n]: x,y,z,intensity :return: logits: [bs,n,2],scores for bkg...
2
null
Implement the Python class `PointNetInstanceSeg` described below. Class description: Implement the PointNetInstanceSeg class. Method signatures and docstrings: - def __init__(self, n_classes=3, n_channel=4): v1 3D Instance Segmentation PointNet @input: (B,C(4),N) @return: logits: [bs,n,2] :param n_classes:3 - def con...
Implement the Python class `PointNetInstanceSeg` described below. Class description: Implement the PointNetInstanceSeg class. Method signatures and docstrings: - def __init__(self, n_classes=3, n_channel=4): v1 3D Instance Segmentation PointNet @input: (B,C(4),N) @return: logits: [bs,n,2] :param n_classes:3 - def con...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class PointNetInstanceSeg: def __init__(self, n_classes=3, n_channel=4): """v1 3D Instance Segmentation PointNet @input: (B,C(4),N) @return: logits: [bs,n,2] :param n_classes:3""" <|body_0|> def construct(self, pts: ms.Tensor, one_hot_vec: ms.Tensor): """:param pts: [bs,4,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PointNetInstanceSeg: def __init__(self, n_classes=3, n_channel=4): """v1 3D Instance Segmentation PointNet @input: (B,C(4),N) @return: logits: [bs,n,2] :param n_classes:3""" super(PointNetInstanceSeg, self).__init__() self.max_op = ms.ops.ArgMaxWithValue(axis=2, keep_dims=True) ...
the_stack_v2_python_sparse
research/cv/frustum-pointnet/src/frustum_pointnets_v1.py
mindspore-ai/models
train
301
e0817766a0d19fdfe180f923a6272bf25f8c1b8d
[ "calculated_n_qubits = count_qubits(qubit_operator)\nif n_qubits is None:\n n_qubits = calculated_n_qubits\nelif n_qubits < calculated_n_qubits:\n raise ValueError('Invalid number of qubits specified {} < {}.'.format(n_qubits, calculated_n_qubits))\nn_hilbert = 2 ** n_qubits\nsuper(LinearQubitOperator, self)....
<|body_start_0|> calculated_n_qubits = count_qubits(qubit_operator) if n_qubits is None: n_qubits = calculated_n_qubits elif n_qubits < calculated_n_qubits: raise ValueError('Invalid number of qubits specified {} < {}.'.format(n_qubits, calculated_n_qubits)) n_hil...
A LinearOperator implied from a QubitOperator. The idea is that a single i_th qubit operator, O_i, is a 2-by-2 matrix, to be applied on a vector of length n_hilbert / 2^i, performs permutations and/ or adds an extra factor for its first half and the second half, e.g. a `Z` operator keeps the first half unchanged, while...
LinearQubitOperator
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearQubitOperator: """A LinearOperator implied from a QubitOperator. The idea is that a single i_th qubit operator, O_i, is a 2-by-2 matrix, to be applied on a vector of length n_hilbert / 2^i, performs permutations and/ or adds an extra factor for its first half and the second half, e.g. a `Z`...
stack_v2_sparse_classes_36k_train_020498
8,329
permissive
[ { "docstring": "Args: qubit_operator(QubitOperator): A qubit operator to be applied on vectors. n_qubits(int): The total number of qubits", "name": "__init__", "signature": "def __init__(self, qubit_operator, n_qubits=None)" }, { "docstring": "Matrix-vector multiplication for the LinearQubitOper...
2
null
Implement the Python class `LinearQubitOperator` described below. Class description: A LinearOperator implied from a QubitOperator. The idea is that a single i_th qubit operator, O_i, is a 2-by-2 matrix, to be applied on a vector of length n_hilbert / 2^i, performs permutations and/ or adds an extra factor for its fir...
Implement the Python class `LinearQubitOperator` described below. Class description: A LinearOperator implied from a QubitOperator. The idea is that a single i_th qubit operator, O_i, is a 2-by-2 matrix, to be applied on a vector of length n_hilbert / 2^i, performs permutations and/ or adds an extra factor for its fir...
788481753c798a72c5cb3aa9f2aa9da3ce3190b0
<|skeleton|> class LinearQubitOperator: """A LinearOperator implied from a QubitOperator. The idea is that a single i_th qubit operator, O_i, is a 2-by-2 matrix, to be applied on a vector of length n_hilbert / 2^i, performs permutations and/ or adds an extra factor for its first half and the second half, e.g. a `Z`...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinearQubitOperator: """A LinearOperator implied from a QubitOperator. The idea is that a single i_th qubit operator, O_i, is a 2-by-2 matrix, to be applied on a vector of length n_hilbert / 2^i, performs permutations and/ or adds an extra factor for its first half and the second half, e.g. a `Z` operator kee...
the_stack_v2_python_sparse
src/openfermion/linalg/linear_qubit_operator.py
quantumlib/OpenFermion
train
1,481
de04a3db521d8a79e51769b52e648dc1ff464351
[ "t0 = time.time()\nres = self.bfs_optimized(n, 0)\nprint(time.time() - t0)\nreturn res", "queue = Queue()\nvisited = {}\nqueue.put((start, 0))\nvisited[start] = True\nwhile not queue.empty():\n node, step = queue.get()\n for i in range(1, int(math.sqrt(node)) + 1):\n new_node = node - i ** 2\n ...
<|body_start_0|> t0 = time.time() res = self.bfs_optimized(n, 0) print(time.time() - t0) return res <|end_body_0|> <|body_start_1|> queue = Queue() visited = {} queue.put((start, 0)) visited[start] = True while not queue.empty(): node,...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numSquares(self, n): """:type n: int :rtype: int""" <|body_0|> def bfs_optimized(self, start, end): """optimized bfs :param start: :param end: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> t0 = time.time() res = self...
stack_v2_sparse_classes_36k_train_020499
2,240
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "numSquares", "signature": "def numSquares(self, n)" }, { "docstring": "optimized bfs :param start: :param end: :return:", "name": "bfs_optimized", "signature": "def bfs_optimized(self, start, end)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numSquares(self, n): :type n: int :rtype: int - def bfs_optimized(self, start, end): optimized bfs :param start: :param end: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numSquares(self, n): :type n: int :rtype: int - def bfs_optimized(self, start, end): optimized bfs :param start: :param end: :return: <|skeleton|> class Solution: def n...
cf4235170db3629b65790fd0855a8a72ac5886f7
<|skeleton|> class Solution: def numSquares(self, n): """:type n: int :rtype: int""" <|body_0|> def bfs_optimized(self, start, end): """optimized bfs :param start: :param end: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def numSquares(self, n): """:type n: int :rtype: int""" t0 = time.time() res = self.bfs_optimized(n, 0) print(time.time() - t0) return res def bfs_optimized(self, start, end): """optimized bfs :param start: :param end: :return:""" queue = ...
the_stack_v2_python_sparse
perfect_squares_graph_tutorial.py
buxizhizhoum/leetcode
train
1