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
de657f6e41f4b3a2951491b151a73910da459499
[ "lo, hi = (max(nums), sum(nums))\nwhile lo < hi:\n mid = lo + (hi - lo) // 2\n cnt = 0\n curr = 0\n for num in nums:\n if curr + num <= mid:\n curr += num\n else:\n cnt += 1\n curr = num\n if cnt >= m:\n lo = mid + 1\n else:\n hi = mid\n...
<|body_start_0|> lo, hi = (max(nums), sum(nums)) while lo < hi: mid = lo + (hi - lo) // 2 cnt = 0 curr = 0 for num in nums: if curr + num <= mid: curr += num else: cnt += 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def splitArray1(self, nums: List[int], m: int) -> int: """binary search""" <|body_0|> def splitArray2(self, nums: List[int], m: int) -> int: """dynamic programming: define dp[i][j] as minimum largest subarray sum for splitting nums[0..j] in i parts time: O(...
stack_v2_sparse_classes_36k_train_012300
2,009
no_license
[ { "docstring": "binary search", "name": "splitArray1", "signature": "def splitArray1(self, nums: List[int], m: int) -> int" }, { "docstring": "dynamic programming: define dp[i][j] as minimum largest subarray sum for splitting nums[0..j] in i parts time: O(MN^2) space: O(MN)", "name": "splitA...
2
stack_v2_sparse_classes_30k_train_006065
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def splitArray1(self, nums: List[int], m: int) -> int: binary search - def splitArray2(self, nums: List[int], m: int) -> int: dynamic programming: define dp[i][j] as minimum larg...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def splitArray1(self, nums: List[int], m: int) -> int: binary search - def splitArray2(self, nums: List[int], m: int) -> int: dynamic programming: define dp[i][j] as minimum larg...
6ff1941ff213a843013100ac7033e2d4f90fbd6a
<|skeleton|> class Solution: def splitArray1(self, nums: List[int], m: int) -> int: """binary search""" <|body_0|> def splitArray2(self, nums: List[int], m: int) -> int: """dynamic programming: define dp[i][j] as minimum largest subarray sum for splitting nums[0..j] in i parts time: O(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def splitArray1(self, nums: List[int], m: int) -> int: """binary search""" lo, hi = (max(nums), sum(nums)) while lo < hi: mid = lo + (hi - lo) // 2 cnt = 0 curr = 0 for num in nums: if curr + num <= mid: ...
the_stack_v2_python_sparse
Leetcode 0410. Split Array Largest Sum.py
Chaoran-sjsu/leetcode
train
0
ba3a5f1c9813e9546e496c36725bcad3ed6aa44c
[ "self.cycletime = datetime(2017, 1, 10, 6)\ncube_uk_det = set_up_variable_cube(np.full((4, 4), 273.15, dtype=np.float32), time=self.cycletime, frt=datetime(2017, 1, 10, 3))\ntime_points = [1484038800, 1484046000, 1484053200]\ncube_uk_det = add_coordinate(cube_uk_det, time_points, 'time', dtype=np.int64, coord_units...
<|body_start_0|> self.cycletime = datetime(2017, 1, 10, 6) cube_uk_det = set_up_variable_cube(np.full((4, 4), 273.15, dtype=np.float32), time=self.cycletime, frt=datetime(2017, 1, 10, 3)) time_points = [1484038800, 1484046000, 1484053200] cube_uk_det = add_coordinate(cube_uk_det, time_po...
Test the unify_cycletime function.
Test_unify_cycletime
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_unify_cycletime: """Test the unify_cycletime function.""" def setUp(self): """Set up a UK deterministic cube for testing.""" <|body_0|> def test_cubelist_input(self): """Test when supplying a cubelist as input containing cubes representing UK deterministic a...
stack_v2_sparse_classes_36k_train_012301
20,564
permissive
[ { "docstring": "Set up a UK deterministic cube for testing.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test when supplying a cubelist as input containing cubes representing UK deterministic and UK ensemble model configuration and unifying the forecast_reference_time, so...
4
null
Implement the Python class `Test_unify_cycletime` described below. Class description: Test the unify_cycletime function. Method signatures and docstrings: - def setUp(self): Set up a UK deterministic cube for testing. - def test_cubelist_input(self): Test when supplying a cubelist as input containing cubes representi...
Implement the Python class `Test_unify_cycletime` described below. Class description: Test the unify_cycletime function. Method signatures and docstrings: - def setUp(self): Set up a UK deterministic cube for testing. - def test_cubelist_input(self): Test when supplying a cubelist as input containing cubes representi...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test_unify_cycletime: """Test the unify_cycletime function.""" def setUp(self): """Set up a UK deterministic cube for testing.""" <|body_0|> def test_cubelist_input(self): """Test when supplying a cubelist as input containing cubes representing UK deterministic a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test_unify_cycletime: """Test the unify_cycletime function.""" def setUp(self): """Set up a UK deterministic cube for testing.""" self.cycletime = datetime(2017, 1, 10, 6) cube_uk_det = set_up_variable_cube(np.full((4, 4), 273.15, dtype=np.float32), time=self.cycletime, frt=dateti...
the_stack_v2_python_sparse
improver_tests/metadata/test_forecast_times.py
metoppv/improver
train
101
e59a8db10ff05797345353182cb7d141482091ec
[ "self.explanation_type = explanation_type\nself._internal_obj = internal_obj\nself.feature_names = feature_names\nself.feature_types = feature_types\nself.name = name\nself.selector = selector", "if key is None:\n return self._internal_obj['overall']\nreturn None", "from ..visual.plot import plot_performance...
<|body_start_0|> self.explanation_type = explanation_type self._internal_obj = internal_obj self.feature_names = feature_names self.feature_types = feature_types self.name = name self.selector = selector <|end_body_0|> <|body_start_1|> if key is None: ...
Explanation object specific to ROC explainer.
ROCExplanation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ROCExplanation: """Explanation object specific to ROC explainer.""" def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): """Initializes class. Args: explanation_type: Type of explanation. internal_obj: A jsonable object...
stack_v2_sparse_classes_36k_train_012302
10,362
permissive
[ { "docstring": "Initializes class. Args: explanation_type: Type of explanation. internal_obj: A jsonable object that backs the explanation. feature_names: List of feature names. feature_types: List of feature types. name: User-defined name of explanation. selector: A dataframe whose indices correspond to explan...
3
stack_v2_sparse_classes_30k_train_004554
Implement the Python class `ROCExplanation` described below. Class description: Explanation object specific to ROC explainer. Method signatures and docstrings: - def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): Initializes class. Args: explanation_t...
Implement the Python class `ROCExplanation` described below. Class description: Explanation object specific to ROC explainer. Method signatures and docstrings: - def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): Initializes class. Args: explanation_t...
e6f38ea195aecbbd9d28c7183a83c65ada16e1ae
<|skeleton|> class ROCExplanation: """Explanation object specific to ROC explainer.""" def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): """Initializes class. Args: explanation_type: Type of explanation. internal_obj: A jsonable object...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ROCExplanation: """Explanation object specific to ROC explainer.""" def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): """Initializes class. Args: explanation_type: Type of explanation. internal_obj: A jsonable object that backs t...
the_stack_v2_python_sparse
python/interpret-core/interpret/perf/_curve.py
interpretml/interpret
train
3,731
db1d4a3da7a83ce12d74b4aaf8db23295dfee816
[ "super(Attention, self).__init__()\nassert kernel_size % 2 == 1, \"Kernel size should be odd for 'same' conv.\"\npadding = (kernel_size - 1) // 2\nself.conv = nn.Conv1d(1, 1, kernel_size, padding=padding)\nself.log_t = log_t", "pax = eh * dhx\npax = torch.sum(pax, dim=2)\nif ax is not None:\n ax = ax.unsqueeze...
<|body_start_0|> super(Attention, self).__init__() assert kernel_size % 2 == 1, "Kernel size should be odd for 'same' conv." padding = (kernel_size - 1) // 2 self.conv = nn.Conv1d(1, 1, kernel_size, padding=padding) self.log_t = log_t <|end_body_0|> <|body_start_1|> pax ...
Attention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Attention: def __init__(self, kernel_size=11, log_t=False): """Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' and 'location' based attention. The 'content' based attention is an inner product of the decoder hid...
stack_v2_sparse_classes_36k_train_012303
19,030
no_license
[ { "docstring": "Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' and 'location' based attention. The 'content' based attention is an inner product of the decoder hidden state with each time-step of the encoder state. The 'location' base...
2
stack_v2_sparse_classes_30k_train_002843
Implement the Python class `Attention` described below. Class description: Implement the Attention class. Method signatures and docstrings: - def __init__(self, kernel_size=11, log_t=False): Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' an...
Implement the Python class `Attention` described below. Class description: Implement the Attention class. Method signatures and docstrings: - def __init__(self, kernel_size=11, log_t=False): Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' an...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class Attention: def __init__(self, kernel_size=11, log_t=False): """Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' and 'location' based attention. The 'content' based attention is an inner product of the decoder hid...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Attention: def __init__(self, kernel_size=11, log_t=False): """Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' and 'location' based attention. The 'content' based attention is an inner product of the decoder hidden state with...
the_stack_v2_python_sparse
generated/test_awni_speech.py
jansel/pytorch-jit-paritybench
train
35
353a6ff0d796c054bc92a5c446de5b0439b6bfe8
[ "if 'querystring_parts' not in context:\n context['querystring_parts'] = {}\nreturn deepcopy(context['querystring_parts'])", "context = super(WithQueryStringViewMixin, self).get_context_data(**kwargs)\nqs = self.request.META.get('QUERY_STRING', '')\nqs_dict = parse_qs(qs)\nqs_parts = {}\nfor key, values in qs_...
<|body_start_0|> if 'querystring_parts' not in context: context['querystring_parts'] = {} return deepcopy(context['querystring_parts']) <|end_body_0|> <|body_start_1|> context = super(WithQueryStringViewMixin, self).get_context_data(**kwargs) qs = self.request.META.get('QUER...
WithQueryStringViewMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WithQueryStringViewMixin: def get_qs_parts(self, context): """Get the querystring parts from the context""" <|body_0|> def get_context_data(self, **kwargs): """By default, simply split the querystring in parts for use in other views, and put the parts and the whole q...
stack_v2_sparse_classes_36k_train_012304
15,489
no_license
[ { "docstring": "Get the querystring parts from the context", "name": "get_qs_parts", "signature": "def get_qs_parts(self, context)" }, { "docstring": "By default, simply split the querystring in parts for use in other views, and put the parts and the whole querystring in the context", "name"...
2
stack_v2_sparse_classes_30k_train_016279
Implement the Python class `WithQueryStringViewMixin` described below. Class description: Implement the WithQueryStringViewMixin class. Method signatures and docstrings: - def get_qs_parts(self, context): Get the querystring parts from the context - def get_context_data(self, **kwargs): By default, simply split the q...
Implement the Python class `WithQueryStringViewMixin` described below. Class description: Implement the WithQueryStringViewMixin class. Method signatures and docstrings: - def get_qs_parts(self, context): Get the querystring parts from the context - def get_context_data(self, **kwargs): By default, simply split the q...
63a405b993e77f10b9c2b6d9790aae7576d9d84f
<|skeleton|> class WithQueryStringViewMixin: def get_qs_parts(self, context): """Get the querystring parts from the context""" <|body_0|> def get_context_data(self, **kwargs): """By default, simply split the querystring in parts for use in other views, and put the parts and the whole q...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WithQueryStringViewMixin: def get_qs_parts(self, context): """Get the querystring parts from the context""" if 'querystring_parts' not in context: context['querystring_parts'] = {} return deepcopy(context['querystring_parts']) def get_context_data(self, **kwargs): ...
the_stack_v2_python_sparse
gim/front/mixins/views.py
derekey/github-issues-manager
train
1
b7cd1529e270beeb6207689743e8bead6b45fb25
[ "super().__init__(self.PROBLEM_NAME)\nself.root_node1 = root_node1\nself.root_node2 = root_node2", "print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nif self.root_node2 is None:\n return True\nif self.root_node2 is None:\n return True\nreturn self.are_identical(self.root_node1, self.root_node2) or ...
<|body_start_0|> super().__init__(self.PROBLEM_NAME) self.root_node1 = root_node1 self.root_node2 = root_node2 <|end_body_0|> <|body_start_1|> print('Solving {} problem ...'.format(self.PROBLEM_NAME)) if self.root_node2 is None: return True if self.root_node2...
Check Binary Tree Is Subtree
CheckBinaryTreeIsSubtree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CheckBinaryTreeIsSubtree: """Check Binary Tree Is Subtree""" def __init__(self, root_node1, root_node2): """CheckBinaryTreeIsSubtree Args: root_node1: node of the 1st tree root_node2: node of the 2nd tree Returns: None Raises: None""" <|body_0|> def solve(self): ...
stack_v2_sparse_classes_36k_train_012305
2,482
no_license
[ { "docstring": "CheckBinaryTreeIsSubtree Args: root_node1: node of the 1st tree root_node2: node of the 2nd tree Returns: None Raises: None", "name": "__init__", "signature": "def __init__(self, root_node1, root_node2)" }, { "docstring": "Solve the problem Note: O(nm) (runtime) solution recursiv...
3
null
Implement the Python class `CheckBinaryTreeIsSubtree` described below. Class description: Check Binary Tree Is Subtree Method signatures and docstrings: - def __init__(self, root_node1, root_node2): CheckBinaryTreeIsSubtree Args: root_node1: node of the 1st tree root_node2: node of the 2nd tree Returns: None Raises: ...
Implement the Python class `CheckBinaryTreeIsSubtree` described below. Class description: Check Binary Tree Is Subtree Method signatures and docstrings: - def __init__(self, root_node1, root_node2): CheckBinaryTreeIsSubtree Args: root_node1: node of the 1st tree root_node2: node of the 2nd tree Returns: None Raises: ...
11f4d25cb211740514c119a60962d075a0817abd
<|skeleton|> class CheckBinaryTreeIsSubtree: """Check Binary Tree Is Subtree""" def __init__(self, root_node1, root_node2): """CheckBinaryTreeIsSubtree Args: root_node1: node of the 1st tree root_node2: node of the 2nd tree Returns: None Raises: None""" <|body_0|> def solve(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CheckBinaryTreeIsSubtree: """Check Binary Tree Is Subtree""" def __init__(self, root_node1, root_node2): """CheckBinaryTreeIsSubtree Args: root_node1: node of the 1st tree root_node2: node of the 2nd tree Returns: None Raises: None""" super().__init__(self.PROBLEM_NAME) self.root_...
the_stack_v2_python_sparse
python/problems/binary_tree/check_binary_tree_is_subtree.py
santhosh-kumar/AlgorithmsAndDataStructures
train
2
1633e726570eb038def367dbda4bac4a1edbd892
[ "print('Loading weights: ', path)\nsuper(MidasNet, self).__init__()\nuse_pretrained = False if path is None else True\nself.pretrained, self.scratch = _make_encoder(backbone='resnext101_wsl', features=features, use_pretrained=use_pretrained)\nself.scratch.refinenet4 = FeatureFusionBlock(features)\nself.scratch.refi...
<|body_start_0|> print('Loading weights: ', path) super(MidasNet, self).__init__() use_pretrained = False if path is None else True self.pretrained, self.scratch = _make_encoder(backbone='resnext101_wsl', features=features, use_pretrained=use_pretrained) self.scratch.refinenet4 =...
Network for monocular depth estimation.
MidasNet
[ "MIT", "Apache-2.0", "Python-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MidasNet: """Network for monocular depth estimation.""" def __init__(self, path=None, features=256, non_negative=True): """Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional):...
stack_v2_sparse_classes_36k_train_012306
2,934
permissive
[ { "docstring": "Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encoder. Defaults to resnet50", "name": "__init__", "signature": "def __init__(self, path=None, features=...
2
stack_v2_sparse_classes_30k_train_018643
Implement the Python class `MidasNet` described below. Class description: Network for monocular depth estimation. Method signatures and docstrings: - def __init__(self, path=None, features=256, non_negative=True): Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Numbe...
Implement the Python class `MidasNet` described below. Class description: Network for monocular depth estimation. Method signatures and docstrings: - def __init__(self, path=None, features=256, non_negative=True): Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Numbe...
038fb5afe017b82334ad39a256531d2c4e9e1e1a
<|skeleton|> class MidasNet: """Network for monocular depth estimation.""" def __init__(self, path=None, features=256, non_negative=True): """Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MidasNet: """Network for monocular depth estimation.""" def __init__(self, path=None, features=256, non_negative=True): """Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone net...
the_stack_v2_python_sparse
15.PaddleGAN/PaddleGAN/ppgan/apps/midas/midas_net.py
yingshaoxo/ML
train
5
a1abb29738ddf87c9452c3724c7399dddc73aabf
[ "x, y = polar_cartesian(1, 0)\nself.assertEqual(x, 1)\nself.assertEqual(y, 0)\nx, y = polar_cartesian(1, math.pi / 2)\nself.assertEqual(round(x, 4), 0)\nself.assertEqual(round(y, 4), 1)\nx, y = polar_cartesian(1, math.pi)\nself.assertEqual(round(x, 4), -1)\nself.assertEqual(round(y, 4), 0)\nx, y = polar_cartesian(1...
<|body_start_0|> x, y = polar_cartesian(1, 0) self.assertEqual(x, 1) self.assertEqual(y, 0) x, y = polar_cartesian(1, math.pi / 2) self.assertEqual(round(x, 4), 0) self.assertEqual(round(y, 4), 1) x, y = polar_cartesian(1, math.pi) self.assertEqual(round(x...
Class to test module.
TestCoordinateConversion
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCoordinateConversion: """Class to test module.""" def test_polar_cartesian(self): """Test method for polar to cartesioan conversion.""" <|body_0|> def test_cartesian_polar(self): """Test method for cartesian to polar conversion.""" <|body_1|> <|end_s...
stack_v2_sparse_classes_36k_train_012307
3,712
no_license
[ { "docstring": "Test method for polar to cartesioan conversion.", "name": "test_polar_cartesian", "signature": "def test_polar_cartesian(self)" }, { "docstring": "Test method for cartesian to polar conversion.", "name": "test_cartesian_polar", "signature": "def test_cartesian_polar(self)...
2
null
Implement the Python class `TestCoordinateConversion` described below. Class description: Class to test module. Method signatures and docstrings: - def test_polar_cartesian(self): Test method for polar to cartesioan conversion. - def test_cartesian_polar(self): Test method for cartesian to polar conversion.
Implement the Python class `TestCoordinateConversion` described below. Class description: Class to test module. Method signatures and docstrings: - def test_polar_cartesian(self): Test method for polar to cartesioan conversion. - def test_cartesian_polar(self): Test method for cartesian to polar conversion. <|skelet...
848a3143e1f808d919a48b527637a96fe0aea47d
<|skeleton|> class TestCoordinateConversion: """Class to test module.""" def test_polar_cartesian(self): """Test method for polar to cartesioan conversion.""" <|body_0|> def test_cartesian_polar(self): """Test method for cartesian to polar conversion.""" <|body_1|> <|end_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestCoordinateConversion: """Class to test module.""" def test_polar_cartesian(self): """Test method for polar to cartesioan conversion.""" x, y = polar_cartesian(1, 0) self.assertEqual(x, 1) self.assertEqual(y, 0) x, y = polar_cartesian(1, math.pi / 2) sel...
the_stack_v2_python_sparse
blog/kode/part6/tools.py
christopheblomsen/ast2000
train
0
3ee4b072e1c54fc37139b7cc3c02b779dfe2248f
[ "super().__init__(coordinator=coordinator)\nself.entity_description = entity_description\nself.entity_id = f'{SENSOR_DOMAIN}.{entity_description.key}'\nself._attr_unique_id = f'{entry_id}_{entity_description.key}'\nself._attr_device_info = DeviceInfo(entry_type=DeviceEntryType.SERVICE, identifiers={(DOMAIN, entry_i...
<|body_start_0|> super().__init__(coordinator=coordinator) self.entity_description = entity_description self.entity_id = f'{SENSOR_DOMAIN}.{entity_description.key}' self._attr_unique_id = f'{entry_id}_{entity_description.key}' self._attr_device_info = DeviceInfo(entry_type=Device...
Defines a Forecast.Solar sensor.
ForecastSolarSensorEntity
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ForecastSolarSensorEntity: """Defines a Forecast.Solar sensor.""" def __init__(self, *, entry_id: str, coordinator: ForecastSolarDataUpdateCoordinator, entity_description: ForecastSolarSensorEntityDescription) -> None: """Initialize Forecast.Solar sensor.""" <|body_0|> d...
stack_v2_sparse_classes_36k_train_012308
7,317
permissive
[ { "docstring": "Initialize Forecast.Solar sensor.", "name": "__init__", "signature": "def __init__(self, *, entry_id: str, coordinator: ForecastSolarDataUpdateCoordinator, entity_description: ForecastSolarSensorEntityDescription) -> None" }, { "docstring": "Return the state of the sensor.", ...
2
stack_v2_sparse_classes_30k_train_012302
Implement the Python class `ForecastSolarSensorEntity` described below. Class description: Defines a Forecast.Solar sensor. Method signatures and docstrings: - def __init__(self, *, entry_id: str, coordinator: ForecastSolarDataUpdateCoordinator, entity_description: ForecastSolarSensorEntityDescription) -> None: Initi...
Implement the Python class `ForecastSolarSensorEntity` described below. Class description: Defines a Forecast.Solar sensor. Method signatures and docstrings: - def __init__(self, *, entry_id: str, coordinator: ForecastSolarDataUpdateCoordinator, entity_description: ForecastSolarSensorEntityDescription) -> None: Initi...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class ForecastSolarSensorEntity: """Defines a Forecast.Solar sensor.""" def __init__(self, *, entry_id: str, coordinator: ForecastSolarDataUpdateCoordinator, entity_description: ForecastSolarSensorEntityDescription) -> None: """Initialize Forecast.Solar sensor.""" <|body_0|> d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ForecastSolarSensorEntity: """Defines a Forecast.Solar sensor.""" def __init__(self, *, entry_id: str, coordinator: ForecastSolarDataUpdateCoordinator, entity_description: ForecastSolarSensorEntityDescription) -> None: """Initialize Forecast.Solar sensor.""" super().__init__(coordinator=c...
the_stack_v2_python_sparse
homeassistant/components/forecast_solar/sensor.py
home-assistant/core
train
35,501
56c71e68686c9e9c9d2f087a2752c95546385dff
[ "product_total_cost_price = TradeComplete.objects.filter(commission_buy_user_id_id=user_id, c_type=2, created_date__lte=the_date).aggregate(total=Coalesce(Sum('total'), 0.0))['total']\nsales_amount = TradeComplete.objects.filter(commission_sale_user_id_id=user_id, created_date__lte=the_date).aggregate(total=Coalesc...
<|body_start_0|> product_total_cost_price = TradeComplete.objects.filter(commission_buy_user_id_id=user_id, c_type=2, created_date__lte=the_date).aggregate(total=Coalesce(Sum('total'), 0.0))['total'] sales_amount = TradeComplete.objects.filter(commission_sale_user_id_id=user_id, created_date__lte=the_da...
AssetsUtil
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AssetsUtil: def get_profit_up_to_thd_day(user_id, the_date): """返回指定用户截至某天的累计收益 :param user_id: :param the_date:截至此日期 :return: 累计收益""" <|body_0|> def get_profit(user_id): """返回指定用户累计收益(截至昨天)、昨天收益 :param user_id: :return: (累计收益, 昨天收益)""" <|body_1|> def ge...
stack_v2_sparse_classes_36k_train_012309
5,250
no_license
[ { "docstring": "返回指定用户截至某天的累计收益 :param user_id: :param the_date:截至此日期 :return: 累计收益", "name": "get_profit_up_to_thd_day", "signature": "def get_profit_up_to_thd_day(user_id, the_date)" }, { "docstring": "返回指定用户累计收益(截至昨天)、昨天收益 :param user_id: :return: (累计收益, 昨天收益)", "name": "get_profit", ...
3
null
Implement the Python class `AssetsUtil` described below. Class description: Implement the AssetsUtil class. Method signatures and docstrings: - def get_profit_up_to_thd_day(user_id, the_date): 返回指定用户截至某天的累计收益 :param user_id: :param the_date:截至此日期 :return: 累计收益 - def get_profit(user_id): 返回指定用户累计收益(截至昨天)、昨天收益 :param u...
Implement the Python class `AssetsUtil` described below. Class description: Implement the AssetsUtil class. Method signatures and docstrings: - def get_profit_up_to_thd_day(user_id, the_date): 返回指定用户截至某天的累计收益 :param user_id: :param the_date:截至此日期 :return: 累计收益 - def get_profit(user_id): 返回指定用户累计收益(截至昨天)、昨天收益 :param u...
3d6198c2a1abc97fa9286408f52c1f5153883b7a
<|skeleton|> class AssetsUtil: def get_profit_up_to_thd_day(user_id, the_date): """返回指定用户截至某天的累计收益 :param user_id: :param the_date:截至此日期 :return: 累计收益""" <|body_0|> def get_profit(user_id): """返回指定用户累计收益(截至昨天)、昨天收益 :param user_id: :return: (累计收益, 昨天收益)""" <|body_1|> def ge...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AssetsUtil: def get_profit_up_to_thd_day(user_id, the_date): """返回指定用户截至某天的累计收益 :param user_id: :param the_date:截至此日期 :return: 累计收益""" product_total_cost_price = TradeComplete.objects.filter(commission_buy_user_id_id=user_id, c_type=2, created_date__lte=the_date).aggregate(total=Coalesce(Sum('...
the_stack_v2_python_sparse
stars/apps/customer/assets/utils.py
lisongwei15931/stars
train
0
04c56c2e9e61d645f540c027a4e0742fdc9093a6
[ "super().__init__(client, api_object_id=api_object_id, api_object_prefix=self.__API_OBJECT_PREFIX, retry_opts=retry_opts, cache_opts=cache_opts)\nself.description = None\nself.locked_by = None\nself.created = None\nself.management_ip = None\nself.memory_count = None\nself.cpu_topology = None\nself.ipmi_ip = None\ns...
<|body_start_0|> super().__init__(client, api_object_id=api_object_id, api_object_prefix=self.__API_OBJECT_PREFIX, retry_opts=retry_opts, cache_opts=cache_opts) self.description = None self.locked_by = None self.created = None self.management_ip = None self.memory_count =...
Veil node entity. Attributes: client: https_client instance. api_object_id: VeiL node id(uuid). cluster_id: VeiL cluster id(uuid) for extra filtering.
VeilNode
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VeilNode: """Veil node entity. Attributes: client: https_client instance. api_object_id: VeiL node id(uuid). cluster_id: VeiL cluster id(uuid) for extra filtering.""" def __init__(self, client, api_object_id: Optional[str]=None, cluster_id: Optional[str]=None, resource_pool_id: Optional[str]...
stack_v2_sparse_classes_36k_train_012310
2,870
permissive
[ { "docstring": "Please see help(VeilNode) for more info.", "name": "__init__", "signature": "def __init__(self, client, api_object_id: Optional[str]=None, cluster_id: Optional[str]=None, resource_pool_id: Optional[str]=None, retry_opts: Optional[VeilRetryConfiguration]=None, cache_opts: Optional[VeilCac...
4
stack_v2_sparse_classes_30k_train_009993
Implement the Python class `VeilNode` described below. Class description: Veil node entity. Attributes: client: https_client instance. api_object_id: VeiL node id(uuid). cluster_id: VeiL cluster id(uuid) for extra filtering. Method signatures and docstrings: - def __init__(self, client, api_object_id: Optional[str]=N...
Implement the Python class `VeilNode` described below. Class description: Veil node entity. Attributes: client: https_client instance. api_object_id: VeiL node id(uuid). cluster_id: VeiL cluster id(uuid) for extra filtering. Method signatures and docstrings: - def __init__(self, client, api_object_id: Optional[str]=N...
65c7adf3280217c9f9523a7dd7664d7d4d3f46fe
<|skeleton|> class VeilNode: """Veil node entity. Attributes: client: https_client instance. api_object_id: VeiL node id(uuid). cluster_id: VeiL cluster id(uuid) for extra filtering.""" def __init__(self, client, api_object_id: Optional[str]=None, cluster_id: Optional[str]=None, resource_pool_id: Optional[str]...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VeilNode: """Veil node entity. Attributes: client: https_client instance. api_object_id: VeiL node id(uuid). cluster_id: VeiL cluster id(uuid) for extra filtering.""" def __init__(self, client, api_object_id: Optional[str]=None, cluster_id: Optional[str]=None, resource_pool_id: Optional[str]=None, retry_...
the_stack_v2_python_sparse
veil_api_client/api_objects/node.py
devalv/veil-api-client
train
1
1c0665372e79a83ee7c08b36d35b7471595eecfd
[ "try:\n topic = topic_fetchers.get_topic_from_model(topic_model)\n topic.validate()\nexcept Exception as e:\n logging.exception(e)\n return result.Err((topic_id, e))\nreturn result.Ok((topic_id, topic))", "subtopic_version = topic_model.subtopic_schema_version\nif subtopic_version < feconf.CURRENT_SUB...
<|body_start_0|> try: topic = topic_fetchers.get_topic_from_model(topic_model) topic.validate() except Exception as e: logging.exception(e) return result.Err((topic_id, e)) return result.Ok((topic_id, topic)) <|end_body_0|> <|body_start_1|> ...
Transform that gets all Topic models, performs migration and filters any error results.
MigrateTopicModels
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MigrateTopicModels: """Transform that gets all Topic models, performs migration and filters any error results.""" def _migrate_topic(topic_id: str, topic_model: topic_models.TopicModel) -> result.Result[Tuple[str, topic_domain.Topic], Tuple[str, Exception]]: """Migrates topic and tra...
stack_v2_sparse_classes_36k_train_012311
13,939
permissive
[ { "docstring": "Migrates topic and transform topic model into topic object. Args: topic_id: str. The id of the topic. topic_model: TopicModel. The topic model to migrate. Returns: Result((str, Topic), (str, Exception)). Result containing tuple that consist of topic ID and either topic object or Exception. Topic...
3
null
Implement the Python class `MigrateTopicModels` described below. Class description: Transform that gets all Topic models, performs migration and filters any error results. Method signatures and docstrings: - def _migrate_topic(topic_id: str, topic_model: topic_models.TopicModel) -> result.Result[Tuple[str, topic_doma...
Implement the Python class `MigrateTopicModels` described below. Class description: Transform that gets all Topic models, performs migration and filters any error results. Method signatures and docstrings: - def _migrate_topic(topic_id: str, topic_model: topic_models.TopicModel) -> result.Result[Tuple[str, topic_doma...
d16fdf23d790eafd63812bd7239532256e30a21d
<|skeleton|> class MigrateTopicModels: """Transform that gets all Topic models, performs migration and filters any error results.""" def _migrate_topic(topic_id: str, topic_model: topic_models.TopicModel) -> result.Result[Tuple[str, topic_domain.Topic], Tuple[str, Exception]]: """Migrates topic and tra...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MigrateTopicModels: """Transform that gets all Topic models, performs migration and filters any error results.""" def _migrate_topic(topic_id: str, topic_model: topic_models.TopicModel) -> result.Result[Tuple[str, topic_domain.Topic], Tuple[str, Exception]]: """Migrates topic and transform topic ...
the_stack_v2_python_sparse
core/jobs/batch_jobs/topic_migration_jobs.py
oppia/oppia
train
6,172
c2c2fa39d93dae474258a44ec5daa0c3725a55ad
[ "self.amount = amount\nself.currency_code = currency_code\nself.formatted_price = formatted_price", "if dictionary is None:\n return None\nformatted_price = dictionary.get('FormattedPrice')\namount = dictionary.get('Amount')\ncurrency_code = dictionary.get('CurrencyCode')\nreturn cls(formatted_price, amount, c...
<|body_start_0|> self.amount = amount self.currency_code = currency_code self.formatted_price = formatted_price <|end_body_0|> <|body_start_1|> if dictionary is None: return None formatted_price = dictionary.get('FormattedPrice') amount = dictionary.get('Amou...
Implementation of the 'Price' model. TODO: type model description here. Attributes: amount (int): TODO: type description here. currency_code (string): TODO: type description here. formatted_price (string): TODO: type description here.
Price
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Price: """Implementation of the 'Price' model. TODO: type model description here. Attributes: amount (int): TODO: type description here. currency_code (string): TODO: type description here. formatted_price (string): TODO: type description here.""" def __init__(self, formatted_price=None, amo...
stack_v2_sparse_classes_36k_train_012312
1,870
permissive
[ { "docstring": "Constructor for the Price class", "name": "__init__", "signature": "def __init__(self, formatted_price=None, amount=None, currency_code=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the ...
2
stack_v2_sparse_classes_30k_test_000587
Implement the Python class `Price` described below. Class description: Implementation of the 'Price' model. TODO: type model description here. Attributes: amount (int): TODO: type description here. currency_code (string): TODO: type description here. formatted_price (string): TODO: type description here. Method signa...
Implement the Python class `Price` described below. Class description: Implementation of the 'Price' model. TODO: type model description here. Attributes: amount (int): TODO: type description here. currency_code (string): TODO: type description here. formatted_price (string): TODO: type description here. Method signa...
26ea1019115a1de3b1b37a4b830525e164ac55ce
<|skeleton|> class Price: """Implementation of the 'Price' model. TODO: type model description here. Attributes: amount (int): TODO: type description here. currency_code (string): TODO: type description here. formatted_price (string): TODO: type description here.""" def __init__(self, formatted_price=None, amo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Price: """Implementation of the 'Price' model. TODO: type model description here. Attributes: amount (int): TODO: type description here. currency_code (string): TODO: type description here. formatted_price (string): TODO: type description here.""" def __init__(self, formatted_price=None, amount=None, cur...
the_stack_v2_python_sparse
awsecommerceservice/models/price.py
nidaizamir/Test-PY
train
0
8f45220716cfdf9575c2221252cdea69b86ef8c6
[ "RAMSTKWorkView.__init__(self, controller, module='Function')\nself._lst_assess_labels[1].append(_(u'Total Mode Count:'))\nself._function_id = None\nself.txtModeCount = ramstk.RAMSTKEntry(width=125, editable=False, bold=True, tooltip=_(u'Displays the total number of failure modes associated with the selected Functi...
<|body_start_0|> RAMSTKWorkView.__init__(self, controller, module='Function') self._lst_assess_labels[1].append(_(u'Total Mode Count:')) self._function_id = None self.txtModeCount = ramstk.RAMSTKEntry(width=125, editable=False, bold=True, tooltip=_(u'Displays the total number of failure ...
Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_id: the ID of the Function currently being displayed.
AssessmentResults
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AssessmentResults: """Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_id: the ID of the Function currently bei...
stack_v2_sparse_classes_36k_train_012313
16,082
permissive
[ { "docstring": "Initialize the Work View for the Function package. :param controller: the RAMSTK master data controller instance. :type controller: :class:`ramstk.RAMSTK.RAMSTK`", "name": "__init__", "signature": "def __init__(self, controller, **kwargs)" }, { "docstring": "Load the Function Ass...
4
stack_v2_sparse_classes_30k_train_020263
Implement the Python class `AssessmentResults` described below. Class description: Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_i...
Implement the Python class `AssessmentResults` described below. Class description: Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_i...
488ffed8b842399ddcae93007de6c6f1dda23d05
<|skeleton|> class AssessmentResults: """Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_id: the ID of the Function currently bei...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AssessmentResults: """Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_id: the ID of the Function currently being displayed....
the_stack_v2_python_sparse
src/ramstk/gui/gtk/workviews/Function.py
JmiXIII/ramstk
train
0
c8dedbc240007f0f1b271698e2a85448f1f93533
[ "candidate = math.gcd(len(str1), len(str2))\nif str1 + str2 != str2 + str1:\n return ''\nreturn str1[:candidate]", "candidate = math.gcd(len(str1), len(str2))\nif len(str1) // candidate * str1[:candidate] == str1 and len(str2) // candidate * str1[:candidate] == str2:\n return str1[:candidate]\nreturn ''" ]
<|body_start_0|> candidate = math.gcd(len(str1), len(str2)) if str1 + str2 != str2 + str1: return '' return str1[:candidate] <|end_body_0|> <|body_start_1|> candidate = math.gcd(len(str1), len(str2)) if len(str1) // candidate * str1[:candidate] == str1 and len(str2) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: """执行用时 :40 ms, 在所有 Python3 提交中击败了44.21%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了7.48%的用户 数学法: 1、先计算出两个字符串最大公因子长度 2、如果两个字符串存在最大公因子T,str1=m*T,str2=n*T.必定满足str1 + str2 == str2 + str1 :param str1: :param str2: :return:""" <|...
stack_v2_sparse_classes_36k_train_012314
2,028
no_license
[ { "docstring": "执行用时 :40 ms, 在所有 Python3 提交中击败了44.21%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了7.48%的用户 数学法: 1、先计算出两个字符串最大公因子长度 2、如果两个字符串存在最大公因子T,str1=m*T,str2=n*T.必定满足str1 + str2 == str2 + str1 :param str1: :param str2: :return:", "name": "gcdOfStrings", "signature": "def gcdOfStrings(self, str1: str, str2:...
2
stack_v2_sparse_classes_30k_train_013023
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def gcdOfStrings(self, str1: str, str2: str) -> str: 执行用时 :40 ms, 在所有 Python3 提交中击败了44.21%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了7.48%的用户 数学法: 1、先计算出两个字符串最大公因子长度 2、如果两个字符串存在最大公因子T,...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def gcdOfStrings(self, str1: str, str2: str) -> str: 执行用时 :40 ms, 在所有 Python3 提交中击败了44.21%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了7.48%的用户 数学法: 1、先计算出两个字符串最大公因子长度 2、如果两个字符串存在最大公因子T,...
e43ee86c5a8cdb808da09b4b6138e10275abadb5
<|skeleton|> class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: """执行用时 :40 ms, 在所有 Python3 提交中击败了44.21%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了7.48%的用户 数学法: 1、先计算出两个字符串最大公因子长度 2、如果两个字符串存在最大公因子T,str1=m*T,str2=n*T.必定满足str1 + str2 == str2 + str1 :param str1: :param str2: :return:""" <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: """执行用时 :40 ms, 在所有 Python3 提交中击败了44.21%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了7.48%的用户 数学法: 1、先计算出两个字符串最大公因子长度 2、如果两个字符串存在最大公因子T,str1=m*T,str2=n*T.必定满足str1 + str2 == str2 + str1 :param str1: :param str2: :return:""" candidate = math...
the_stack_v2_python_sparse
LeetCode/1071. Greatest Common Divisor of Strings.py
yiming1012/MyLeetCode
train
2
1726098070ee974cf2eed92807f8c43476f44d65
[ "name_to_features = mention_encoder_task.MentionEncoderTask.get_name_to_features(config)\nif config.apply_answer_mask:\n name_to_features['dense_answer_mask'] = tf.io.FixedLenFeature(config.model_config.encoder_config.max_length, tf.int64)\nreturn name_to_features", "max_length = config.model_config.encoder_co...
<|body_start_0|> name_to_features = mention_encoder_task.MentionEncoderTask.get_name_to_features(config) if config.apply_answer_mask: name_to_features['dense_answer_mask'] = tf.io.FixedLenFeature(config.model_config.encoder_config.max_length, tf.int64) return name_to_features <|end_b...
Abstract class for all entity-answer question answering tasks.
EntityQATask
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EntityQATask: """Abstract class for all entity-answer question answering tasks.""" def get_name_to_features(config: ml_collections.ConfigDict) -> Dict[str, Any]: """Return feature dict for decoding purposes. See BaseTask.""" <|body_0|> def make_preprocess_fn(config: ml_c...
stack_v2_sparse_classes_36k_train_012315
5,499
permissive
[ { "docstring": "Return feature dict for decoding purposes. See BaseTask.", "name": "get_name_to_features", "signature": "def get_name_to_features(config: ml_collections.ConfigDict) -> Dict[str, Any]" }, { "docstring": "Produces function to preprocess samples. See BaseTask. During preprocessing w...
3
null
Implement the Python class `EntityQATask` described below. Class description: Abstract class for all entity-answer question answering tasks. Method signatures and docstrings: - def get_name_to_features(config: ml_collections.ConfigDict) -> Dict[str, Any]: Return feature dict for decoding purposes. See BaseTask. - def...
Implement the Python class `EntityQATask` described below. Class description: Abstract class for all entity-answer question answering tasks. Method signatures and docstrings: - def get_name_to_features(config: ml_collections.ConfigDict) -> Dict[str, Any]: Return feature dict for decoding purposes. See BaseTask. - def...
ac9447064195e06de48cc91ff642f7fffa28ffe8
<|skeleton|> class EntityQATask: """Abstract class for all entity-answer question answering tasks.""" def get_name_to_features(config: ml_collections.ConfigDict) -> Dict[str, Any]: """Return feature dict for decoding purposes. See BaseTask.""" <|body_0|> def make_preprocess_fn(config: ml_c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EntityQATask: """Abstract class for all entity-answer question answering tasks.""" def get_name_to_features(config: ml_collections.ConfigDict) -> Dict[str, Any]: """Return feature dict for decoding purposes. See BaseTask.""" name_to_features = mention_encoder_task.MentionEncoderTask.get_n...
the_stack_v2_python_sparse
language/mentionmemory/tasks/entity_qa_task.py
google-research/language
train
1,567
2c1a39263c8aabf0ed5134fc355ffb55a65dfce9
[ "log.trace('Getting the diff for users.')\nusers = await self.bot.api_client.get('bot/users')\ndb_users = {user_dict['id']: _User(roles=tuple(sorted(user_dict.pop('roles'))), **user_dict) for user_dict in users}\nguild_users = {member.id: _User(id=member.id, name=member.name, discriminator=int(member.discriminator)...
<|body_start_0|> log.trace('Getting the diff for users.') users = await self.bot.api_client.get('bot/users') db_users = {user_dict['id']: _User(roles=tuple(sorted(user_dict.pop('roles'))), **user_dict) for user_dict in users} guild_users = {member.id: _User(id=member.id, name=member.name...
Synchronise the database with users in the cache.
UserSyncer
[ "Python-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserSyncer: """Synchronise the database with users in the cache.""" async def _get_diff(self, guild: Guild) -> _Diff: """Return the difference of users between the cache of `guild` and the database.""" <|body_0|> async def _sync(self, diff: _Diff) -> None: """Syn...
stack_v2_sparse_classes_36k_train_012316
14,281
permissive
[ { "docstring": "Return the difference of users between the cache of `guild` and the database.", "name": "_get_diff", "signature": "async def _get_diff(self, guild: Guild) -> _Diff" }, { "docstring": "Synchronise the database with the user cache of `guild`.", "name": "_sync", "signature":...
2
null
Implement the Python class `UserSyncer` described below. Class description: Synchronise the database with users in the cache. Method signatures and docstrings: - async def _get_diff(self, guild: Guild) -> _Diff: Return the difference of users between the cache of `guild` and the database. - async def _sync(self, diff...
Implement the Python class `UserSyncer` described below. Class description: Synchronise the database with users in the cache. Method signatures and docstrings: - async def _get_diff(self, guild: Guild) -> _Diff: Return the difference of users between the cache of `guild` and the database. - async def _sync(self, diff...
232cc68b0a0ef210027beacb9b4f50ffeeaddd00
<|skeleton|> class UserSyncer: """Synchronise the database with users in the cache.""" async def _get_diff(self, guild: Guild) -> _Diff: """Return the difference of users between the cache of `guild` and the database.""" <|body_0|> async def _sync(self, diff: _Diff) -> None: """Syn...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserSyncer: """Synchronise the database with users in the cache.""" async def _get_diff(self, guild: Guild) -> _Diff: """Return the difference of users between the cache of `guild` and the database.""" log.trace('Getting the diff for users.') users = await self.bot.api_client.get(...
the_stack_v2_python_sparse
bot/cogs/sync/syncers.py
pormes/bot
train
2
5f179d2316f534c147804fae97e19d3704c0ea27
[ "if not self.created_date:\n self.created_date = datetime.utcnow()\nself.modified_date = datetime.utcnow()\nsuper(Message, self).save(*args, **kwargs)", "logging.info('getting %s %s for Message %s (%s)' % (asset_class, mime_type, self, self.pk))\nif isinstance(asset_class, AssetClass):\n return self.assets....
<|body_start_0|> if not self.created_date: self.created_date = datetime.utcnow() self.modified_date = datetime.utcnow() super(Message, self).save(*args, **kwargs) <|end_body_0|> <|body_start_1|> logging.info('getting %s %s for Message %s (%s)' % (asset_class, mime_type, self...
Message
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Message: def save(self, *args, **kwargs): """Overwriting save to set created_date and modified_date to utcnow() Django uses datetime.now() We want to store and transmit only UTC time, and localize it at rendering time""" <|body_0|> def get_asset(self, asset_class, mime_type)...
stack_v2_sparse_classes_36k_train_012317
23,088
no_license
[ { "docstring": "Overwriting save to set created_date and modified_date to utcnow() Django uses datetime.now() We want to store and transmit only UTC time, and localize it at rendering time", "name": "save", "signature": "def save(self, *args, **kwargs)" }, { "docstring": "Get an asset associated...
2
stack_v2_sparse_classes_30k_train_020643
Implement the Python class `Message` described below. Class description: Implement the Message class. Method signatures and docstrings: - def save(self, *args, **kwargs): Overwriting save to set created_date and modified_date to utcnow() Django uses datetime.now() We want to store and transmit only UTC time, and loca...
Implement the Python class `Message` described below. Class description: Implement the Message class. Method signatures and docstrings: - def save(self, *args, **kwargs): Overwriting save to set created_date and modified_date to utcnow() Django uses datetime.now() We want to store and transmit only UTC time, and loca...
e5a0d666ff11c812518cecb0f57257c64ca5cdfd
<|skeleton|> class Message: def save(self, *args, **kwargs): """Overwriting save to set created_date and modified_date to utcnow() Django uses datetime.now() We want to store and transmit only UTC time, and localize it at rendering time""" <|body_0|> def get_asset(self, asset_class, mime_type)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Message: def save(self, *args, **kwargs): """Overwriting save to set created_date and modified_date to utcnow() Django uses datetime.now() We want to store and transmit only UTC time, and localize it at rendering time""" if not self.created_date: self.created_date = datetime.utcnow...
the_stack_v2_python_sparse
donomo_archive/lib/donomo/archive/models.py
alexissmirnov/donomo
train
0
42eaa465a6e4d010e0e90eab0a216a3628419bba
[ "self.radius = radius\nself.max_neighbors = int(max_neighbors)\nself.step = step", "from pymatgen import Structure\ns = Structure.from_dict(struct)\nfeatures = self._get_structure_graph_features(s)\nfeatures = np.array(features)\nreturn features", "atom_features = np.array([site.specie.Z for site in struct], dt...
<|body_start_0|> self.radius = radius self.max_neighbors = int(max_neighbors) self.step = step <|end_body_0|> <|body_start_1|> from pymatgen import Structure s = Structure.from_dict(struct) features = self._get_structure_graph_features(s) features = np.array(feat...
Calculate structure graph features for crystals. Based on the implementation in Crystal Graph Convolutional Neural Networks (CGCNN). The method constructs a crystal graph representation including atom features (atomic numbers) and bond features (neighbor distances). Neighbors are determined by searching in a sphere aro...
StructureGraphFeaturizer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StructureGraphFeaturizer: """Calculate structure graph features for crystals. Based on the implementation in Crystal Graph Convolutional Neural Networks (CGCNN). The method constructs a crystal graph representation including atom features (atomic numbers) and bond features (neighbor distances). N...
stack_v2_sparse_classes_36k_train_012318
8,595
permissive
[ { "docstring": "Parameters ---------- radius : float (default 8.0) Radius of sphere for finding neighbors of atoms in unit cell. max_neighbors : int (default 12) Maximum number of neighbors to consider when constructing graph. step : float (default 0.2) Step size for Gaussian filter.", "name": "__init__", ...
4
stack_v2_sparse_classes_30k_train_007475
Implement the Python class `StructureGraphFeaturizer` described below. Class description: Calculate structure graph features for crystals. Based on the implementation in Crystal Graph Convolutional Neural Networks (CGCNN). The method constructs a crystal graph representation including atom features (atomic numbers) an...
Implement the Python class `StructureGraphFeaturizer` described below. Class description: Calculate structure graph features for crystals. Based on the implementation in Crystal Graph Convolutional Neural Networks (CGCNN). The method constructs a crystal graph representation including atom features (atomic numbers) an...
c9eaf1b64b6969cec692893288ca92439f9b6dda
<|skeleton|> class StructureGraphFeaturizer: """Calculate structure graph features for crystals. Based on the implementation in Crystal Graph Convolutional Neural Networks (CGCNN). The method constructs a crystal graph representation including atom features (atomic numbers) and bond features (neighbor distances). N...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StructureGraphFeaturizer: """Calculate structure graph features for crystals. Based on the implementation in Crystal Graph Convolutional Neural Networks (CGCNN). The method constructs a crystal graph representation including atom features (atomic numbers) and bond features (neighbor distances). Neighbors are ...
the_stack_v2_python_sparse
deepchem/feat/materials_featurizers.py
borisdayma/deepchem
train
1
f7bec886dda157a2574e0bcd9887e4fd6eb2662e
[ "field = model._meta.get_field(field_name)\nif isinstance(field, ForeignKey):\n fk_model = field.rel.to\n if fk_model.__name__ in FK_DISPLAY_FIELDS:\n report_field = FK_DISPLAY_FIELDS[fk_model.__name__]\n if fk_model == User:\n path = '%s__' % field_name\n else:\n pa...
<|body_start_0|> field = model._meta.get_field(field_name) if isinstance(field, ForeignKey): fk_model = field.rel.to if fk_model.__name__ in FK_DISPLAY_FIELDS: report_field = FK_DISPLAY_FIELDS[fk_model.__name__] if fk_model == User: ...
Command
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Command: def add_field_to_report(self, report, model, field_name, allow_recursion=True): """Adds the given field to the report. Includes logic to follow foreign keys in order to display their text value properly.""" <|body_0|> def add_display_fields_to_report(self, report, m...
stack_v2_sparse_classes_36k_train_012319
6,409
permissive
[ { "docstring": "Adds the given field to the report. Includes logic to follow foreign keys in order to display their text value properly.", "name": "add_field_to_report", "signature": "def add_field_to_report(self, report, model, field_name, allow_recursion=True)" }, { "docstring": "Adds all fiel...
4
stack_v2_sparse_classes_30k_train_017346
Implement the Python class `Command` described below. Class description: Implement the Command class. Method signatures and docstrings: - def add_field_to_report(self, report, model, field_name, allow_recursion=True): Adds the given field to the report. Includes logic to follow foreign keys in order to display their ...
Implement the Python class `Command` described below. Class description: Implement the Command class. Method signatures and docstrings: - def add_field_to_report(self, report, model, field_name, allow_recursion=True): Adds the given field to the report. Includes logic to follow foreign keys in order to display their ...
f0ed6ad723d70fae4737e517d4dca07b2aef176a
<|skeleton|> class Command: def add_field_to_report(self, report, model, field_name, allow_recursion=True): """Adds the given field to the report. Includes logic to follow foreign keys in order to display their text value properly.""" <|body_0|> def add_display_fields_to_report(self, report, m...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Command: def add_field_to_report(self, report, model, field_name, allow_recursion=True): """Adds the given field to the report. Includes logic to follow foreign keys in order to display their text value properly.""" field = model._meta.get_field(field_name) if isinstance(field, Foreign...
the_stack_v2_python_sparse
ovpr_atp/core/management/commands/set_up_reports.py
pawanacharya1979/Awdportal
train
0
220e44708c0c78b79b996070a4bcad6bf46a0164
[ "num = len(s)\nsum = 0\nfor i in range(num):\n chr = s[i]\n sum += (ord(chr) - 64) * pow(26, num - 1 - i)\nreturn sum", "sum = 0\nfor chr in list(s):\n x = ord(chr) - 64\n sum = sum * 26 + x\nreturn sum" ]
<|body_start_0|> num = len(s) sum = 0 for i in range(num): chr = s[i] sum += (ord(chr) - 64) * pow(26, num - 1 - i) return sum <|end_body_0|> <|body_start_1|> sum = 0 for chr in list(s): x = ord(chr) - 64 sum = sum * 26 + x...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def titleToNumber(self, s): """:type s: str :rtype: int""" <|body_0|> def titleToNumber2(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> num = len(s) sum = 0 for i in range(num): ...
stack_v2_sparse_classes_36k_train_012320
675
no_license
[ { "docstring": ":type s: str :rtype: int", "name": "titleToNumber", "signature": "def titleToNumber(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "titleToNumber2", "signature": "def titleToNumber2(self, s)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def titleToNumber(self, s): :type s: str :rtype: int - def titleToNumber2(self, s): :type s: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def titleToNumber(self, s): :type s: str :rtype: int - def titleToNumber2(self, s): :type s: str :rtype: int <|skeleton|> class Solution: def titleToNumber(self, s): ...
0fc4c7af59246e3064db41989a45d9db413a624b
<|skeleton|> class Solution: def titleToNumber(self, s): """:type s: str :rtype: int""" <|body_0|> def titleToNumber2(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def titleToNumber(self, s): """:type s: str :rtype: int""" num = len(s) sum = 0 for i in range(num): chr = s[i] sum += (ord(chr) - 64) * pow(26, num - 1 - i) return sum def titleToNumber2(self, s): """:type s: str :rtype: i...
the_stack_v2_python_sparse
171. Excel Sheet Column Number/sheet.py
Macielyoung/LeetCode
train
1
699b6d59a29ed093e53631af4003f3164b2a9a61
[ "super(MyConv2d, self).__init__()\nself.gpu = 'cuda:0'\nself.kernel = nn.Parameter(kernel, requires_grad=False)\nself.mode = mode\nself.stride = stride\nif padding == 0:\n size_padding = int((kernel[0, 0].size(0) - 1) / 2)\nelse:\n size_padding = padding\nif pad_type == 'replicate':\n self.padding = nn.Rep...
<|body_start_0|> super(MyConv2d, self).__init__() self.gpu = 'cuda:0' self.kernel = nn.Parameter(kernel, requires_grad=False) self.mode = mode self.stride = stride if padding == 0: size_padding = int((kernel[0, 0].size(0) - 1) / 2) else: si...
Performs circular convolution on images with a constant filter. Attributes ---------- kernel (torch.cuda.FloatTensor): size c*c*h*w filter mode (str): 'single' or 'batch' stride (int): dilation factor padding : instance of CircularPadding or torch.nn.ReplicationPad2d
MyConv2d
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyConv2d: """Performs circular convolution on images with a constant filter. Attributes ---------- kernel (torch.cuda.FloatTensor): size c*c*h*w filter mode (str): 'single' or 'batch' stride (int): dilation factor padding : instance of CircularPadding or torch.nn.ReplicationPad2d""" def __in...
stack_v2_sparse_classes_36k_train_012321
17,849
no_license
[ { "docstring": "Parameters ---------- gpu (str): gpu id kernel (torch.FloatTensor): convolution filter mode (str): indicates if the input is a single image of a batch of images pad_type (str): padding type (default is 'circular') padding (int): padding size (default is 0) stride (int): dilation factor (default ...
2
stack_v2_sparse_classes_30k_train_017751
Implement the Python class `MyConv2d` described below. Class description: Performs circular convolution on images with a constant filter. Attributes ---------- kernel (torch.cuda.FloatTensor): size c*c*h*w filter mode (str): 'single' or 'batch' stride (int): dilation factor padding : instance of CircularPadding or tor...
Implement the Python class `MyConv2d` described below. Class description: Performs circular convolution on images with a constant filter. Attributes ---------- kernel (torch.cuda.FloatTensor): size c*c*h*w filter mode (str): 'single' or 'batch' stride (int): dilation factor padding : instance of CircularPadding or tor...
6c4182add8135830c5e55e239b63cf65ee385ba8
<|skeleton|> class MyConv2d: """Performs circular convolution on images with a constant filter. Attributes ---------- kernel (torch.cuda.FloatTensor): size c*c*h*w filter mode (str): 'single' or 'batch' stride (int): dilation factor padding : instance of CircularPadding or torch.nn.ReplicationPad2d""" def __in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyConv2d: """Performs circular convolution on images with a constant filter. Attributes ---------- kernel (torch.cuda.FloatTensor): size c*c*h*w filter mode (str): 'single' or 'batch' stride (int): dilation factor padding : instance of CircularPadding or torch.nn.ReplicationPad2d""" def __init__(self, ke...
the_stack_v2_python_sparse
OLD/Copy/modules.py
ceciledellavalle/phd
train
1
ba2e6254bf560d2d9a1c38f9237a0e26b096551f
[ "ugrid_filename = os.path.join(PKG_PATH, 'converters', 'aflr', 'ugrid', 'models', 'two_blade_wake_sym_extended.surf')\nlog = SimpleLogger(level='warning')\ntest = SurfGui()\ntest.log = log\ntest.on_load_geometry(ugrid_filename, geometry_format='surf', raise_error=True)", "log = SimpleLogger(level='error')\nMODEL_...
<|body_start_0|> ugrid_filename = os.path.join(PKG_PATH, 'converters', 'aflr', 'ugrid', 'models', 'two_blade_wake_sym_extended.surf') log = SimpleLogger(level='warning') test = SurfGui() test.log = log test.on_load_geometry(ugrid_filename, geometry_format='surf', raise_error=True...
defines *.surf tests
TestSurfGui
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestSurfGui: """defines *.surf tests""" def test_surf_gui_01(self): """tests two_blade_wake_sym_extended.surf""" <|body_0|> def test_surf_01(self): """tests two_blade_wake_sym_extended.surf""" <|body_1|> <|end_skeleton|> <|body_start_0|> ugrid_f...
stack_v2_sparse_classes_36k_train_012322
4,370
no_license
[ { "docstring": "tests two_blade_wake_sym_extended.surf", "name": "test_surf_gui_01", "signature": "def test_surf_gui_01(self)" }, { "docstring": "tests two_blade_wake_sym_extended.surf", "name": "test_surf_01", "signature": "def test_surf_01(self)" } ]
2
null
Implement the Python class `TestSurfGui` described below. Class description: defines *.surf tests Method signatures and docstrings: - def test_surf_gui_01(self): tests two_blade_wake_sym_extended.surf - def test_surf_01(self): tests two_blade_wake_sym_extended.surf
Implement the Python class `TestSurfGui` described below. Class description: defines *.surf tests Method signatures and docstrings: - def test_surf_gui_01(self): tests two_blade_wake_sym_extended.surf - def test_surf_01(self): tests two_blade_wake_sym_extended.surf <|skeleton|> class TestSurfGui: """defines *.su...
cc596e637b53cf0a997f92e0e09f43222960052c
<|skeleton|> class TestSurfGui: """defines *.surf tests""" def test_surf_gui_01(self): """tests two_blade_wake_sym_extended.surf""" <|body_0|> def test_surf_01(self): """tests two_blade_wake_sym_extended.surf""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestSurfGui: """defines *.surf tests""" def test_surf_gui_01(self): """tests two_blade_wake_sym_extended.surf""" ugrid_filename = os.path.join(PKG_PATH, 'converters', 'aflr', 'ugrid', 'models', 'two_blade_wake_sym_extended.surf') log = SimpleLogger(level='warning') test = ...
the_stack_v2_python_sparse
pyNastran/converters/aflr/surf/test_surf_gui.py
lnderuiter/pyNastran
train
0
f85f4ce87c4a43d8679cf531f43382f6ba565849
[ "if len(nums) == 0:\n return 0\nlens_value_list = list()\nlens_value_list.append(nums[0])\nfor i in range(1, len(nums)):\n index_just_less = self.binary_search_just_less(lens_value_list, nums[i])\n if index_just_less + 1 > len(lens_value_list) - 1:\n lens_value_list.append(nums[i])\n elif lens_va...
<|body_start_0|> if len(nums) == 0: return 0 lens_value_list = list() lens_value_list.append(nums[0]) for i in range(1, len(nums)): index_just_less = self.binary_search_just_less(lens_value_list, nums[i]) if index_just_less + 1 > len(lens_value_list) -...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lengthOfLIS(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def binary_search_just_less(self, arr, target, begin=None, end=None): """找到arr中小于等于target的最大元素位置 :param arr: :param target: :param begin: :param end: :return:""" <|body_...
stack_v2_sparse_classes_36k_train_012323
1,717
permissive
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "lengthOfLIS", "signature": "def lengthOfLIS(self, nums)" }, { "docstring": "找到arr中小于等于target的最大元素位置 :param arr: :param target: :param begin: :param end: :return:", "name": "binary_search_just_less", "signature": "def binary_sea...
2
stack_v2_sparse_classes_30k_train_012026
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int - def binary_search_just_less(self, arr, target, begin=None, end=None): 找到arr中小于等于target的最大元素位置 :param arr: :param ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int - def binary_search_just_less(self, arr, target, begin=None, end=None): 找到arr中小于等于target的最大元素位置 :param arr: :param ...
6ddba1f3b86c40639a8203cbc3373d52301c1b1f
<|skeleton|> class Solution: def lengthOfLIS(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def binary_search_just_less(self, arr, target, begin=None, end=None): """找到arr中小于等于target的最大元素位置 :param arr: :param target: :param begin: :param end: :return:""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def lengthOfLIS(self, nums): """:type nums: List[int] :rtype: int""" if len(nums) == 0: return 0 lens_value_list = list() lens_value_list.append(nums[0]) for i in range(1, len(nums)): index_just_less = self.binary_search_just_less(lens_...
the_stack_v2_python_sparse
algorithms/python/leetcode/LongestIncreasingSubsequence.py
ytjia/leetcode
train
0
fe7ce80200d059705407185c30f706d57a15c7b0
[ "if num == 0:\n return [0]\nres = [0, 1]\nn = int(math.log2(num))\nfor i in range(0, n - 1):\n last = res[-2 ** i:]\n res.extend(last)\n res.extend([k + 1 for k in last])\nif len(res) < num + 1:\n last = res[-2 ** (n - 1):]\n last += [k + 1 for k in last]\n res += last[:num + 1 - len(res)]\nret...
<|body_start_0|> if num == 0: return [0] res = [0, 1] n = int(math.log2(num)) for i in range(0, n - 1): last = res[-2 ** i:] res.extend(last) res.extend([k + 1 for k in last]) if len(res) < num + 1: last = res[-2 ** (n -...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countBitsDP(self, num): """:type num: int :rtype: List[int]""" <|body_0|> def countBits(self, num): """:type num: int :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> if num == 0: return [0] res = [...
stack_v2_sparse_classes_36k_train_012324
1,640
no_license
[ { "docstring": ":type num: int :rtype: List[int]", "name": "countBitsDP", "signature": "def countBitsDP(self, num)" }, { "docstring": ":type num: int :rtype: List[int]", "name": "countBits", "signature": "def countBits(self, num)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countBitsDP(self, num): :type num: int :rtype: List[int] - def countBits(self, num): :type num: int :rtype: List[int]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countBitsDP(self, num): :type num: int :rtype: List[int] - def countBits(self, num): :type num: int :rtype: List[int] <|skeleton|> class Solution: def countBitsDP(self,...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def countBitsDP(self, num): """:type num: int :rtype: List[int]""" <|body_0|> def countBits(self, num): """:type num: int :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def countBitsDP(self, num): """:type num: int :rtype: List[int]""" if num == 0: return [0] res = [0, 1] n = int(math.log2(num)) for i in range(0, n - 1): last = res[-2 ** i:] res.extend(last) res.extend([k + 1 fo...
the_stack_v2_python_sparse
C/CountingBits.py
bssrdf/pyleet
train
2
47ccfa5b464a8d72d4507953373650945169f5ac
[ "if s == '':\n return ''\n\ndef isPalindrome(sub):\n m = len(sub)\n for i in range(m / 2):\n if sub[i] != sub[m - 1 - i]:\n return False\n return True\nres = ''\nn = len(s)\nfor i in range(n):\n for j in range(n, i, -1):\n if isPalindrome(s[i:j]):\n if j - i + 1 > ...
<|body_start_0|> if s == '': return '' def isPalindrome(sub): m = len(sub) for i in range(m / 2): if sub[i] != sub[m - 1 - i]: return False return True res = '' n = len(s) for i in range(n): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestPalindrome(self, s): """:type s: str :rtype: str""" <|body_0|> def longestPalindrome(self, s): """:type s: str :rtype: str""" <|body_1|> def longestPalindrome(self, s): """:type s: str :rtype: str""" <|body_2|> d...
stack_v2_sparse_classes_36k_train_012325
2,492
no_license
[ { "docstring": ":type s: str :rtype: str", "name": "longestPalindrome", "signature": "def longestPalindrome(self, s)" }, { "docstring": ":type s: str :rtype: str", "name": "longestPalindrome", "signature": "def longestPalindrome(self, s)" }, { "docstring": ":type s: str :rtype: s...
4
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestPalindrome(self, s): :type s: str :rtype: str - def longestPalindrome(self, s): :type s: str :rtype: str - def longestPalindrome(self, s): :type s: str :rtype: str - d...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestPalindrome(self, s): :type s: str :rtype: str - def longestPalindrome(self, s): :type s: str :rtype: str - def longestPalindrome(self, s): :type s: str :rtype: str - d...
a509b383a42f54313970168d9faa11f088f18708
<|skeleton|> class Solution: def longestPalindrome(self, s): """:type s: str :rtype: str""" <|body_0|> def longestPalindrome(self, s): """:type s: str :rtype: str""" <|body_1|> def longestPalindrome(self, s): """:type s: str :rtype: str""" <|body_2|> d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestPalindrome(self, s): """:type s: str :rtype: str""" if s == '': return '' def isPalindrome(sub): m = len(sub) for i in range(m / 2): if sub[i] != sub[m - 1 - i]: return False retur...
the_stack_v2_python_sparse
0005_Longest_Palindromic_Substring.py
bingli8802/leetcode
train
0
164c21ebb623bf1d6355dc5671e72e16d0149d7b
[ "self.mean = mean\nself.std = std\nself.norm_factor = norm_factor\nself.bias = bias\nself.preproc = Preproc(size, 0.6)\nself.size = size\nif pipeline is None:\n self.pipeline = None\nelse:\n self.pipeline = Compose(pipeline)", "if self.pipeline is not None:\n return {k: v for k, v in self.pipeline({'img'...
<|body_start_0|> self.mean = mean self.std = std self.norm_factor = norm_factor self.bias = bias self.preproc = Preproc(size, 0.6) self.size = size if pipeline is None: self.pipeline = None else: self.pipeline = Compose(pipeline) <|...
TrainAugmentation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TrainAugmentation: def __init__(self, pipeline, size, mean, std, norm_factor=255.0, bias=0.0): """Args: size: the size the of final image. mean: mean pixel value per channel.""" <|body_0|> def __call__(self, img, boxes, labels): """Args: img: the output of cv.imread ...
stack_v2_sparse_classes_36k_train_012326
2,877
permissive
[ { "docstring": "Args: size: the size the of final image. mean: mean pixel value per channel.", "name": "__init__", "signature": "def __init__(self, pipeline, size, mean, std, norm_factor=255.0, bias=0.0)" }, { "docstring": "Args: img: the output of cv.imread in RGB layout. boxes: boundding boxes...
2
stack_v2_sparse_classes_30k_train_007675
Implement the Python class `TrainAugmentation` described below. Class description: Implement the TrainAugmentation class. Method signatures and docstrings: - def __init__(self, pipeline, size, mean, std, norm_factor=255.0, bias=0.0): Args: size: the size the of final image. mean: mean pixel value per channel. - def _...
Implement the Python class `TrainAugmentation` described below. Class description: Implement the TrainAugmentation class. Method signatures and docstrings: - def __init__(self, pipeline, size, mean, std, norm_factor=255.0, bias=0.0): Args: size: the size the of final image. mean: mean pixel value per channel. - def _...
8a32196ce342b8ad9e3885895735d1286e25beba
<|skeleton|> class TrainAugmentation: def __init__(self, pipeline, size, mean, std, norm_factor=255.0, bias=0.0): """Args: size: the size the of final image. mean: mean pixel value per channel.""" <|body_0|> def __call__(self, img, boxes, labels): """Args: img: the output of cv.imread ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TrainAugmentation: def __init__(self, pipeline, size, mean, std, norm_factor=255.0, bias=0.0): """Args: size: the size the of final image. mean: mean pixel value per channel.""" self.mean = mean self.std = std self.norm_factor = norm_factor self.bias = bias self...
the_stack_v2_python_sparse
aw_nas/dataset/det_transform.py
blyucs/aw_nas
train
0
9b42a9cdebe9c8d70d467c6afe09e9f31d74560e
[ "self.continue_on_error = continue_on_error\nself.file_recovery_method = file_recovery_method\nself.filenames = filenames\nself.filter_ip_config = filter_ip_config\nself.is_file_based_volume_restore = is_file_based_volume_restore\nself.mount_disks_on_vm = mount_disks_on_vm\nself.name = name\nself.new_base_directory...
<|body_start_0|> self.continue_on_error = continue_on_error self.file_recovery_method = file_recovery_method self.filenames = filenames self.filter_ip_config = filter_ip_config self.is_file_based_volume_restore = is_file_based_volume_restore self.mount_disks_on_vm = mount...
Implementation of the 'RestoreFilesTaskRequest' model. Specifies information about a Restore Task that recovers files and folders. Attributes: continue_on_error (bool): Specifies if the Restore Task should continue even if the copy operation of some files and folders fails. If true, the Cohesity Cluster ignores intermi...
RestoreFilesTaskRequest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RestoreFilesTaskRequest: """Implementation of the 'RestoreFilesTaskRequest' model. Specifies information about a Restore Task that recovers files and folders. Attributes: continue_on_error (bool): Specifies if the Restore Task should continue even if the copy operation of some files and folders f...
stack_v2_sparse_classes_36k_train_012327
10,417
permissive
[ { "docstring": "Constructor for the RestoreFilesTaskRequest class", "name": "__init__", "signature": "def __init__(self, continue_on_error=None, file_recovery_method=None, filenames=None, filter_ip_config=None, is_file_based_volume_restore=None, mount_disks_on_vm=None, name=None, new_base_directory=None...
2
stack_v2_sparse_classes_30k_train_006689
Implement the Python class `RestoreFilesTaskRequest` described below. Class description: Implementation of the 'RestoreFilesTaskRequest' model. Specifies information about a Restore Task that recovers files and folders. Attributes: continue_on_error (bool): Specifies if the Restore Task should continue even if the cop...
Implement the Python class `RestoreFilesTaskRequest` described below. Class description: Implementation of the 'RestoreFilesTaskRequest' model. Specifies information about a Restore Task that recovers files and folders. Attributes: continue_on_error (bool): Specifies if the Restore Task should continue even if the cop...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class RestoreFilesTaskRequest: """Implementation of the 'RestoreFilesTaskRequest' model. Specifies information about a Restore Task that recovers files and folders. Attributes: continue_on_error (bool): Specifies if the Restore Task should continue even if the copy operation of some files and folders f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RestoreFilesTaskRequest: """Implementation of the 'RestoreFilesTaskRequest' model. Specifies information about a Restore Task that recovers files and folders. Attributes: continue_on_error (bool): Specifies if the Restore Task should continue even if the copy operation of some files and folders fails. If true...
the_stack_v2_python_sparse
cohesity_management_sdk/models/restore_files_task_request.py
cohesity/management-sdk-python
train
24
0a7e8b5836dd5b0956f3104b80ac4105992964e1
[ "if 'AVALON_TASK' in session:\n return True\nreturn False", "with pype.modified_environ(**session):\n print(self.name)\n app = lib.get_application(self.name)\n executable = lib.which(app['executable'])\n arguments = []\n tools_env = acre.get_tools([self.name])\n env = acre.compute(tools_env)\...
<|body_start_0|> if 'AVALON_TASK' in session: return True return False <|end_body_0|> <|body_start_1|> with pype.modified_environ(**session): print(self.name) app = lib.get_application(self.name) executable = lib.which(app['executable']) ...
Aport
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Aport: def is_compatible(self, session): """Return whether the action is compatible with the session""" <|body_0|> def process(self, session, **kwargs): """Implement the behavior for when the action is triggered Args: session (dict): environment dictionary Returns: P...
stack_v2_sparse_classes_36k_train_012328
1,606
permissive
[ { "docstring": "Return whether the action is compatible with the session", "name": "is_compatible", "signature": "def is_compatible(self, session)" }, { "docstring": "Implement the behavior for when the action is triggered Args: session (dict): environment dictionary Returns: Popen instance of n...
2
stack_v2_sparse_classes_30k_test_000468
Implement the Python class `Aport` described below. Class description: Implement the Aport class. Method signatures and docstrings: - def is_compatible(self, session): Return whether the action is compatible with the session - def process(self, session, **kwargs): Implement the behavior for when the action is trigger...
Implement the Python class `Aport` described below. Class description: Implement the Aport class. Method signatures and docstrings: - def is_compatible(self, session): Return whether the action is compatible with the session - def process(self, session, **kwargs): Implement the behavior for when the action is trigger...
47ef4b64f297186c6d929a8f56ecfb93dd0f44e8
<|skeleton|> class Aport: def is_compatible(self, session): """Return whether the action is compatible with the session""" <|body_0|> def process(self, session, **kwargs): """Implement the behavior for when the action is triggered Args: session (dict): environment dictionary Returns: P...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Aport: def is_compatible(self, session): """Return whether the action is compatible with the session""" if 'AVALON_TASK' in session: return True return False def process(self, session, **kwargs): """Implement the behavior for when the action is triggered Args: ...
the_stack_v2_python_sparse
pype/plugins/launcher/actions/Aport.py
jrsndl/pype
train
1
8ea4028e00ca0f7ee162c29ac0becc77d4069c33
[ "asteroidset = set()\nfor i, row in enumerate(inputmap.split('\\n')):\n for j, asteroid in enumerate(row):\n if asteroid == '#':\n asteroidset.add((j, i))\nself.asteroidset = asteroidset", "visibleangle = dict()\nxp, yp = position\nfor asteroid in self.asteroidset:\n if position == asteroi...
<|body_start_0|> asteroidset = set() for i, row in enumerate(inputmap.split('\n')): for j, asteroid in enumerate(row): if asteroid == '#': asteroidset.add((j, i)) self.asteroidset = asteroidset <|end_body_0|> <|body_start_1|> visibleangle ...
Asteroid map
AsteroidMap
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AsteroidMap: """Asteroid map""" def __init__(self, inputmap): """Turn an input map into a set of coordinates""" <|body_0|> def visiblefrom(self, position): """Finds all asteroids that are visible from a given position""" <|body_1|> def destroyasteroi...
stack_v2_sparse_classes_36k_train_012329
3,238
no_license
[ { "docstring": "Turn an input map into a set of coordinates", "name": "__init__", "signature": "def __init__(self, inputmap)" }, { "docstring": "Finds all asteroids that are visible from a given position", "name": "visiblefrom", "signature": "def visiblefrom(self, position)" }, { ...
4
stack_v2_sparse_classes_30k_train_020076
Implement the Python class `AsteroidMap` described below. Class description: Asteroid map Method signatures and docstrings: - def __init__(self, inputmap): Turn an input map into a set of coordinates - def visiblefrom(self, position): Finds all asteroids that are visible from a given position - def destroyasteroids(s...
Implement the Python class `AsteroidMap` described below. Class description: Asteroid map Method signatures and docstrings: - def __init__(self, inputmap): Turn an input map into a set of coordinates - def visiblefrom(self, position): Finds all asteroids that are visible from a given position - def destroyasteroids(s...
2ffc427f42332ca76813c0732e170ceaffadf6dc
<|skeleton|> class AsteroidMap: """Asteroid map""" def __init__(self, inputmap): """Turn an input map into a set of coordinates""" <|body_0|> def visiblefrom(self, position): """Finds all asteroids that are visible from a given position""" <|body_1|> def destroyasteroi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AsteroidMap: """Asteroid map""" def __init__(self, inputmap): """Turn an input map into a set of coordinates""" asteroidset = set() for i, row in enumerate(inputmap.split('\n')): for j, asteroid in enumerate(row): if asteroid == '#': ...
the_stack_v2_python_sparse
day10/day10.py
riccardosven/adventofcode2019
train
0
48b50c0e2b96caf223f4991ae64ae86248aac133
[ "for _ng in cls.WORD_LIST:\n m = re.search(_ng, text)\n if m:\n return True\nreturn False", "for _ng_word in cls.WORD_LIST:\n text = re.sub('%s' % _ng_word, '', text)\nreturn text" ]
<|body_start_0|> for _ng in cls.WORD_LIST: m = re.search(_ng, text) if m: return True return False <|end_body_0|> <|body_start_1|> for _ng_word in cls.WORD_LIST: text = re.sub('%s' % _ng_word, '', text) return text <|end_body_1|>
NGBase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NGBase: def check(cls, text): """マッチしたらTrue""" <|body_0|> def remove(cls, text): """textからNGワードを除外して返却""" <|body_1|> <|end_skeleton|> <|body_start_0|> for _ng in cls.WORD_LIST: m = re.search(_ng, text) if m: r...
stack_v2_sparse_classes_36k_train_012330
844
no_license
[ { "docstring": "マッチしたらTrue", "name": "check", "signature": "def check(cls, text)" }, { "docstring": "textからNGワードを除外して返却", "name": "remove", "signature": "def remove(cls, text)" } ]
2
null
Implement the Python class `NGBase` described below. Class description: Implement the NGBase class. Method signatures and docstrings: - def check(cls, text): マッチしたらTrue - def remove(cls, text): textからNGワードを除外して返却
Implement the Python class `NGBase` described below. Class description: Implement the NGBase class. Method signatures and docstrings: - def check(cls, text): マッチしたらTrue - def remove(cls, text): textからNGワードを除外して返却 <|skeleton|> class NGBase: def check(cls, text): """マッチしたらTrue""" <|body_0|> d...
eefd311c6f1edad483b89f9a513bcc2f9dfabe14
<|skeleton|> class NGBase: def check(cls, text): """マッチしたらTrue""" <|body_0|> def remove(cls, text): """textからNGワードを除外して返却""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NGBase: def check(cls, text): """マッチしたらTrue""" for _ng in cls.WORD_LIST: m = re.search(_ng, text) if m: return True return False def remove(cls, text): """textからNGワードを除外して返却""" for _ng_word in cls.WORD_LIST: text ...
the_stack_v2_python_sparse
anchovy/module/mecab/ng_word.py
arpsabbir/anchovy
train
0
6efa6c275d8c110a5c176c2ef483c601bc164466
[ "try:\n registry = oai_registry_api.get_all()\n serializer = serializers.RegistrySerializer(registry, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\nexcept Exception as e:\n content = OaiPmhMessage.get_message_labelled(str(e))\n return Response(content, status=status.HTTP_5...
<|body_start_0|> try: registry = oai_registry_api.get_all() serializer = serializers.RegistrySerializer(registry, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: content = OaiPmhMessage.get_message_labelled(str...
RegistryList
[ "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegistryList: def get(self, request): """Get all Registries (Data provider) Args: request: HTTP request Returns: - code: 200 content: List of Registries - code: 500 content: Internal server error""" <|body_0|> def post(self, request): """Create a Registry (Data provi...
stack_v2_sparse_classes_36k_train_012331
16,118
permissive
[ { "docstring": "Get all Registries (Data provider) Args: request: HTTP request Returns: - code: 200 content: List of Registries - code: 500 content: Internal server error", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Create a Registry (Data provider) Parameters: { \"u...
2
stack_v2_sparse_classes_30k_test_000595
Implement the Python class `RegistryList` described below. Class description: Implement the RegistryList class. Method signatures and docstrings: - def get(self, request): Get all Registries (Data provider) Args: request: HTTP request Returns: - code: 200 content: List of Registries - code: 500 content: Internal serv...
Implement the Python class `RegistryList` described below. Class description: Implement the RegistryList class. Method signatures and docstrings: - def get(self, request): Get all Registries (Data provider) Args: request: HTTP request Returns: - code: 200 content: List of Registries - code: 500 content: Internal serv...
e41fd9c5a75b51dc626995e753a5840f238a557d
<|skeleton|> class RegistryList: def get(self, request): """Get all Registries (Data provider) Args: request: HTTP request Returns: - code: 200 content: List of Registries - code: 500 content: Internal server error""" <|body_0|> def post(self, request): """Create a Registry (Data provi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RegistryList: def get(self, request): """Get all Registries (Data provider) Args: request: HTTP request Returns: - code: 200 content: List of Registries - code: 500 content: Internal server error""" try: registry = oai_registry_api.get_all() serializer = serializers.Reg...
the_stack_v2_python_sparse
core_oaipmh_harvester_app/rest/oai_registry/views.py
faical-yannick-congo/core_oaipmh_harvester_app
train
0
a8a148c64de5c00d6e3e3fb29f6fa235012c3aa1
[ "self.front = -1\nself.rare = -1\nself.max_size = 5\nself.queue = [0] * self.max_size", "if self.front == 0 and self.rare == self.max_size - 1 or self.front == self.rare + 1:\n print('Overflow')\nelse:\n if self.front == -1:\n self.front = 0\n self.rare = 0\n elif self.rare == self.max_size...
<|body_start_0|> self.front = -1 self.rare = -1 self.max_size = 5 self.queue = [0] * self.max_size <|end_body_0|> <|body_start_1|> if self.front == 0 and self.rare == self.max_size - 1 or self.front == self.rare + 1: print('Overflow') else: if sel...
This class contains functions for doubly ended queue.
deQueue
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class deQueue: """This class contains functions for doubly ended queue.""" def __init__(self): """Constructor function. Argument: self -- represents the object of the class.""" <|body_0|> def insert_rare(self, item): """This function inserts at the rare position. Argum...
stack_v2_sparse_classes_36k_train_012332
3,636
no_license
[ { "docstring": "Constructor function. Argument: self -- represents the object of the class.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "This function inserts at the rare position. Arguments: self -- represents the object of the class. item -- integer value, the val...
6
stack_v2_sparse_classes_30k_train_003763
Implement the Python class `deQueue` described below. Class description: This class contains functions for doubly ended queue. Method signatures and docstrings: - def __init__(self): Constructor function. Argument: self -- represents the object of the class. - def insert_rare(self, item): This function inserts at the...
Implement the Python class `deQueue` described below. Class description: This class contains functions for doubly ended queue. Method signatures and docstrings: - def __init__(self): Constructor function. Argument: self -- represents the object of the class. - def insert_rare(self, item): This function inserts at the...
6870426104aef417086788221dad29e887ddfe3f
<|skeleton|> class deQueue: """This class contains functions for doubly ended queue.""" def __init__(self): """Constructor function. Argument: self -- represents the object of the class.""" <|body_0|> def insert_rare(self, item): """This function inserts at the rare position. Argum...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class deQueue: """This class contains functions for doubly ended queue.""" def __init__(self): """Constructor function. Argument: self -- represents the object of the class.""" self.front = -1 self.rare = -1 self.max_size = 5 self.queue = [0] * self.max_size def ins...
the_stack_v2_python_sparse
Data Structure/03. Queue/03. Doubly Ended Queue/py_code.py
Slothfulwave612/Coding-Problems
train
5
002c469bd1ed9c15918a9194cb968ec187203d0b
[ "self.check_file(infile, need_seek)\nself.infile = infile\nself.closed = self.infile_closed = None\nself.inbuf = ''\nself.outbuf = array.array('c')\nself.eof = self.infile_eof = None", "if not hasattr(file, 'read'):\n raise TypeError('Basis file must have a read() method')\nif not hasattr(file, 'close'):\n ...
<|body_start_0|> self.check_file(infile, need_seek) self.infile = infile self.closed = self.infile_closed = None self.inbuf = '' self.outbuf = array.array('c') self.eof = self.infile_eof = None <|end_body_0|> <|body_start_1|> if not hasattr(file, 'read'): ...
File-like object used by SigFile, DeltaFile, and PatchFile
LikeFile
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LikeFile: """File-like object used by SigFile, DeltaFile, and PatchFile""" def __init__(self, infile, need_seek=None): """LikeFile initializer - zero buffers, set eofs off""" <|body_0|> def check_file(self, file, need_seek=None): """Raise type error if file doesn...
stack_v2_sparse_classes_36k_train_012333
8,383
no_license
[ { "docstring": "LikeFile initializer - zero buffers, set eofs off", "name": "__init__", "signature": "def __init__(self, infile, need_seek=None)" }, { "docstring": "Raise type error if file doesn't have necessary attributes", "name": "check_file", "signature": "def check_file(self, file,...
6
stack_v2_sparse_classes_30k_train_000163
Implement the Python class `LikeFile` described below. Class description: File-like object used by SigFile, DeltaFile, and PatchFile Method signatures and docstrings: - def __init__(self, infile, need_seek=None): LikeFile initializer - zero buffers, set eofs off - def check_file(self, file, need_seek=None): Raise typ...
Implement the Python class `LikeFile` described below. Class description: File-like object used by SigFile, DeltaFile, and PatchFile Method signatures and docstrings: - def __init__(self, infile, need_seek=None): LikeFile initializer - zero buffers, set eofs off - def check_file(self, file, need_seek=None): Raise typ...
ef6d0f4bdff52be379784325e504de22cfe149de
<|skeleton|> class LikeFile: """File-like object used by SigFile, DeltaFile, and PatchFile""" def __init__(self, infile, need_seek=None): """LikeFile initializer - zero buffers, set eofs off""" <|body_0|> def check_file(self, file, need_seek=None): """Raise type error if file doesn...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LikeFile: """File-like object used by SigFile, DeltaFile, and PatchFile""" def __init__(self, infile, need_seek=None): """LikeFile initializer - zero buffers, set eofs off""" self.check_file(infile, need_seek) self.infile = infile self.closed = self.infile_closed = None ...
the_stack_v2_python_sparse
duplicity/librsync.py
henrysher/duplicity
train
90
abcfc42589ba95e61fb11ff1f0e218828f139f42
[ "if type(data) != np.ndarray or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nn = data.shape[1]\nif n < 2:\n raise ValueError('data must contain multiple data points')\nd = data.shape[0]\nself.mean = np.mean(data, axis=1).reshape(d, 1)\nX = data - self.mean\nself.cov = np.dot(X, ...
<|body_start_0|> if type(data) != np.ndarray or len(data.shape) != 2: raise TypeError('data must be a 2D numpy.ndarray') n = data.shape[1] if n < 2: raise ValueError('data must contain multiple data points') d = data.shape[0] self.mean = np.mean(data, axis...
Class that represents a Multivariate Normal distribution
MultiNormal
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiNormal: """Class that represents a Multivariate Normal distribution""" def __init__(self, data): """Constructor funtcion Arguments: - data is a numpy.ndarray of shape (d, n) containing the data set: - n is the number of data points - d is the number of dimensions in each data po...
stack_v2_sparse_classes_36k_train_012334
2,132
no_license
[ { "docstring": "Constructor funtcion Arguments: - data is a numpy.ndarray of shape (d, n) containing the data set: - n is the number of data points - d is the number of dimensions in each data point Public instance variables: - mean - a numpy.ndarray of shape (d, 1) containing the mean of data - cov - a numpy.n...
2
null
Implement the Python class `MultiNormal` described below. Class description: Class that represents a Multivariate Normal distribution Method signatures and docstrings: - def __init__(self, data): Constructor funtcion Arguments: - data is a numpy.ndarray of shape (d, n) containing the data set: - n is the number of da...
Implement the Python class `MultiNormal` described below. Class description: Class that represents a Multivariate Normal distribution Method signatures and docstrings: - def __init__(self, data): Constructor funtcion Arguments: - data is a numpy.ndarray of shape (d, n) containing the data set: - n is the number of da...
fc2cec306961f7ca2448965ddd3a2f656bbe10c7
<|skeleton|> class MultiNormal: """Class that represents a Multivariate Normal distribution""" def __init__(self, data): """Constructor funtcion Arguments: - data is a numpy.ndarray of shape (d, n) containing the data set: - n is the number of data points - d is the number of dimensions in each data po...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiNormal: """Class that represents a Multivariate Normal distribution""" def __init__(self, data): """Constructor funtcion Arguments: - data is a numpy.ndarray of shape (d, n) containing the data set: - n is the number of data points - d is the number of dimensions in each data point Public in...
the_stack_v2_python_sparse
math/0x06-multivariate_prob/multinormal.py
dalexach/holbertonschool-machine_learning
train
2
3dac4473e9fa80d202f36bbda543413e08bcc674
[ "try:\n count = current_app.redis_slave.zscore(cls.key, user_id)\nexcept RedisError as e:\n current_app.logger.error(e)\n raise e\nif count:\n return int(count) if int(count) > 0 else 0\nelse:\n return 0", "try:\n current_app.redis_master.zincrby(cls.key, user_id)\nexcept RedisError as e:\n c...
<|body_start_0|> try: count = current_app.redis_slave.zscore(cls.key, user_id) except RedisError as e: current_app.logger.error(e) raise e if count: return int(count) if int(count) > 0 else 0 else: return 0 <|end_body_0|> <|bod...
数据统计的基类
BaseCountStorage
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseCountStorage: """数据统计的基类""" def get(cls, user_id): """获取指定用户的统计量 :return: 数量""" <|body_0|> def incr(cls, user_id): """更新用户指定的统计量 :return: None""" <|body_1|> def reset(cls, db_query_ret): """重置对应的数据集 :data: 数据集合 :return:""" <|body_...
stack_v2_sparse_classes_36k_train_012335
3,455
permissive
[ { "docstring": "获取指定用户的统计量 :return: 数量", "name": "get", "signature": "def get(cls, user_id)" }, { "docstring": "更新用户指定的统计量 :return: None", "name": "incr", "signature": "def incr(cls, user_id)" }, { "docstring": "重置对应的数据集 :data: 数据集合 :return:", "name": "reset", "signature"...
3
stack_v2_sparse_classes_30k_test_000192
Implement the Python class `BaseCountStorage` described below. Class description: 数据统计的基类 Method signatures and docstrings: - def get(cls, user_id): 获取指定用户的统计量 :return: 数量 - def incr(cls, user_id): 更新用户指定的统计量 :return: None - def reset(cls, db_query_ret): 重置对应的数据集 :data: 数据集合 :return:
Implement the Python class `BaseCountStorage` described below. Class description: 数据统计的基类 Method signatures and docstrings: - def get(cls, user_id): 获取指定用户的统计量 :return: 数量 - def incr(cls, user_id): 更新用户指定的统计量 :return: None - def reset(cls, db_query_ret): 重置对应的数据集 :data: 数据集合 :return: <|skeleton|> class BaseCountStor...
dbdf0f3790d0dc5f233b4c9e7bd69927bbfff28d
<|skeleton|> class BaseCountStorage: """数据统计的基类""" def get(cls, user_id): """获取指定用户的统计量 :return: 数量""" <|body_0|> def incr(cls, user_id): """更新用户指定的统计量 :return: None""" <|body_1|> def reset(cls, db_query_ret): """重置对应的数据集 :data: 数据集合 :return:""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseCountStorage: """数据统计的基类""" def get(cls, user_id): """获取指定用户的统计量 :return: 数量""" try: count = current_app.redis_slave.zscore(cls.key, user_id) except RedisError as e: current_app.logger.error(e) raise e if count: return in...
the_stack_v2_python_sparse
common/cache/statistic.py
qls7/xinwen
train
0
baeca08d23207a0224ba2009160b44f5de2f0b65
[ "path = os.path.join(self.directory, self.filepath)\nlog_report('INFO', 'path: ' + str(path), self)\nself.image_dp = self.get_default_image_path(path, self.image_dp)\ncameras, points, mesh_fp, image_dp = MeshroomFileHandler.parse_meshroom_file(path, self.use_workspace_images, self.image_dp, self.image_fp_type, self...
<|body_start_0|> path = os.path.join(self.directory, self.filepath) log_report('INFO', 'path: ' + str(path), self) self.image_dp = self.get_default_image_path(path, self.image_dp) cameras, points, mesh_fp, image_dp = MeshroomFileHandler.parse_meshroom_file(path, self.use_workspace_images...
Import a :code:`Meshroom` MG/SfM/JSON file.
ImportMeshroomOperator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImportMeshroomOperator: """Import a :code:`Meshroom` MG/SfM/JSON file.""" def execute(self, context): """Import a :code:`Meshroom` file/workspace.""" <|body_0|> def invoke(self, context, event): """Set the default import options before running the operator.""" ...
stack_v2_sparse_classes_36k_train_012336
5,448
permissive
[ { "docstring": "Import a :code:`Meshroom` file/workspace.", "name": "execute", "signature": "def execute(self, context)" }, { "docstring": "Set the default import options before running the operator.", "name": "invoke", "signature": "def invoke(self, context, event)" }, { "docstr...
3
stack_v2_sparse_classes_30k_train_001766
Implement the Python class `ImportMeshroomOperator` described below. Class description: Import a :code:`Meshroom` MG/SfM/JSON file. Method signatures and docstrings: - def execute(self, context): Import a :code:`Meshroom` file/workspace. - def invoke(self, context, event): Set the default import options before runnin...
Implement the Python class `ImportMeshroomOperator` described below. Class description: Import a :code:`Meshroom` MG/SfM/JSON file. Method signatures and docstrings: - def execute(self, context): Import a :code:`Meshroom` file/workspace. - def invoke(self, context, event): Set the default import options before runnin...
da404ebf8d4412196c2740f0b569cbf9e542952d
<|skeleton|> class ImportMeshroomOperator: """Import a :code:`Meshroom` MG/SfM/JSON file.""" def execute(self, context): """Import a :code:`Meshroom` file/workspace.""" <|body_0|> def invoke(self, context, event): """Set the default import options before running the operator.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ImportMeshroomOperator: """Import a :code:`Meshroom` MG/SfM/JSON file.""" def execute(self, context): """Import a :code:`Meshroom` file/workspace.""" path = os.path.join(self.directory, self.filepath) log_report('INFO', 'path: ' + str(path), self) self.image_dp = self.get_...
the_stack_v2_python_sparse
photogrammetry_importer/operators/meshroom_import_op.py
SBCV/Blender-Addon-Photogrammetry-Importer
train
718
f42ec257bbf40bc57b982776371775865744bd0b
[ "albums = Album.objects.all()\nalbums = album_filter(request, albums)\nif type(albums) == Response:\n return albums\nreturn Response(AlbumSerializer(albums, many=True).data)", "serializer = AlbumSerializerCreate(data=request.data, context={'request': request})\nif serializer.is_valid():\n serializer.save()\...
<|body_start_0|> albums = Album.objects.all() albums = album_filter(request, albums) if type(albums) == Response: return albums return Response(AlbumSerializer(albums, many=True).data) <|end_body_0|> <|body_start_1|> serializer = AlbumSerializerCreate(data=request.da...
AlbumView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlbumView: def get(request): """List albums""" <|body_0|> def post(request): """Create album""" <|body_1|> <|end_skeleton|> <|body_start_0|> albums = Album.objects.all() albums = album_filter(request, albums) if type(albums) == Respo...
stack_v2_sparse_classes_36k_train_012337
2,230
permissive
[ { "docstring": "List albums", "name": "get", "signature": "def get(request)" }, { "docstring": "Create album", "name": "post", "signature": "def post(request)" } ]
2
null
Implement the Python class `AlbumView` described below. Class description: Implement the AlbumView class. Method signatures and docstrings: - def get(request): List albums - def post(request): Create album
Implement the Python class `AlbumView` described below. Class description: Implement the AlbumView class. Method signatures and docstrings: - def get(request): List albums - def post(request): Create album <|skeleton|> class AlbumView: def get(request): """List albums""" <|body_0|> def post...
b93fa2fea8d45df9f19c3c58037e59dad4981921
<|skeleton|> class AlbumView: def get(request): """List albums""" <|body_0|> def post(request): """Create album""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AlbumView: def get(request): """List albums""" albums = Album.objects.all() albums = album_filter(request, albums) if type(albums) == Response: return albums return Response(AlbumSerializer(albums, many=True).data) def post(request): """Create a...
the_stack_v2_python_sparse
v1/music/views/album.py
lawiz22/PLOUC-Backend-master
train
0
b0db2db35fed328278562d03ca063003c5146a3c
[ "super().__init__(**kwargs)\ntrain_factory, inference_factory, validation_factory, test_factory = (kwargs.get('triples_factory'), kwargs.get('inference_factory'), kwargs.get('validation_factory'), kwargs.get('test_factory'))\nif gnn_encoder is None:\n dim = self.entity_representations[0].shape[0]\n gnn_encode...
<|body_start_0|> super().__init__(**kwargs) train_factory, inference_factory, validation_factory, test_factory = (kwargs.get('triples_factory'), kwargs.get('inference_factory'), kwargs.get('validation_factory'), kwargs.get('test_factory')) if gnn_encoder is None: dim = self.entity_re...
Inductive NodePiece with a GNN encoder on top. Overall, it's a 3-step procedure: 1. Featurizing nodes via NodePiece 2. Message passing over the active graph using NodePiece features 3. Scoring function for a given batch of triples As of now, message passing is expected to be over the full graph
InductiveNodePieceGNN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InductiveNodePieceGNN: """Inductive NodePiece with a GNN encoder on top. Overall, it's a 3-step procedure: 1. Featurizing nodes via NodePiece 2. Message passing over the active graph using NodePiece features 3. Scoring function for a given batch of triples As of now, message passing is expected t...
stack_v2_sparse_classes_36k_train_012338
5,554
permissive
[ { "docstring": "Initialize the model. :param gnn_encoder: an iterable of message passing layers. Defaults to 2-layer CompGCN with Hadamard composition. :param kwargs: additional keyword-based parameters passed to `InductiveNodePiece.__init__`.", "name": "__init__", "signature": "def __init__(self, *, gn...
3
stack_v2_sparse_classes_30k_train_016714
Implement the Python class `InductiveNodePieceGNN` described below. Class description: Inductive NodePiece with a GNN encoder on top. Overall, it's a 3-step procedure: 1. Featurizing nodes via NodePiece 2. Message passing over the active graph using NodePiece features 3. Scoring function for a given batch of triples A...
Implement the Python class `InductiveNodePieceGNN` described below. Class description: Inductive NodePiece with a GNN encoder on top. Overall, it's a 3-step procedure: 1. Featurizing nodes via NodePiece 2. Message passing over the active graph using NodePiece features 3. Scoring function for a given batch of triples A...
5ff3597b18ab9a220e34361d3c3f262060811df1
<|skeleton|> class InductiveNodePieceGNN: """Inductive NodePiece with a GNN encoder on top. Overall, it's a 3-step procedure: 1. Featurizing nodes via NodePiece 2. Message passing over the active graph using NodePiece features 3. Scoring function for a given batch of triples As of now, message passing is expected t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InductiveNodePieceGNN: """Inductive NodePiece with a GNN encoder on top. Overall, it's a 3-step procedure: 1. Featurizing nodes via NodePiece 2. Message passing over the active graph using NodePiece features 3. Scoring function for a given batch of triples As of now, message passing is expected to be over the...
the_stack_v2_python_sparse
src/pykeen/models/inductive/inductive_nodepiece_gnn.py
pykeen/pykeen
train
1,308
841a8573b4336388f38566486a0f77934f33c60b
[ "if path.endswith('/'):\n path = path + 'index.html'\nreturn self.server.pages[path]", "try:\n content = self.load_page(self.path)\nexcept KeyError:\n self.send_response(404)\n self.end_headers()\nelse:\n self.send_response(200)\n self.end_headers()\n self.wfile.write(content)" ]
<|body_start_0|> if path.endswith('/'): path = path + 'index.html' return self.server.pages[path] <|end_body_0|> <|body_start_1|> try: content = self.load_page(self.path) except KeyError: self.send_response(404) self.end_headers() ...
Handler for the PreviewServer.
_PreviewHandler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _PreviewHandler: """Handler for the PreviewServer.""" def load_page(self, path): """Load a page, or raise KeyError.""" <|body_0|> def do_GET(self): """Handle GET requests.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if path.endswith('/'): ...
stack_v2_sparse_classes_36k_train_012339
1,528
permissive
[ { "docstring": "Load a page, or raise KeyError.", "name": "load_page", "signature": "def load_page(self, path)" }, { "docstring": "Handle GET requests.", "name": "do_GET", "signature": "def do_GET(self)" } ]
2
stack_v2_sparse_classes_30k_train_005409
Implement the Python class `_PreviewHandler` described below. Class description: Handler for the PreviewServer. Method signatures and docstrings: - def load_page(self, path): Load a page, or raise KeyError. - def do_GET(self): Handle GET requests.
Implement the Python class `_PreviewHandler` described below. Class description: Handler for the PreviewServer. Method signatures and docstrings: - def load_page(self, path): Load a page, or raise KeyError. - def do_GET(self): Handle GET requests. <|skeleton|> class _PreviewHandler: """Handler for the PreviewSer...
08b037518fafd9afef7b6dc34a9fd0960cc1de07
<|skeleton|> class _PreviewHandler: """Handler for the PreviewServer.""" def load_page(self, path): """Load a page, or raise KeyError.""" <|body_0|> def do_GET(self): """Handle GET requests.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _PreviewHandler: """Handler for the PreviewServer.""" def load_page(self, path): """Load a page, or raise KeyError.""" if path.endswith('/'): path = path + 'index.html' return self.server.pages[path] def do_GET(self): """Handle GET requests.""" try...
the_stack_v2_python_sparse
scarab/servers.py
cknv/scarab
train
0
86547aa61b3731edf1b4add87a115491cc54d68a
[ "length = len(nums)\nfor i in range(length):\n for j in range(i + 1, length):\n if nums[i] + nums[j] == target:\n print([i, j])\n return [i, j]\nelse:\n return []", "n = len(nums)\nmap = {}\nfor i in range(n):\n a = nums[i]\n b = target - a\n if b in map and map.get(b) ...
<|body_start_0|> length = len(nums) for i in range(length): for j in range(i + 1, length): if nums[i] + nums[j] == target: print([i, j]) return [i, j] else: return [] <|end_body_0|> <|body_start_1|> n = len(...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def two_sum(self, nums, target): """暴力法时间复杂度O(n^2) :type nums: List[int] :type target: int :rtype: List[int]""" <|body_0|> def two_sum2(self, nums, target): """一遍哈希表法,时间复杂度O(n) :type nums: List[int] :type target: int :rtype: List[int]""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_012340
1,873
no_license
[ { "docstring": "暴力法时间复杂度O(n^2) :type nums: List[int] :type target: int :rtype: List[int]", "name": "two_sum", "signature": "def two_sum(self, nums, target)" }, { "docstring": "一遍哈希表法,时间复杂度O(n) :type nums: List[int] :type target: int :rtype: List[int]", "name": "two_sum2", "signature": "d...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def two_sum(self, nums, target): 暴力法时间复杂度O(n^2) :type nums: List[int] :type target: int :rtype: List[int] - def two_sum2(self, nums, target): 一遍哈希表法,时间复杂度O(n) :type nums: List[in...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def two_sum(self, nums, target): 暴力法时间复杂度O(n^2) :type nums: List[int] :type target: int :rtype: List[int] - def two_sum2(self, nums, target): 一遍哈希表法,时间复杂度O(n) :type nums: List[in...
3b13b36f37eb364410b3b5b4f10a1808d8b1111e
<|skeleton|> class Solution: def two_sum(self, nums, target): """暴力法时间复杂度O(n^2) :type nums: List[int] :type target: int :rtype: List[int]""" <|body_0|> def two_sum2(self, nums, target): """一遍哈希表法,时间复杂度O(n) :type nums: List[int] :type target: int :rtype: List[int]""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def two_sum(self, nums, target): """暴力法时间复杂度O(n^2) :type nums: List[int] :type target: int :rtype: List[int]""" length = len(nums) for i in range(length): for j in range(i + 1, length): if nums[i] + nums[j] == target: print([i, ...
the_stack_v2_python_sparse
leetcode/1.py
yanggelinux/algorithm-data-structure
train
0
74f9eafdea97ac8b9552b795b3af81549c804fc5
[ "current_user = request.user\nhighlight_data = request.data.get('highlight_data', {})\ntry:\n article = Articles.objects.get(slug=slug)\nexcept Articles.DoesNotExist:\n return Response({'errors': HIGHLIGHT_MSGS['ARTICLE_NOT_FOUND']}, status=status.HTTP_404_NOT_FOUND)\nhighlights = Highlights.objects.filter(ar...
<|body_start_0|> current_user = request.user highlight_data = request.data.get('highlight_data', {}) try: article = Articles.objects.get(slug=slug) except Articles.DoesNotExist: return Response({'errors': HIGHLIGHT_MSGS['ARTICLE_NOT_FOUND']}, status=status.HTTP_40...
Provide methods for creating a highlight
CreateGetDeleteMyHighlightsAPIView
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateGetDeleteMyHighlightsAPIView: """Provide methods for creating a highlight""" def get(self, request, slug): """Get all my highlights for an article Params ------- request: Object with request data and functions. Returns -------- Response object: { "message": "message body", "hig...
stack_v2_sparse_classes_36k_train_012341
12,153
permissive
[ { "docstring": "Get all my highlights for an article Params ------- request: Object with request data and functions. Returns -------- Response object: { \"message\": \"message body\", \"highlights\": list of highlights and their details } OR { \"errors\": \"error details body\" }", "name": "get", "signa...
2
stack_v2_sparse_classes_30k_train_020182
Implement the Python class `CreateGetDeleteMyHighlightsAPIView` described below. Class description: Provide methods for creating a highlight Method signatures and docstrings: - def get(self, request, slug): Get all my highlights for an article Params ------- request: Object with request data and functions. Returns --...
Implement the Python class `CreateGetDeleteMyHighlightsAPIView` described below. Class description: Provide methods for creating a highlight Method signatures and docstrings: - def get(self, request, slug): Get all my highlights for an article Params ------- request: Object with request data and functions. Returns --...
5a31840856de4b361fe2594dfa7a33d7774d3fe2
<|skeleton|> class CreateGetDeleteMyHighlightsAPIView: """Provide methods for creating a highlight""" def get(self, request, slug): """Get all my highlights for an article Params ------- request: Object with request data and functions. Returns -------- Response object: { "message": "message body", "hig...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateGetDeleteMyHighlightsAPIView: """Provide methods for creating a highlight""" def get(self, request, slug): """Get all my highlights for an article Params ------- request: Object with request data and functions. Returns -------- Response object: { "message": "message body", "highlights": lis...
the_stack_v2_python_sparse
authors/apps/highlights/views.py
bl4ck4ndbr0wn/ah-centauri-backend
train
0
7bfcc0611b92fb47dbaa63385e7a3f3decd9eb05
[ "DBFormatter.__init__(self, logger, dbi)\nself.owner = '%s.' % owner if not owner in ('', '__MYSQL__') else ''\nself.sql = 'UPDATE {owner}FILES F SET LAST_MODIFIED_BY=:myuser,\\n LAST_MODIFICATION_DATE=:mydate,\\n IS_FILE_VALID = :is_file_valid\\n '.format(owner=self.owner)", "binds = dict(my...
<|body_start_0|> DBFormatter.__init__(self, logger, dbi) self.owner = '%s.' % owner if not owner in ('', '__MYSQL__') else '' self.sql = 'UPDATE {owner}FILES F SET LAST_MODIFIED_BY=:myuser,\n LAST_MODIFICATION_DATE=:mydate,\n IS_FILE_VALID = :is_file_valid\n '.format(owner=s...
File Update Status DAO class.
UpdateStatus
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpdateStatus: """File Update Status DAO class.""" def __init__(self, logger, dbi, owner): """Add schema owner and sql.""" <|body_0|> def execute(self, conn, logical_file_name, is_file_valid, lost, dataset, transaction=False): """for a given file or a list of file...
stack_v2_sparse_classes_36k_train_012342
2,612
permissive
[ { "docstring": "Add schema owner and sql.", "name": "__init__", "signature": "def __init__(self, logger, dbi, owner)" }, { "docstring": "for a given file or a list of files", "name": "execute", "signature": "def execute(self, conn, logical_file_name, is_file_valid, lost, dataset, transac...
2
null
Implement the Python class `UpdateStatus` described below. Class description: File Update Status DAO class. Method signatures and docstrings: - def __init__(self, logger, dbi, owner): Add schema owner and sql. - def execute(self, conn, logical_file_name, is_file_valid, lost, dataset, transaction=False): for a given f...
Implement the Python class `UpdateStatus` described below. Class description: File Update Status DAO class. Method signatures and docstrings: - def __init__(self, logger, dbi, owner): Add schema owner and sql. - def execute(self, conn, logical_file_name, is_file_valid, lost, dataset, transaction=False): for a given f...
14df8bbe8ee8f874fe423399b18afef911fe78c7
<|skeleton|> class UpdateStatus: """File Update Status DAO class.""" def __init__(self, logger, dbi, owner): """Add schema owner and sql.""" <|body_0|> def execute(self, conn, logical_file_name, is_file_valid, lost, dataset, transaction=False): """for a given file or a list of file...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UpdateStatus: """File Update Status DAO class.""" def __init__(self, logger, dbi, owner): """Add schema owner and sql.""" DBFormatter.__init__(self, logger, dbi) self.owner = '%s.' % owner if not owner in ('', '__MYSQL__') else '' self.sql = 'UPDATE {owner}FILES F SET LAST...
the_stack_v2_python_sparse
Server/Python/src/dbs/dao/Oracle/File/UpdateStatus.py
vkuznet/DBS
train
0
685701112523a6ca58daa5e3744648887070eaef
[ "self.name = info_dict['name']\nself.path = info_dict['path']\nself.save_path = info_dict['save_path']", "video = cv2.VideoCapture(self.path)\ncount = video.get(cv2.CAP_PROP_FRAME_COUNT)\nframes = []\nret, frame = video.read()\nassert ret\ncv2.imwrite(self.save_path + '.jpg', frame)\nreturn frames" ]
<|body_start_0|> self.name = info_dict['name'] self.path = info_dict['path'] self.save_path = info_dict['save_path'] <|end_body_0|> <|body_start_1|> video = cv2.VideoCapture(self.path) count = video.get(cv2.CAP_PROP_FRAME_COUNT) frames = [] ret, frame = video.rea...
Video3D
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Video3D: def __init__(self, info_dict): """keys of info_dict: name, path notes: if indexs of your img is 0,1,2,3, your frame num should be 4.""" <|body_0|> def get_cover_frames(self): """return: num_frames * height * width * channel (rgb:3 , flow:2)""" <|body...
stack_v2_sparse_classes_36k_train_012343
2,997
no_license
[ { "docstring": "keys of info_dict: name, path notes: if indexs of your img is 0,1,2,3, your frame num should be 4.", "name": "__init__", "signature": "def __init__(self, info_dict)" }, { "docstring": "return: num_frames * height * width * channel (rgb:3 , flow:2)", "name": "get_cover_frames"...
2
stack_v2_sparse_classes_30k_train_020206
Implement the Python class `Video3D` described below. Class description: Implement the Video3D class. Method signatures and docstrings: - def __init__(self, info_dict): keys of info_dict: name, path notes: if indexs of your img is 0,1,2,3, your frame num should be 4. - def get_cover_frames(self): return: num_frames *...
Implement the Python class `Video3D` described below. Class description: Implement the Video3D class. Method signatures and docstrings: - def __init__(self, info_dict): keys of info_dict: name, path notes: if indexs of your img is 0,1,2,3, your frame num should be 4. - def get_cover_frames(self): return: num_frames *...
b401a487a613b6e9dcfb42ce9ca134e7bda8b4f8
<|skeleton|> class Video3D: def __init__(self, info_dict): """keys of info_dict: name, path notes: if indexs of your img is 0,1,2,3, your frame num should be 4.""" <|body_0|> def get_cover_frames(self): """return: num_frames * height * width * channel (rgb:3 , flow:2)""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Video3D: def __init__(self, info_dict): """keys of info_dict: name, path notes: if indexs of your img is 0,1,2,3, your frame num should be 4.""" self.name = info_dict['name'] self.path = info_dict['path'] self.save_path = info_dict['save_path'] def get_cover_frames(self): ...
the_stack_v2_python_sparse
preprocessing/preparation/2.extract_first.py
subburajs/ChaLearn-2021-ISLR-Challenge
train
0
5eaaaf7a891fe628366957175dac812bb10f7455
[ "l = 0\nr = len(List) - 1\nif l > r:\n return None\nif l == r:\n return TreeNode(List[l])\nmid = int((l + r) / 2)\nroot = TreeNode(List[mid])\nroot.left = self.build_tree(List[:mid])\nroot.right = self.build_tree(List[mid + 1:])\nreturn root", "if not root:\n return []\nqueue = []\nresult = []\nqueue.app...
<|body_start_0|> l = 0 r = len(List) - 1 if l > r: return None if l == r: return TreeNode(List[l]) mid = int((l + r) / 2) root = TreeNode(List[mid]) root.left = self.build_tree(List[:mid]) root.right = self.build_tree(List[mid + 1:]...
二叉树结构类
BinaryTree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinaryTree: """二叉树结构类""" def build_tree(self, List): """构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归""" <|body_0|> def PrintFromTopToBottom(self, root): """从上往下打印二叉树——层序遍历""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_012344
4,104
no_license
[ { "docstring": "构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归", "name": "build_tree", "signature": "def build_tree(self, List)" }, { "docstring": "从上往下打印二叉树——层序遍历", "name": "PrintFromTopToBottom", "signature": "def PrintFromTopToBottom(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_014033
Implement the Python class `BinaryTree` described below. Class description: 二叉树结构类 Method signatures and docstrings: - def build_tree(self, List): 构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归 - def PrintFromTopToBottom(self, root): 从上往下打印二叉树——层序遍历
Implement the Python class `BinaryTree` described below. Class description: 二叉树结构类 Method signatures and docstrings: - def build_tree(self, List): 构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归 - def PrintFromTopToBottom(self, root): 从上往下打印二叉树——层序遍历 <|skeleton|> class BinaryTree: "...
4e4f739402b95691f6c91411da26d7d3bfe042b6
<|skeleton|> class BinaryTree: """二叉树结构类""" def build_tree(self, List): """构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归""" <|body_0|> def PrintFromTopToBottom(self, root): """从上往下打印二叉树——层序遍历""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinaryTree: """二叉树结构类""" def build_tree(self, List): """构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归""" l = 0 r = len(List) - 1 if l > r: return None if l == r: return TreeNode(List[l]) mid = int((l +...
the_stack_v2_python_sparse
剑指offer/17.树的子结构.py
hugechuanqi/Algorithms-and-Data-Structures
train
3
98b705b8745ea9f539f4e9a08af27bd40be13a13
[ "today = datetime.date.today().strftime('%y%m%d')\nkey = 'num:{shop_id}:{order_type}:{today}'.format(shop_id=shop_id, order_type=order_type, today=today)\nredis_conn = get_redis_connection('num_generate')\nnum = redis_conn.incr(key)\nredis_conn.expire(key, 3600 * 24)\nresult = '{shop_type}{shop_id_fill}{today}{orde...
<|body_start_0|> today = datetime.date.today().strftime('%y%m%d') key = 'num:{shop_id}:{order_type}:{today}'.format(shop_id=shop_id, order_type=order_type, today=today) redis_conn = get_redis_connection('num_generate') num = redis_conn.incr(key) redis_conn.expire(key, 3600 * 24) ...
单号生成器
NumGenerator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumGenerator: """单号生成器""" def generate(shop_id: int, order_type: int) -> str: """生成订单号,规则:店铺类型2位 + 店铺自增编号5位 + 订单日期6位 + 订单类型2位 + 订单自增编号4位 :param order_type: 订单类型: 1:普通订单,5:拼团订单""" <|body_0|> def decode(num: str) -> tuple: """解码订单号 :param num: 订单号码 :return: 店铺id, 订...
stack_v2_sparse_classes_36k_train_012345
6,425
permissive
[ { "docstring": "生成订单号,规则:店铺类型2位 + 店铺自增编号5位 + 订单日期6位 + 订单类型2位 + 订单自增编号4位 :param order_type: 订单类型: 1:普通订单,5:拼团订单", "name": "generate", "signature": "def generate(shop_id: int, order_type: int) -> str" }, { "docstring": "解码订单号 :param num: 订单号码 :return: 店铺id, 订单类型", "name": "decode", "signat...
2
stack_v2_sparse_classes_30k_test_000937
Implement the Python class `NumGenerator` described below. Class description: 单号生成器 Method signatures and docstrings: - def generate(shop_id: int, order_type: int) -> str: 生成订单号,规则:店铺类型2位 + 店铺自增编号5位 + 订单日期6位 + 订单类型2位 + 订单自增编号4位 :param order_type: 订单类型: 1:普通订单,5:拼团订单 - def decode(num: str) -> tuple: 解码订单号 :param num: ...
Implement the Python class `NumGenerator` described below. Class description: 单号生成器 Method signatures and docstrings: - def generate(shop_id: int, order_type: int) -> str: 生成订单号,规则:店铺类型2位 + 店铺自增编号5位 + 订单日期6位 + 订单类型2位 + 订单自增编号4位 :param order_type: 订单类型: 1:普通订单,5:拼团订单 - def decode(num: str) -> tuple: 解码订单号 :param num: ...
c0a4de1a4479fe83f36108c1fdd4d68d18348b8d
<|skeleton|> class NumGenerator: """单号生成器""" def generate(shop_id: int, order_type: int) -> str: """生成订单号,规则:店铺类型2位 + 店铺自增编号5位 + 订单日期6位 + 订单类型2位 + 订单自增编号4位 :param order_type: 订单类型: 1:普通订单,5:拼团订单""" <|body_0|> def decode(num: str) -> tuple: """解码订单号 :param num: 订单号码 :return: 店铺id, 订...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumGenerator: """单号生成器""" def generate(shop_id: int, order_type: int) -> str: """生成订单号,规则:店铺类型2位 + 店铺自增编号5位 + 订单日期6位 + 订单类型2位 + 订单自增编号4位 :param order_type: 订单类型: 1:普通订单,5:拼团订单""" today = datetime.date.today().strftime('%y%m%d') key = 'num:{shop_id}:{order_type}:{today}'.format(sho...
the_stack_v2_python_sparse
wsc_django/wsc_django/utils/core.py
hzh595395786/wsc_django
train
2
6b195ac6442a1965b29863fe210658327ae9ea5b
[ "def residual(x):\n y_, log_dy_dx = bijection(x)\n return (y_ - y, log_dy_dx)\nwith torch.no_grad():\n x, log_dx_dy = root_finder(residual, x0=y)\nctx.save_for_backward(x, *params)\nctx.bijection = bijection\nreturn (x, log_dx_dy)", "x, *params = ctx.saved_tensors\nwith torch.enable_grad():\n x = x.de...
<|body_start_0|> def residual(x): y_, log_dy_dx = bijection(x) return (y_ - y, log_dy_dx) with torch.no_grad(): x, log_dx_dy = root_finder(residual, x0=y) ctx.save_for_backward(x, *params) ctx.bijection = bijection return (x, log_dx_dy) <|end_b...
First-order-differentiation of an elementwise bijection under black-box inversion.
DifferentiableApproximateInverse
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DifferentiableApproximateInverse: """First-order-differentiation of an elementwise bijection under black-box inversion.""" def forward(ctx, root_finder, bijection, y, *params): """Inverse pass Parameters ---------- ctx : object context object to stash information for the backward cal...
stack_v2_sparse_classes_36k_train_012346
8,727
no_license
[ { "docstring": "Inverse pass Parameters ---------- ctx : object context object to stash information for the backward call root_finder : Callable Root finding method, which takes two parameters (residue, x0) bijection : Flow a flow object, whose forward function returns (y, dlogp) y : torch.Tensor the input to t...
2
stack_v2_sparse_classes_30k_train_002511
Implement the Python class `DifferentiableApproximateInverse` described below. Class description: First-order-differentiation of an elementwise bijection under black-box inversion. Method signatures and docstrings: - def forward(ctx, root_finder, bijection, y, *params): Inverse pass Parameters ---------- ctx : object...
Implement the Python class `DifferentiableApproximateInverse` described below. Class description: First-order-differentiation of an elementwise bijection under black-box inversion. Method signatures and docstrings: - def forward(ctx, root_finder, bijection, y, *params): Inverse pass Parameters ---------- ctx : object...
15835d43a5ec2d29f05d325d65ffd973a6c8a201
<|skeleton|> class DifferentiableApproximateInverse: """First-order-differentiation of an elementwise bijection under black-box inversion.""" def forward(ctx, root_finder, bijection, y, *params): """Inverse pass Parameters ---------- ctx : object context object to stash information for the backward cal...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DifferentiableApproximateInverse: """First-order-differentiation of an elementwise bijection under black-box inversion.""" def forward(ctx, root_finder, bijection, y, *params): """Inverse pass Parameters ---------- ctx : object context object to stash information for the backward call root_finder...
the_stack_v2_python_sparse
bgflow/bgflow/nn/flow/root_finding/approx_inverse.py
noegroup/smooth_normalizing_flows
train
1
c5c5c9e51526029c580e1690e6c14ca4d7f0583f
[ "Parameter.checkFloat(tau, 0.0, 1.0)\nParameter.checkClass(kernelX, AbstractKernel)\nParameter.checkClass(kernelY, AbstractKernel)\nself.kernelX = kernelX\nself.kernelY = kernelY\nself.tau = tau", "self.trainX = X\nself.trainY = Y\nKx = self.kernelX.evaluate(X, X)\nKy = self.kernelX.evaluate(Y, Y)\nKxx = numpy.do...
<|body_start_0|> Parameter.checkFloat(tau, 0.0, 1.0) Parameter.checkClass(kernelX, AbstractKernel) Parameter.checkClass(kernelY, AbstractKernel) self.kernelX = kernelX self.kernelY = kernelY self.tau = tau <|end_body_0|> <|body_start_1|> self.trainX = X s...
KernelCCA
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KernelCCA: def __init__(self, kernelX, kernelY, tau): """Intialise the object with kernels (i.e an object instantiating a subclass of AbstractKernel) on the X and Y spaces and regularisation parameter tau between 0 (no regularisation) and 1 (full regularisation). :param kernelX: The kern...
stack_v2_sparse_classes_36k_train_012347
3,998
no_license
[ { "docstring": "Intialise the object with kernels (i.e an object instantiating a subclass of AbstractKernel) on the X and Y spaces and regularisation parameter tau between 0 (no regularisation) and 1 (full regularisation). :param kernelX: The kernel object on the X examples. :type kernelX: :class:`apgl.kernel.A...
3
null
Implement the Python class `KernelCCA` described below. Class description: Implement the KernelCCA class. Method signatures and docstrings: - def __init__(self, kernelX, kernelY, tau): Intialise the object with kernels (i.e an object instantiating a subclass of AbstractKernel) on the X and Y spaces and regularisation...
Implement the Python class `KernelCCA` described below. Class description: Implement the KernelCCA class. Method signatures and docstrings: - def __init__(self, kernelX, kernelY, tau): Intialise the object with kernels (i.e an object instantiating a subclass of AbstractKernel) on the X and Y spaces and regularisation...
1703510cbb51ec6df0efe1de850cd48ef7004b00
<|skeleton|> class KernelCCA: def __init__(self, kernelX, kernelY, tau): """Intialise the object with kernels (i.e an object instantiating a subclass of AbstractKernel) on the X and Y spaces and regularisation parameter tau between 0 (no regularisation) and 1 (full regularisation). :param kernelX: The kern...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KernelCCA: def __init__(self, kernelX, kernelY, tau): """Intialise the object with kernels (i.e an object instantiating a subclass of AbstractKernel) on the X and Y spaces and regularisation parameter tau between 0 (no regularisation) and 1 (full regularisation). :param kernelX: The kernel object on t...
the_stack_v2_python_sparse
apgl/features/KernelCCA.py
malcolmreynolds/APGL
train
0
e05abbef9c25320578f58a3065230ba6d8503014
[ "if not root:\n return '[]'\nfrom collections import deque\nq = deque()\nq.append(root)\nres = []\nwhile q:\n temp = q.popleft()\n if temp:\n res.append(str(temp.val))\n q.append(temp.left)\n q.append(temp.right)\n else:\n res.append('null')\nreturn '[' + ','.join(res) + ']'"...
<|body_start_0|> if not root: return '[]' from collections import deque q = deque() q.append(root) res = [] while q: temp = q.popleft() if temp: res.append(str(temp.val)) q.append(temp.left) ...
Codec
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_012348
3,372
permissive
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
a81007908e3c2f65a6be3ff2d62dfb92d0753b0d
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return '[]' from collections import deque q = deque() q.append(root) res = [] while q: temp = q.popleft() ...
the_stack_v2_python_sparse
algo_probs/jzoffer/jz37.py
Jackthebighead/recruiment-2022
train
0
9287250760624f3e344034fb105186a21f6ae4f2
[ "response = utility.ExecutorResponse()\nerr_msg = 'Testing handling of OSError'\nwith patch('subprocess.run') as mock_run:\n mock_run.side_effect = MagicMock(side_effect=OSError(err_msg))\n response.execute_command([])\nself.assertEqual(response._stdout, '')\nself.assertEqual(response._stderr, err_msg)", "t...
<|body_start_0|> response = utility.ExecutorResponse() err_msg = 'Testing handling of OSError' with patch('subprocess.run') as mock_run: mock_run.side_effect = MagicMock(side_effect=OSError(err_msg)) response.execute_command([]) self.assertEqual(response._stdout, ...
UtilityTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UtilityTest: def test_execute_command_oserror(self): """Testing stdout and stderr is correctly captured upon OSError.""" <|body_0|> def test_execute_command_stdout(self): """Testing stdout output is correctly captured.""" <|body_1|> def test_execute_comm...
stack_v2_sparse_classes_36k_train_012349
2,714
permissive
[ { "docstring": "Testing stdout and stderr is correctly captured upon OSError.", "name": "test_execute_command_oserror", "signature": "def test_execute_command_oserror(self)" }, { "docstring": "Testing stdout output is correctly captured.", "name": "test_execute_command_stdout", "signatur...
5
stack_v2_sparse_classes_30k_train_013368
Implement the Python class `UtilityTest` described below. Class description: Implement the UtilityTest class. Method signatures and docstrings: - def test_execute_command_oserror(self): Testing stdout and stderr is correctly captured upon OSError. - def test_execute_command_stdout(self): Testing stdout output is corr...
Implement the Python class `UtilityTest` described below. Class description: Implement the UtilityTest class. Method signatures and docstrings: - def test_execute_command_oserror(self): Testing stdout and stderr is correctly captured upon OSError. - def test_execute_command_stdout(self): Testing stdout output is corr...
3fb199658f68e7debf4906d9ce32a9a307e39243
<|skeleton|> class UtilityTest: def test_execute_command_oserror(self): """Testing stdout and stderr is correctly captured upon OSError.""" <|body_0|> def test_execute_command_stdout(self): """Testing stdout output is correctly captured.""" <|body_1|> def test_execute_comm...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UtilityTest: def test_execute_command_oserror(self): """Testing stdout and stderr is correctly captured upon OSError.""" response = utility.ExecutorResponse() err_msg = 'Testing handling of OSError' with patch('subprocess.run') as mock_run: mock_run.side_effect = Ma...
the_stack_v2_python_sparse
sdk/python/kfp/cli/diagnose_me/utility_test.py
kubeflow/pipelines
train
3,434
6f352844dd7a9acce659d9b4f688fbda3ab5b746
[ "self.data = data\nself.eof = eof\nself.error = error\nself.file_length = file_length\nself.start_offset = start_offset", "if dictionary is None:\n return None\ndata = dictionary.get('data')\neof = dictionary.get('eof')\nerror = cohesity_management_sdk.models.error_proto.ErrorProto.from_dictionary(dictionary.g...
<|body_start_0|> self.data = data self.eof = eof self.error = error self.file_length = file_length self.start_offset = start_offset <|end_body_0|> <|body_start_1|> if dictionary is None: return None data = dictionary.get('data') eof = dictiona...
Implementation of the 'ExtractFileRangeResult' model. This will capture output of ExtractFileRange and ExtractNFSFileRange. Attributes: data (list of long|int): The actual data bytes. eof (bool): Will be true if start_offset > file length or EOF is reached. This is an alternative to using file_length to determine when ...
ExtractFileRangeResult
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExtractFileRangeResult: """Implementation of the 'ExtractFileRangeResult' model. This will capture output of ExtractFileRange and ExtractNFSFileRange. Attributes: data (list of long|int): The actual data bytes. eof (bool): Will be true if start_offset > file length or EOF is reached. This is an a...
stack_v2_sparse_classes_36k_train_012350
2,663
permissive
[ { "docstring": "Constructor for the ExtractFileRangeResult class", "name": "__init__", "signature": "def __init__(self, data=None, eof=None, error=None, file_length=None, start_offset=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A d...
2
null
Implement the Python class `ExtractFileRangeResult` described below. Class description: Implementation of the 'ExtractFileRangeResult' model. This will capture output of ExtractFileRange and ExtractNFSFileRange. Attributes: data (list of long|int): The actual data bytes. eof (bool): Will be true if start_offset > file...
Implement the Python class `ExtractFileRangeResult` described below. Class description: Implementation of the 'ExtractFileRangeResult' model. This will capture output of ExtractFileRange and ExtractNFSFileRange. Attributes: data (list of long|int): The actual data bytes. eof (bool): Will be true if start_offset > file...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class ExtractFileRangeResult: """Implementation of the 'ExtractFileRangeResult' model. This will capture output of ExtractFileRange and ExtractNFSFileRange. Attributes: data (list of long|int): The actual data bytes. eof (bool): Will be true if start_offset > file length or EOF is reached. This is an a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExtractFileRangeResult: """Implementation of the 'ExtractFileRangeResult' model. This will capture output of ExtractFileRange and ExtractNFSFileRange. Attributes: data (list of long|int): The actual data bytes. eof (bool): Will be true if start_offset > file length or EOF is reached. This is an alternative to...
the_stack_v2_python_sparse
cohesity_management_sdk/models/extract_file_range_result.py
cohesity/management-sdk-python
train
24
bb44a0ff42db36d942dbe184c7a09a2e11a3791c
[ "sq = []\ntq = []\nfor s in S:\n if s != '#':\n sq.append(s)\n else:\n try:\n sq.pop()\n except:\n pass\nfor t in T:\n if t != '#':\n tq.append(t)\n else:\n try:\n tq.pop()\n except:\n pass\nreturn tq == sq", "s_str ...
<|body_start_0|> sq = [] tq = [] for s in S: if s != '#': sq.append(s) else: try: sq.pop() except: pass for t in T: if t != '#': tq.append(t) ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _backspaceCompare(self, S, T): """:type S: str :type T: str :rtype: bool""" <|body_0|> def backspaceCompare(self, S, T): """:type S: str :type T: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> sq = [] tq = [] ...
stack_v2_sparse_classes_36k_train_012351
2,623
permissive
[ { "docstring": ":type S: str :type T: str :rtype: bool", "name": "_backspaceCompare", "signature": "def _backspaceCompare(self, S, T)" }, { "docstring": ":type S: str :type T: str :rtype: bool", "name": "backspaceCompare", "signature": "def backspaceCompare(self, S, T)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _backspaceCompare(self, S, T): :type S: str :type T: str :rtype: bool - def backspaceCompare(self, S, T): :type S: str :type T: str :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _backspaceCompare(self, S, T): :type S: str :type T: str :rtype: bool - def backspaceCompare(self, S, T): :type S: str :type T: str :rtype: bool <|skeleton|> class Solution:...
0dd67edca4e0b0323cb5a7239f02ea46383cd15a
<|skeleton|> class Solution: def _backspaceCompare(self, S, T): """:type S: str :type T: str :rtype: bool""" <|body_0|> def backspaceCompare(self, S, T): """:type S: str :type T: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def _backspaceCompare(self, S, T): """:type S: str :type T: str :rtype: bool""" sq = [] tq = [] for s in S: if s != '#': sq.append(s) else: try: sq.pop() except: ...
the_stack_v2_python_sparse
844.backspace-string-compare.py
windard/leeeeee
train
0
85093ce0dde3042a1641d214fe093650ef2e44d4
[ "if not nums:\n return 1\nzeros = [0] * (max(nums) + 2)\nfor num in nums:\n if num > 0:\n zeros[num] = 1\nfor i in range(1, len(zeros)):\n if zeros[i] != 1:\n return i", "nums = set(nums)\nfor i in range(1, len(nums) + 2):\n if i not in nums:\n return i", "zeros = [0] * (len(num...
<|body_start_0|> if not nums: return 1 zeros = [0] * (max(nums) + 2) for num in nums: if num > 0: zeros[num] = 1 for i in range(1, len(zeros)): if zeros[i] != 1: return i <|end_body_0|> <|body_start_1|> nums = s...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _firstMissingPositive(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def __firstMissingPositive(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> def ___firstMissingPositive(self, nums): """:type nums:...
stack_v2_sparse_classes_36k_train_012352
2,642
permissive
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "_firstMissingPositive", "signature": "def _firstMissingPositive(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "__firstMissingPositive", "signature": "def __firstMissingPositive(self, nums)" }, ...
4
stack_v2_sparse_classes_30k_train_012351
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _firstMissingPositive(self, nums): :type nums: List[int] :rtype: int - def __firstMissingPositive(self, nums): :type nums: List[int] :rtype: int - def ___firstMissingPositive...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _firstMissingPositive(self, nums): :type nums: List[int] :rtype: int - def __firstMissingPositive(self, nums): :type nums: List[int] :rtype: int - def ___firstMissingPositive...
0dd67edca4e0b0323cb5a7239f02ea46383cd15a
<|skeleton|> class Solution: def _firstMissingPositive(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def __firstMissingPositive(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> def ___firstMissingPositive(self, nums): """:type nums:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def _firstMissingPositive(self, nums): """:type nums: List[int] :rtype: int""" if not nums: return 1 zeros = [0] * (max(nums) + 2) for num in nums: if num > 0: zeros[num] = 1 for i in range(1, len(zeros)): if...
the_stack_v2_python_sparse
41.first-missing-positive.py
windard/leeeeee
train
0
8d9be2ff8b8ac9e088adef79f4e58bfeccb68d13
[ "context = {'measurements_form': forms.DatasetTypeMeasurementsForm(), 'flags_definition_form': forms.DatasetTypeFlagsDefinitionForm(), 'dataset_type_id': dataset_type_id}\ndataset_type = models.DatasetType.objects.using('agdc').get(id=dataset_type_id)\ncontext.update(utils.forms_from_definition(dataset_type.definit...
<|body_start_0|> context = {'measurements_form': forms.DatasetTypeMeasurementsForm(), 'flags_definition_form': forms.DatasetTypeFlagsDefinitionForm(), 'dataset_type_id': dataset_type_id} dataset_type = models.DatasetType.objects.using('agdc').get(id=dataset_type_id) context.update(utils.forms_fr...
Main end piont for viewing or adding a dataset type
DatasetTypeView
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DatasetTypeView: """Main end piont for viewing or adding a dataset type""" def get(self, request, dataset_type_id=None): """View a dataset type and all its attributes Context: Bound forms for: DatasetTypeMeasurementsForm, DatasetTypeFlagsDefinitionForm dataset_type_id: id/pk of the d...
stack_v2_sparse_classes_36k_train_012353
10,227
permissive
[ { "docstring": "View a dataset type and all its attributes Context: Bound forms for: DatasetTypeMeasurementsForm, DatasetTypeFlagsDefinitionForm dataset_type_id: id/pk of the dataset type", "name": "get", "signature": "def get(self, request, dataset_type_id=None)" }, { "docstring": "Add a datase...
2
stack_v2_sparse_classes_30k_train_011957
Implement the Python class `DatasetTypeView` described below. Class description: Main end piont for viewing or adding a dataset type Method signatures and docstrings: - def get(self, request, dataset_type_id=None): View a dataset type and all its attributes Context: Bound forms for: DatasetTypeMeasurementsForm, Datas...
Implement the Python class `DatasetTypeView` described below. Class description: Main end piont for viewing or adding a dataset type Method signatures and docstrings: - def get(self, request, dataset_type_id=None): View a dataset type and all its attributes Context: Bound forms for: DatasetTypeMeasurementsForm, Datas...
ef50e918df89313f130d735e7cb7c0a069da410e
<|skeleton|> class DatasetTypeView: """Main end piont for viewing or adding a dataset type""" def get(self, request, dataset_type_id=None): """View a dataset type and all its attributes Context: Bound forms for: DatasetTypeMeasurementsForm, DatasetTypeFlagsDefinitionForm dataset_type_id: id/pk of the d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DatasetTypeView: """Main end piont for viewing or adding a dataset type""" def get(self, request, dataset_type_id=None): """View a dataset type and all its attributes Context: Bound forms for: DatasetTypeMeasurementsForm, DatasetTypeFlagsDefinitionForm dataset_type_id: id/pk of the dataset type""...
the_stack_v2_python_sparse
apps/data_cube_manager/views/dataset_type.py
ceos-seo/data_cube_ui
train
47
af037bb5ad00faf28b049035574e0958ac91e08f
[ "super(MotionFieldEncoder, self).__init__()\nconv_prop_0 = {'kernel_size': 3, 'strides': 2, 'activation': 'relu', 'padding': 'same', 'kernel_regularizer': tf.keras.regularizers.L2(weight_reg)}\nself.conv_encoder = []\nnum_conv_enc = 7\nchannels = [6]\nfor i in range(1, num_conv_enc + 1):\n channels.append(2 ** (...
<|body_start_0|> super(MotionFieldEncoder, self).__init__() conv_prop_0 = {'kernel_size': 3, 'strides': 2, 'activation': 'relu', 'padding': 'same', 'kernel_regularizer': tf.keras.regularizers.L2(weight_reg)} self.conv_encoder = [] num_conv_enc = 7 channels = [6] for i in ...
MotionFieldEncoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MotionFieldEncoder: def __init__(self, weight_reg=0.0): """Predict object-motion vectors from a stack of frames. auto_mask: True to automatically masking out the residual translations by thresholding on their mean values. weight_reg: A float scalar, the amount of weight regularization.""...
stack_v2_sparse_classes_36k_train_012354
18,266
no_license
[ { "docstring": "Predict object-motion vectors from a stack of frames. auto_mask: True to automatically masking out the residual translations by thresholding on their mean values. weight_reg: A float scalar, the amount of weight regularization.", "name": "__init__", "signature": "def __init__(self, weigh...
2
stack_v2_sparse_classes_30k_train_017842
Implement the Python class `MotionFieldEncoder` described below. Class description: Implement the MotionFieldEncoder class. Method signatures and docstrings: - def __init__(self, weight_reg=0.0): Predict object-motion vectors from a stack of frames. auto_mask: True to automatically masking out the residual translatio...
Implement the Python class `MotionFieldEncoder` described below. Class description: Implement the MotionFieldEncoder class. Method signatures and docstrings: - def __init__(self, weight_reg=0.0): Predict object-motion vectors from a stack of frames. auto_mask: True to automatically masking out the residual translatio...
a7be32bad38fc9555f480d2db1174aa4dd4d5d37
<|skeleton|> class MotionFieldEncoder: def __init__(self, weight_reg=0.0): """Predict object-motion vectors from a stack of frames. auto_mask: True to automatically masking out the residual translations by thresholding on their mean values. weight_reg: A float scalar, the amount of weight regularization.""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MotionFieldEncoder: def __init__(self, weight_reg=0.0): """Predict object-motion vectors from a stack of frames. auto_mask: True to automatically masking out the residual translations by thresholding on their mean values. weight_reg: A float scalar, the amount of weight regularization.""" supe...
the_stack_v2_python_sparse
models/motion_filed_net.py
dexter2406/Monodepth2-TF2
train
3
6e2f8466664eddb8afcb5c87a0f6feb57fb95fc8
[ "super(ChoicePhoneField, self).validate(value)\nif value and (not self.valid_value(value)):\n raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})", "for k, v, j, f in self.choices:\n if isinstance(v, (list, tuple)):\n for k2, v2 in v:\n if value == smart_unicode...
<|body_start_0|> super(ChoicePhoneField, self).validate(value) if value and (not self.valid_value(value)): raise ValidationError(self.error_messages['invalid_choice'] % {'value': value}) <|end_body_0|> <|body_start_1|> for k, v, j, f in self.choices: if isinstance(v, (li...
ChoicePhoneField
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChoicePhoneField: def validate(self, value): """Validates that the input is in self.choices.""" <|body_0|> def valid_value(self, value): """Check to see if the provided value is a valid choice""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(Ch...
stack_v2_sparse_classes_36k_train_012355
9,752
no_license
[ { "docstring": "Validates that the input is in self.choices.", "name": "validate", "signature": "def validate(self, value)" }, { "docstring": "Check to see if the provided value is a valid choice", "name": "valid_value", "signature": "def valid_value(self, value)" } ]
2
null
Implement the Python class `ChoicePhoneField` described below. Class description: Implement the ChoicePhoneField class. Method signatures and docstrings: - def validate(self, value): Validates that the input is in self.choices. - def valid_value(self, value): Check to see if the provided value is a valid choice
Implement the Python class `ChoicePhoneField` described below. Class description: Implement the ChoicePhoneField class. Method signatures and docstrings: - def validate(self, value): Validates that the input is in self.choices. - def valid_value(self, value): Check to see if the provided value is a valid choice <|sk...
302324dccc135f55d92fb705c58314c55fed22aa
<|skeleton|> class ChoicePhoneField: def validate(self, value): """Validates that the input is in self.choices.""" <|body_0|> def valid_value(self, value): """Check to see if the provided value is a valid choice""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChoicePhoneField: def validate(self, value): """Validates that the input is in self.choices.""" super(ChoicePhoneField, self).validate(value) if value and (not self.valid_value(value)): raise ValidationError(self.error_messages['invalid_choice'] % {'value': value}) def...
the_stack_v2_python_sparse
django-shared/geobase/phone_code_widget.py
riyanhax/a-demo
train
0
16361925bc8dc93e9b8e3925fca08a72a4481964
[ "handler = self.get_handler()\nattrdate = handler.getncattr('first_meas_time')\nreturn datetime.strptime(attrdate, '%Y-%m-%d %H:%M:%S.%f')", "handler = self.get_handler()\nattrdate = handler.getncattr('last_meas_time')\nreturn datetime.strptime(attrdate, '%Y-%m-%d %H:%M:%S.%f')" ]
<|body_start_0|> handler = self.get_handler() attrdate = handler.getncattr('first_meas_time') return datetime.strptime(attrdate, '%Y-%m-%d %H:%M:%S.%f') <|end_body_0|> <|body_start_1|> handler = self.get_handler() attrdate = handler.getncattr('last_meas_time') return dat...
Mapper for CryoSat-2 Altimeter files from NOAA RADS 4.0. Overrides the NCFile mapper to take into account some specific attributes naming
Cryosat2NCFile
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Cryosat2NCFile: """Mapper for CryoSat-2 Altimeter files from NOAA RADS 4.0. Overrides the NCFile mapper to take into account some specific attributes naming""" def get_start_time(self): """Returns the minimum date of the file temporal coverage""" <|body_0|> def get_end_t...
stack_v2_sparse_classes_36k_train_012356
1,156
no_license
[ { "docstring": "Returns the minimum date of the file temporal coverage", "name": "get_start_time", "signature": "def get_start_time(self)" }, { "docstring": "Returns the maximum date of the file temporal coverage", "name": "get_end_time", "signature": "def get_end_time(self)" } ]
2
null
Implement the Python class `Cryosat2NCFile` described below. Class description: Mapper for CryoSat-2 Altimeter files from NOAA RADS 4.0. Overrides the NCFile mapper to take into account some specific attributes naming Method signatures and docstrings: - def get_start_time(self): Returns the minimum date of the file t...
Implement the Python class `Cryosat2NCFile` described below. Class description: Mapper for CryoSat-2 Altimeter files from NOAA RADS 4.0. Overrides the NCFile mapper to take into account some specific attributes naming Method signatures and docstrings: - def get_start_time(self): Returns the minimum date of the file t...
3c354f2ca69dc981eb4117976351e8d7454ad505
<|skeleton|> class Cryosat2NCFile: """Mapper for CryoSat-2 Altimeter files from NOAA RADS 4.0. Overrides the NCFile mapper to take into account some specific attributes naming""" def get_start_time(self): """Returns the minimum date of the file temporal coverage""" <|body_0|> def get_end_t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Cryosat2NCFile: """Mapper for CryoSat-2 Altimeter files from NOAA RADS 4.0. Overrides the NCFile mapper to take into account some specific attributes naming""" def get_start_time(self): """Returns the minimum date of the file temporal coverage""" handler = self.get_handler() attrd...
the_stack_v2_python_sparse
cerbere/cerbere/mapper/cryosat2ncfile.py
whigg/PySOL
train
0
b56a033581dd529f285a21ea85b11b295499f7c2
[ "context = {'page_title': 'Forgot Password', 'email_form': EmailForm(auto_id=True)}\ncontext.update(csrf(request))\nreturn render(request, 'authentication/forgot_password.html', context)", "email_form = EmailForm(request.POST, auto_id=True)\nif email_form.is_valid():\n try:\n input_email = email_form.cl...
<|body_start_0|> context = {'page_title': 'Forgot Password', 'email_form': EmailForm(auto_id=True)} context.update(csrf(request)) return render(request, 'authentication/forgot_password.html', context) <|end_body_0|> <|body_start_1|> email_form = EmailForm(request.POST, auto_id=True) ...
This class allows user to send account recovery email.
ForgotPasswordView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ForgotPasswordView: """This class allows user to send account recovery email.""" def get(self, request, *args, **kwargs): """Handles GET requests to the 'account_forgot_password' named route. Returns: A forgot-password template rendered to a HttpResponse.""" <|body_0|> d...
stack_v2_sparse_classes_36k_train_012357
17,941
permissive
[ { "docstring": "Handles GET requests to the 'account_forgot_password' named route. Returns: A forgot-password template rendered to a HttpResponse.", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Handles the POST request to the 'account_forgot_password' ...
2
null
Implement the Python class `ForgotPasswordView` described below. Class description: This class allows user to send account recovery email. Method signatures and docstrings: - def get(self, request, *args, **kwargs): Handles GET requests to the 'account_forgot_password' named route. Returns: A forgot-password template...
Implement the Python class `ForgotPasswordView` described below. Class description: This class allows user to send account recovery email. Method signatures and docstrings: - def get(self, request, *args, **kwargs): Handles GET requests to the 'account_forgot_password' named route. Returns: A forgot-password template...
3704cbe6e69ba3e4c53401d3bbc339208e9ebccd
<|skeleton|> class ForgotPasswordView: """This class allows user to send account recovery email.""" def get(self, request, *args, **kwargs): """Handles GET requests to the 'account_forgot_password' named route. Returns: A forgot-password template rendered to a HttpResponse.""" <|body_0|> d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ForgotPasswordView: """This class allows user to send account recovery email.""" def get(self, request, *args, **kwargs): """Handles GET requests to the 'account_forgot_password' named route. Returns: A forgot-password template rendered to a HttpResponse.""" context = {'page_title': 'Forg...
the_stack_v2_python_sparse
troupon/authentication/views.py
morristech/troupon
train
0
d7734a6fe05cf6219c28e93dffecae0c932c3fdf
[ "optimal_policy_path = os.path.dirname(os.getcwd()) + '/optimal_policy.pkl'\nself.optimal_policy, _ = pickle.load(open(optimal_policy_path, 'rb'))\nprint('Optimal policy loaded.')\n' Load the policy to be evaluated \\n '\npolicy_path = os.path.dirname(os.getcwd()) + '/policy_evaluation.pkl'\nself.policy, i...
<|body_start_0|> optimal_policy_path = os.path.dirname(os.getcwd()) + '/optimal_policy.pkl' self.optimal_policy, _ = pickle.load(open(optimal_policy_path, 'rb')) print('Optimal policy loaded.') ' Load the policy to be evaluated \n ' policy_path = os.path.dirname(os.getcw...
EvaluateAgainstOptimal
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EvaluateAgainstOptimal: def __init__(self): """Load an optimal policy""" <|body_0|> def Run(self): """Evaluate the performance of the policy as player X""" <|body_1|> def AutoPlay(self, policy_1, policy_2, n_games=100): """Let policy_1 and policy...
stack_v2_sparse_classes_36k_train_012358
2,769
no_license
[ { "docstring": "Load an optimal policy", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Evaluate the performance of the policy as player X", "name": "Run", "signature": "def Run(self)" }, { "docstring": "Let policy_1 and policy_2 play against each other ...
4
stack_v2_sparse_classes_30k_train_005543
Implement the Python class `EvaluateAgainstOptimal` described below. Class description: Implement the EvaluateAgainstOptimal class. Method signatures and docstrings: - def __init__(self): Load an optimal policy - def Run(self): Evaluate the performance of the policy as player X - def AutoPlay(self, policy_1, policy_2...
Implement the Python class `EvaluateAgainstOptimal` described below. Class description: Implement the EvaluateAgainstOptimal class. Method signatures and docstrings: - def __init__(self): Load an optimal policy - def Run(self): Evaluate the performance of the policy as player X - def AutoPlay(self, policy_1, policy_2...
5831d4c1eaf21d41007eb6988f3c9885b55d13b2
<|skeleton|> class EvaluateAgainstOptimal: def __init__(self): """Load an optimal policy""" <|body_0|> def Run(self): """Evaluate the performance of the policy as player X""" <|body_1|> def AutoPlay(self, policy_1, policy_2, n_games=100): """Let policy_1 and policy...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EvaluateAgainstOptimal: def __init__(self): """Load an optimal policy""" optimal_policy_path = os.path.dirname(os.getcwd()) + '/optimal_policy.pkl' self.optimal_policy, _ = pickle.load(open(optimal_policy_path, 'rb')) print('Optimal policy loaded.') ' Load the policy to...
the_stack_v2_python_sparse
ttt_evaluate_against_optimal.py
sw2703/rl_tictactoe
train
0
6bb5f0336d6b43662b746260bedb007303a47f96
[ "q = [root]\nstr_res = ''\nwhile q:\n q_temp = []\n for node in q:\n if node:\n str_res += ',' + str(node.val)\n q_temp.append(node.left)\n q_temp.append(node.right)\n else:\n str_res += ',None'\n q = q_temp\nreturn str_res[1:]", "if not data or d...
<|body_start_0|> q = [root] str_res = '' while q: q_temp = [] for node in q: if node: str_res += ',' + str(node.val) q_temp.append(node.left) q_temp.append(node.right) else: ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_012359
1,809
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
13e61c13c406a73debcfc996937cf16f715d55d1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" q = [root] str_res = '' while q: q_temp = [] for node in q: if node: str_res += ',' + str(node.val) ...
the_stack_v2_python_sparse
src/297_serialize_and_deserialize_binary_tree/297_serialize_and_deserialize_binary_tree_BasedBfs.py
ypliu/leetcode-python
train
0
116afa45e8b6a56bb2c18a1ad75127a152ede077
[ "if type is not None:\n assert type >= 256, type\nif content is not None:\n assert not isinstance(content, str), repr(content)\n newcontent = list(content)\n for i, item in enumerate(newcontent):\n assert isinstance(item, BasePattern), (i, item)\n if isinstance(item, WildcardPattern):\n ...
<|body_start_0|> if type is not None: assert type >= 256, type if content is not None: assert not isinstance(content, str), repr(content) newcontent = list(content) for i, item in enumerate(newcontent): assert isinstance(item, BasePattern),...
NodePattern
[ "MIT", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-other-copyleft", "GPL-1.0-or-later", "Python-2.0", "LicenseRef-scancode-python-cwi" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NodePattern: def __init__(self, type: Optional[int]=None, content: Optional[Iterable[str]]=None, name: Optional[str]=None) -> None: """Initializer. Takes optional type, content, and name. The type, if given, must be a symbol type (>= 256). If the type is None this matches *any* single no...
stack_v2_sparse_classes_36k_train_012360
32,569
permissive
[ { "docstring": "Initializer. Takes optional type, content, and name. The type, if given, must be a symbol type (>= 256). If the type is None this matches *any* single node (leaf or not), except if content is not None, in which it only matches non-leaf nodes that also match the content pattern. The content, if n...
2
stack_v2_sparse_classes_30k_train_018095
Implement the Python class `NodePattern` described below. Class description: Implement the NodePattern class. Method signatures and docstrings: - def __init__(self, type: Optional[int]=None, content: Optional[Iterable[str]]=None, name: Optional[str]=None) -> None: Initializer. Takes optional type, content, and name. ...
Implement the Python class `NodePattern` described below. Class description: Implement the NodePattern class. Method signatures and docstrings: - def __init__(self, type: Optional[int]=None, content: Optional[Iterable[str]]=None, name: Optional[str]=None) -> None: Initializer. Takes optional type, content, and name. ...
47676bf5939ae5c8e670d947917bc8af4732eab6
<|skeleton|> class NodePattern: def __init__(self, type: Optional[int]=None, content: Optional[Iterable[str]]=None, name: Optional[str]=None) -> None: """Initializer. Takes optional type, content, and name. The type, if given, must be a symbol type (>= 256). If the type is None this matches *any* single no...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NodePattern: def __init__(self, type: Optional[int]=None, content: Optional[Iterable[str]]=None, name: Optional[str]=None) -> None: """Initializer. Takes optional type, content, and name. The type, if given, must be a symbol type (>= 256). If the type is None this matches *any* single node (leaf or no...
the_stack_v2_python_sparse
src/blib2to3/pytree.py
psf/black
train
23,453
90e3d66ea7b36248c213bcae2c8fd2a12a388b1c
[ "self.config = get_config()\nself.config[STATES_KEYWORD] = {'attrs': self.config[STATES_KEYWORD]['attrs'], 'subset': [0]}\nself.base_path = path_to_base_field\nif randomizer is not None:\n self.randomizer = {}\n for key, def_r in self.default_randomizer.items():\n if key not in randomizer.keys() or ran...
<|body_start_0|> self.config = get_config() self.config[STATES_KEYWORD] = {'attrs': self.config[STATES_KEYWORD]['attrs'], 'subset': [0]} self.base_path = path_to_base_field if randomizer is not None: self.randomizer = {} for key, def_r in self.default_randomizer.i...
Randomization of Fields, based on some base model.
FieldRandomizer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FieldRandomizer: """Randomization of Fields, based on some base model.""" def __init__(self, path_to_base_field, randomizer=None): """Parameters ---------- path_to_base_field: std Path to the base-field used to randomize around. randomizer: dict Dict with instances of randomizers for...
stack_v2_sparse_classes_36k_train_012361
13,810
permissive
[ { "docstring": "Parameters ---------- path_to_base_field: std Path to the base-field used to randomize around. randomizer: dict Dict with instances of randomizers for states, rock and control (wells) Should have keys the following form: randomizer = { 'states': states_rand, 'rock': rock_rand, 'wells': control_r...
4
stack_v2_sparse_classes_30k_train_014398
Implement the Python class `FieldRandomizer` described below. Class description: Randomization of Fields, based on some base model. Method signatures and docstrings: - def __init__(self, path_to_base_field, randomizer=None): Parameters ---------- path_to_base_field: std Path to the base-field used to randomize around...
Implement the Python class `FieldRandomizer` described below. Class description: Randomization of Fields, based on some base model. Method signatures and docstrings: - def __init__(self, path_to_base_field, randomizer=None): Parameters ---------- path_to_base_field: std Path to the base-field used to randomize around...
3b336ed110ff806316f1f6a99b212f99256a6b56
<|skeleton|> class FieldRandomizer: """Randomization of Fields, based on some base model.""" def __init__(self, path_to_base_field, randomizer=None): """Parameters ---------- path_to_base_field: std Path to the base-field used to randomize around. randomizer: dict Dict with instances of randomizers for...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FieldRandomizer: """Randomization of Fields, based on some base model.""" def __init__(self, path_to_base_field, randomizer=None): """Parameters ---------- path_to_base_field: std Path to the base-field used to randomize around. randomizer: dict Dict with instances of randomizers for states, rock...
the_stack_v2_python_sparse
deepfield/datasets/randomize.py
scuervo91/DeepField
train
0
76d64f53001b8c812ba2d1c6c5c78bd4ba8d11c0
[ "super().__init__(maxiter=maxiter, gtol=gtol, etol=etol, **kwargs)\nself._line_search_type = line_search_type\nself._hessian_update_types = [BFGSUpdate, NullUpdate]\nself._alpha = init_alpha", "assert self._coords is not None and self._coords.g is not None and (self._species is not None) and (self._method is not ...
<|body_start_0|> super().__init__(maxiter=maxiter, gtol=gtol, etol=etol, **kwargs) self._line_search_type = line_search_type self._hessian_update_types = [BFGSUpdate, NullUpdate] self._alpha = init_alpha <|end_body_0|> <|body_start_1|> assert self._coords is not None and self._c...
BFGSOptimiser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BFGSOptimiser: def __init__(self, maxiter: int, gtol: GradientRMS, etol: PotentialEnergy, init_alpha: float=1.0, line_search_type: Type[LineSearchOptimiser]=ArmijoLineSearch, **kwargs): """Broyden–Fletcher–Goldfarb–Shanno optimiser. Implementation taken from: https://tinyurl.com/526yymsw...
stack_v2_sparse_classes_36k_train_012362
3,008
permissive
[ { "docstring": "Broyden–Fletcher–Goldfarb–Shanno optimiser. Implementation taken from: https://tinyurl.com/526yymsw ---------------------------------------------------------------------- Arguments: init_alpha (float): Length of the initial step to take in the line search. Units of distance See Also: :py:meth:`N...
2
null
Implement the Python class `BFGSOptimiser` described below. Class description: Implement the BFGSOptimiser class. Method signatures and docstrings: - def __init__(self, maxiter: int, gtol: GradientRMS, etol: PotentialEnergy, init_alpha: float=1.0, line_search_type: Type[LineSearchOptimiser]=ArmijoLineSearch, **kwargs...
Implement the Python class `BFGSOptimiser` described below. Class description: Implement the BFGSOptimiser class. Method signatures and docstrings: - def __init__(self, maxiter: int, gtol: GradientRMS, etol: PotentialEnergy, init_alpha: float=1.0, line_search_type: Type[LineSearchOptimiser]=ArmijoLineSearch, **kwargs...
4d6667592f083dfcf38de6b75c4222c0a0e7b60b
<|skeleton|> class BFGSOptimiser: def __init__(self, maxiter: int, gtol: GradientRMS, etol: PotentialEnergy, init_alpha: float=1.0, line_search_type: Type[LineSearchOptimiser]=ArmijoLineSearch, **kwargs): """Broyden–Fletcher–Goldfarb–Shanno optimiser. Implementation taken from: https://tinyurl.com/526yymsw...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BFGSOptimiser: def __init__(self, maxiter: int, gtol: GradientRMS, etol: PotentialEnergy, init_alpha: float=1.0, line_search_type: Type[LineSearchOptimiser]=ArmijoLineSearch, **kwargs): """Broyden–Fletcher–Goldfarb–Shanno optimiser. Implementation taken from: https://tinyurl.com/526yymsw -------------...
the_stack_v2_python_sparse
autode/opt/optimisers/bfgs.py
duartegroup/autodE
train
132
04d60c9c440f4649566f636ebb4f13702a25aeb4
[ "res = []\nself.backtrack([], [], [], n, res)\nprint(res)\nfinal_res = []\nfor sol in res:\n str_res = [['.' for _ in range(n)] for _ in range(n)]\n for i, j in enumerate(sol):\n str_res[i][j] = 'Q'\n final_res.append(map(lambda x: ''.join(x), str_res))\nreturn final_res", "if len(queens) == n:\n ...
<|body_start_0|> res = [] self.backtrack([], [], [], n, res) print(res) final_res = [] for sol in res: str_res = [['.' for _ in range(n)] for _ in range(n)] for i, j in enumerate(sol): str_res[i][j] = 'Q' final_res.append(map(la...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def solveNQueens(self, n): """:type n: int :rtype: List[List[str]]""" <|body_0|> def backtrack(self, queens, xy_sum, xy_diff, n, results): """queens: its indices are queens horizontal locations its values are queens vertical locations""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_012363
1,125
no_license
[ { "docstring": ":type n: int :rtype: List[List[str]]", "name": "solveNQueens", "signature": "def solveNQueens(self, n)" }, { "docstring": "queens: its indices are queens horizontal locations its values are queens vertical locations", "name": "backtrack", "signature": "def backtrack(self,...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def solveNQueens(self, n): :type n: int :rtype: List[List[str]] - def backtrack(self, queens, xy_sum, xy_diff, n, results): queens: its indices are queens horizontal locations it...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def solveNQueens(self, n): :type n: int :rtype: List[List[str]] - def backtrack(self, queens, xy_sum, xy_diff, n, results): queens: its indices are queens horizontal locations it...
24aaca7585c59255a86474c1f8088bd5b81ebf51
<|skeleton|> class Solution: def solveNQueens(self, n): """:type n: int :rtype: List[List[str]]""" <|body_0|> def backtrack(self, queens, xy_sum, xy_diff, n, results): """queens: its indices are queens horizontal locations its values are queens vertical locations""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def solveNQueens(self, n): """:type n: int :rtype: List[List[str]]""" res = [] self.backtrack([], [], [], n, res) print(res) final_res = [] for sol in res: str_res = [['.' for _ in range(n)] for _ in range(n)] for i, j in enumer...
the_stack_v2_python_sparse
Backtracking/51. N-Queens.py
burnmg/LC_algorithms_practice
train
0
aeb3ab99d75b26bd66743ad4a6bee3666807a4ab
[ "fmt = 'PO-{abc:02f}-{ref:04d}-{date}-???'\ninfo = InvenTree.format.parse_format_string(fmt)\nself.assertIn('abc', info)\nself.assertIn('ref', info)\nself.assertIn('date', info)\nfor fmt in ['PO-{{xyz}', 'PO-{xyz}}', 'PO-{xyz}-{']:\n with self.assertRaises(ValueError):\n InvenTree.format.parse_format_stri...
<|body_start_0|> fmt = 'PO-{abc:02f}-{ref:04d}-{date}-???' info = InvenTree.format.parse_format_string(fmt) self.assertIn('abc', info) self.assertIn('ref', info) self.assertIn('date', info) for fmt in ['PO-{{xyz}', 'PO-{xyz}}', 'PO-{xyz}-{']: with self.assertR...
Unit tests for custom string formatting functionality
FormatTest
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FormatTest: """Unit tests for custom string formatting functionality""" def test_parse(self): """Tests for the 'parse_format_string' function""" <|body_0|> def test_create_regex(self): """Test function for creating a regex from a format string""" <|body_1...
stack_v2_sparse_classes_36k_train_012364
41,191
permissive
[ { "docstring": "Tests for the 'parse_format_string' function", "name": "test_parse", "signature": "def test_parse(self)" }, { "docstring": "Test function for creating a regex from a format string", "name": "test_create_regex", "signature": "def test_create_regex(self)" }, { "docs...
4
null
Implement the Python class `FormatTest` described below. Class description: Unit tests for custom string formatting functionality Method signatures and docstrings: - def test_parse(self): Tests for the 'parse_format_string' function - def test_create_regex(self): Test function for creating a regex from a format strin...
Implement the Python class `FormatTest` described below. Class description: Unit tests for custom string formatting functionality Method signatures and docstrings: - def test_parse(self): Tests for the 'parse_format_string' function - def test_create_regex(self): Test function for creating a regex from a format strin...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class FormatTest: """Unit tests for custom string formatting functionality""" def test_parse(self): """Tests for the 'parse_format_string' function""" <|body_0|> def test_create_regex(self): """Test function for creating a regex from a format string""" <|body_1...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FormatTest: """Unit tests for custom string formatting functionality""" def test_parse(self): """Tests for the 'parse_format_string' function""" fmt = 'PO-{abc:02f}-{ref:04d}-{date}-???' info = InvenTree.format.parse_format_string(fmt) self.assertIn('abc', info) se...
the_stack_v2_python_sparse
InvenTree/InvenTree/tests.py
inventree/InvenTree
train
3,077
c079ccd79ea0b2e24628d41bb02a42ab6dcae4e2
[ "self.model_type = model_type\nself.model_name = model_name\nself.model_task = model_task\nself.model_description = model_description\nself.model_folder = os.path.join(ROOT_DIR, self.model_type, self.model_task, self.model_name)\nself.bucket = s3.S3Bucket(bucket_name='s3ludos')\nif not os.path.isdir(self.model_fold...
<|body_start_0|> self.model_type = model_type self.model_name = model_name self.model_task = model_task self.model_description = model_description self.model_folder = os.path.join(ROOT_DIR, self.model_type, self.model_task, self.model_name) self.bucket = s3.S3Bucket(bucke...
Base class for the model
BaseModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseModel: """Base class for the model""" def __init__(self, model_name: str, model_task: str, model_description: str='', expname: str=None, model_type: str='models'): """Args: model_type (str): Type of the model, 'models' model_name (str): Name of your model model_task (str): Task o...
stack_v2_sparse_classes_36k_train_012365
3,053
no_license
[ { "docstring": "Args: model_type (str): Type of the model, 'models' model_name (str): Name of your model model_task (str): Task of your model stage (str): training or prediction expname (str): Name of the experiment", "name": "__init__", "signature": "def __init__(self, model_name: str, model_task: str,...
2
stack_v2_sparse_classes_30k_train_002676
Implement the Python class `BaseModel` described below. Class description: Base class for the model Method signatures and docstrings: - def __init__(self, model_name: str, model_task: str, model_description: str='', expname: str=None, model_type: str='models'): Args: model_type (str): Type of the model, 'models' mode...
Implement the Python class `BaseModel` described below. Class description: Base class for the model Method signatures and docstrings: - def __init__(self, model_name: str, model_task: str, model_description: str='', expname: str=None, model_type: str='models'): Args: model_type (str): Type of the model, 'models' mode...
fd09eb1bceafe794d8784a21cfd3753cfd371258
<|skeleton|> class BaseModel: """Base class for the model""" def __init__(self, model_name: str, model_task: str, model_description: str='', expname: str=None, model_type: str='models'): """Args: model_type (str): Type of the model, 'models' model_name (str): Name of your model model_task (str): Task o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseModel: """Base class for the model""" def __init__(self, model_name: str, model_task: str, model_description: str='', expname: str=None, model_type: str='models'): """Args: model_type (str): Type of the model, 'models' model_name (str): Name of your model model_task (str): Task of your model ...
the_stack_v2_python_sparse
ludos/models/common.py
cthorey/ludos
train
0
7444b5029f2d1205696058eceaf2a7ba9aafa096
[ "ret = self.libssock.SCIONListen(self.fd)\nself.port = self.libssock.SCIONGetPort(self.fd)\nreturn ret", "newfd = self.libssock.SCIONAccept(self.fd)\nlogging.debug('Accepted socket %d' % newfd)\nreturn (ScionBaseSocket(self.proto, self.sciond_addr, newfd), None)" ]
<|body_start_0|> ret = self.libssock.SCIONListen(self.fd) self.port = self.libssock.SCIONGetPort(self.fd) return ret <|end_body_0|> <|body_start_1|> newfd = self.libssock.SCIONAccept(self.fd) logging.debug('Accepted socket %d' % newfd) return (ScionBaseSocket(self.proto,...
Server side wrapper of the SCION Multi-Path Socket.
ScionServerSocket
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScionServerSocket: """Server side wrapper of the SCION Multi-Path Socket.""" def listen(self): """Setup the socket to receive incoming connection requests. :returns: 0 on success, -1 on failure :rtype: int""" <|body_0|> def accept(self): """Accepts a connection. ...
stack_v2_sparse_classes_36k_train_012366
19,489
permissive
[ { "docstring": "Setup the socket to receive incoming connection requests. :returns: 0 on success, -1 on failure :rtype: int", "name": "listen", "signature": "def listen(self)" }, { "docstring": "Accepts a connection. The return value is a pair (conn, address) where conn is a new ScionBaseSocket ...
2
null
Implement the Python class `ScionServerSocket` described below. Class description: Server side wrapper of the SCION Multi-Path Socket. Method signatures and docstrings: - def listen(self): Setup the socket to receive incoming connection requests. :returns: 0 on success, -1 on failure :rtype: int - def accept(self): A...
Implement the Python class `ScionServerSocket` described below. Class description: Server side wrapper of the SCION Multi-Path Socket. Method signatures and docstrings: - def listen(self): Setup the socket to receive incoming connection requests. :returns: 0 on success, -1 on failure :rtype: int - def accept(self): A...
06f3f0b82dc8a535ce8b0a128282af00a8425a06
<|skeleton|> class ScionServerSocket: """Server side wrapper of the SCION Multi-Path Socket.""" def listen(self): """Setup the socket to receive incoming connection requests. :returns: 0 on success, -1 on failure :rtype: int""" <|body_0|> def accept(self): """Accepts a connection. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScionServerSocket: """Server side wrapper of the SCION Multi-Path Socket.""" def listen(self): """Setup the socket to receive incoming connection requests. :returns: 0 on success, -1 on failure :rtype: int""" ret = self.libssock.SCIONListen(self.fd) self.port = self.libssock.SCION...
the_stack_v2_python_sparse
endhost/scion_socket.py
marcoeilers/scion
train
1
d85516d4ba096d42f025f84bf5a5b90a5ba73204
[ "\"\"\"\n [1,1,3,4,5,7,7,9]\n \"\"\"\nnums.sort()\nlo, hi = (0, nums[-1] - nums[0])\nself.count(nums, 4)\nwhile lo < hi:\n mid = (hi + lo) / 2\n if self.count(nums, mid) >= k:\n hi = mid\n else:\n lo = mid + 1\nreturn lo", "count = right = 0\nfor left, n in enumerate(nums):\n ...
<|body_start_0|> """ [1,1,3,4,5,7,7,9] """ nums.sort() lo, hi = (0, nums[-1] - nums[0]) self.count(nums, 4) while lo < hi: mid = (hi + lo) / 2 if self.count(nums, mid) >= k: hi = mid else: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def smallestDistancePair(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_0|> def count(self, nums, val): """Count the total number of pair distance which is smaller than val""" <|body_1|> <|end_skeleton|> <|body_start_0...
stack_v2_sparse_classes_36k_train_012367
1,574
no_license
[ { "docstring": ":type nums: List[int] :type k: int :rtype: int", "name": "smallestDistancePair", "signature": "def smallestDistancePair(self, nums, k)" }, { "docstring": "Count the total number of pair distance which is smaller than val", "name": "count", "signature": "def count(self, nu...
2
stack_v2_sparse_classes_30k_train_006006
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def smallestDistancePair(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def count(self, nums, val): Count the total number of pair distance which is smaller tha...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def smallestDistancePair(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def count(self, nums, val): Count the total number of pair distance which is smaller tha...
0127190b27862ec7e7f4f2fcce5ce958d480cdac
<|skeleton|> class Solution: def smallestDistancePair(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_0|> def count(self, nums, val): """Count the total number of pair distance which is smaller than val""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def smallestDistancePair(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" """ [1,1,3,4,5,7,7,9] """ nums.sort() lo, hi = (0, nums[-1] - nums[0]) self.count(nums, 4) while lo < hi: mid = (h...
the_stack_v2_python_sparse
719.find-k-th-smallest-pair-distance.py
Iverance/leetcode
train
0
584d61b0847c65baca43054c5189a65d7b5100d3
[ "self.path = path\nself.name = path.split('.')[-1]\nself.cls = None", "if not self.cls:\n self.cls = _istring(self.path)\nreturn self.cls()" ]
<|body_start_0|> self.path = path self.name = path.split('.')[-1] self.cls = None <|end_body_0|> <|body_start_1|> if not self.cls: self.cls = _istring(self.path) return self.cls() <|end_body_1|>
Handles lazily importing and instantiating a class.
_lazy
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _lazy: """Handles lazily importing and instantiating a class.""" def __init__(self, path): """Specify the path to the class to lazily import and instantiate.""" <|body_0|> def __call__(self): """Import the specified class and return a new instantiation of it.""" ...
stack_v2_sparse_classes_36k_train_012368
1,315
no_license
[ { "docstring": "Specify the path to the class to lazily import and instantiate.", "name": "__init__", "signature": "def __init__(self, path)" }, { "docstring": "Import the specified class and return a new instantiation of it.", "name": "__call__", "signature": "def __call__(self)" } ]
2
stack_v2_sparse_classes_30k_train_008791
Implement the Python class `_lazy` described below. Class description: Handles lazily importing and instantiating a class. Method signatures and docstrings: - def __init__(self, path): Specify the path to the class to lazily import and instantiate. - def __call__(self): Import the specified class and return a new ins...
Implement the Python class `_lazy` described below. Class description: Handles lazily importing and instantiating a class. Method signatures and docstrings: - def __init__(self, path): Specify the path to the class to lazily import and instantiate. - def __call__(self): Import the specified class and return a new ins...
40aeb38397041d042b7497c6090d75a03d751dd6
<|skeleton|> class _lazy: """Handles lazily importing and instantiating a class.""" def __init__(self, path): """Specify the path to the class to lazily import and instantiate.""" <|body_0|> def __call__(self): """Import the specified class and return a new instantiation of it.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _lazy: """Handles lazily importing and instantiating a class.""" def __init__(self, path): """Specify the path to the class to lazily import and instantiate.""" self.path = path self.name = path.split('.')[-1] self.cls = None def __call__(self): """Import the ...
the_stack_v2_python_sparse
lib/LazyControllerLoader.py
dound/CraigNotes
train
0
f8dec2f4fdb7a9faf91673eef84a5716bb3fcd26
[ "self.dynamic = True\nself.type = 'DynamicMetadataTree'\nMetadataTree.__init__(self, rootName)\nself.pivotParam = pivotParam", "pivotVal = float(pivotVal)\npNode = self._findPivot(root, pivotVal)\ntNode = MetadataTree._findTarget(self, pNode, target)\nreturn tNode", "found = False\nfor child in root:\n if ch...
<|body_start_0|> self.dynamic = True self.type = 'DynamicMetadataTree' MetadataTree.__init__(self, rootName) self.pivotParam = pivotParam <|end_body_0|> <|body_start_1|> pivotVal = float(pivotVal) pNode = self._findPivot(root, pivotVal) tNode = MetadataTree._find...
Class for construction of metadata xml trees used in data objects. Usually contains summary data such as that produced by postprocessor models. Two types of tree exist: dynamic and static. See RAVEN Output type of Files object.
DynamicMetadataTree
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DynamicMetadataTree: """Class for construction of metadata xml trees used in data objects. Usually contains summary data such as that produced by postprocessor models. Two types of tree exist: dynamic and static. See RAVEN Output type of Files object.""" def __init__(self, rootName, pivotPar...
stack_v2_sparse_classes_36k_train_012369
36,827
permissive
[ { "docstring": "Constructor. @ In, rootName, str, root of tree if provided @ In, pivotParam, str, pivot variable @ Out, None", "name": "__init__", "signature": "def __init__(self, rootName, pivotParam)" }, { "docstring": "Used to find target node. Extension of base class method for Dynamic mode ...
3
null
Implement the Python class `DynamicMetadataTree` described below. Class description: Class for construction of metadata xml trees used in data objects. Usually contains summary data such as that produced by postprocessor models. Two types of tree exist: dynamic and static. See RAVEN Output type of Files object. Metho...
Implement the Python class `DynamicMetadataTree` described below. Class description: Class for construction of metadata xml trees used in data objects. Usually contains summary data such as that produced by postprocessor models. Two types of tree exist: dynamic and static. See RAVEN Output type of Files object. Metho...
2b16e7aa3325fe84cab2477947a951414c635381
<|skeleton|> class DynamicMetadataTree: """Class for construction of metadata xml trees used in data objects. Usually contains summary data such as that produced by postprocessor models. Two types of tree exist: dynamic and static. See RAVEN Output type of Files object.""" def __init__(self, rootName, pivotPar...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DynamicMetadataTree: """Class for construction of metadata xml trees used in data objects. Usually contains summary data such as that produced by postprocessor models. Two types of tree exist: dynamic and static. See RAVEN Output type of Files object.""" def __init__(self, rootName, pivotParam): ...
the_stack_v2_python_sparse
ravenframework/utils/TreeStructure.py
idaholab/raven
train
201
4046811e93de72963611a2fb2572f66c84fbd7f4
[ "db = getUtility(IDatabase, name='variation.stockdatabase')\nconnection = db.connection\nstatement = sql.select([PhenotypeMethod.c.id, PhenotypeMethod.c.short_name], distinct=True)\nresults = connection.execute(statement).fetchall()\n\"\\n\\t\\treturn [ dict(film_code=film.film_code,\\n\\t\\t\\t\\t\\t url=film.get...
<|body_start_0|> db = getUtility(IDatabase, name='variation.stockdatabase') connection = db.connection statement = sql.select([PhenotypeMethod.c.id, PhenotypeMethod.c.short_name], distinct=True) results = connection.execute(statement).fetchall() "\n\t\treturn [ dict(film_code=fil...
Find phenotype in db
PhenotypeLocator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PhenotypeLocator: """Find phenotype in db""" def get_phenotype_method_id_ls(self): """Return a list of all films showing at the particular ICinema between the specified dates. Returns a list of dictionaries with keys 'film_code', 'url', 'title' and 'summary'.""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_012370
6,707
no_license
[ { "docstring": "Return a list of all films showing at the particular ICinema between the specified dates. Returns a list of dictionaries with keys 'film_code', 'url', 'title' and 'summary'.", "name": "get_phenotype_method_id_ls", "signature": "def get_phenotype_method_id_ls(self)" }, { "docstrin...
2
null
Implement the Python class `PhenotypeLocator` described below. Class description: Find phenotype in db Method signatures and docstrings: - def get_phenotype_method_id_ls(self): Return a list of all films showing at the particular ICinema between the specified dates. Returns a list of dictionaries with keys 'film_code...
Implement the Python class `PhenotypeLocator` described below. Class description: Find phenotype in db Method signatures and docstrings: - def get_phenotype_method_id_ls(self): Return a list of all films showing at the particular ICinema between the specified dates. Returns a list of dictionaries with keys 'film_code...
7b402496aae81665e6a915b5021b94d56e034c9d
<|skeleton|> class PhenotypeLocator: """Find phenotype in db""" def get_phenotype_method_id_ls(self): """Return a list of all films showing at the particular ICinema between the specified dates. Returns a list of dictionaries with keys 'film_code', 'url', 'title' and 'summary'.""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PhenotypeLocator: """Find phenotype in db""" def get_phenotype_method_id_ls(self): """Return a list of all films showing at the particular ICinema between the specified dates. Returns a list of dictionaries with keys 'film_code', 'url', 'title' and 'summary'.""" db = getUtility(IDatabase,...
the_stack_v2_python_sparse
variation/trunk/web_interface/Variation/Products/Variation/dbphenotype.py
polyactis/repos
train
1
218be082072ea0834c7c206ec2895abdcfb895f6
[ "desc = self.db.desc\noutfit_list = []\nfor garment in get_worn_clothes(self, exclude_covered=True):\n wearstyle = garment.db.worn\n if type(wearstyle) is str:\n outfit_list.append(f'{garment.name} {wearstyle}')\n else:\n outfit_list.append(garment.name)\nif outfit_list:\n outfit = f'{self...
<|body_start_0|> desc = self.db.desc outfit_list = [] for garment in get_worn_clothes(self, exclude_covered=True): wearstyle = garment.db.worn if type(wearstyle) is str: outfit_list.append(f'{garment.name} {wearstyle}') else: ou...
Character that displays worn clothing when looked at. You can also just copy the return_appearance hook defined below to your own game's character typeclass.
ClothedCharacter
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClothedCharacter: """Character that displays worn clothing when looked at. You can also just copy the return_appearance hook defined below to your own game's character typeclass.""" def get_display_desc(self, looker, **kwargs): """Get the 'desc' component of the object description. C...
stack_v2_sparse_classes_36k_train_012371
24,575
permissive
[ { "docstring": "Get the 'desc' component of the object description. Called by `return_appearance`. Args: looker (Object): Object doing the looking. **kwargs: Arbitrary data for use when overriding. Returns: str: The desc display string.", "name": "get_display_desc", "signature": "def get_display_desc(se...
2
null
Implement the Python class `ClothedCharacter` described below. Class description: Character that displays worn clothing when looked at. You can also just copy the return_appearance hook defined below to your own game's character typeclass. Method signatures and docstrings: - def get_display_desc(self, looker, **kwarg...
Implement the Python class `ClothedCharacter` described below. Class description: Character that displays worn clothing when looked at. You can also just copy the return_appearance hook defined below to your own game's character typeclass. Method signatures and docstrings: - def get_display_desc(self, looker, **kwarg...
b3ca58b5c1325a3bf57051dfe23560a08d2947b7
<|skeleton|> class ClothedCharacter: """Character that displays worn clothing when looked at. You can also just copy the return_appearance hook defined below to your own game's character typeclass.""" def get_display_desc(self, looker, **kwargs): """Get the 'desc' component of the object description. C...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClothedCharacter: """Character that displays worn clothing when looked at. You can also just copy the return_appearance hook defined below to your own game's character typeclass.""" def get_display_desc(self, looker, **kwargs): """Get the 'desc' component of the object description. Called by `ret...
the_stack_v2_python_sparse
evennia/contrib/game_systems/clothing/clothing.py
evennia/evennia
train
1,781
5984271ee7cd364ff3b41be0b4c8a6b8522d13b8
[ "post_body = json.dumps({'security_group_default_rule': kwargs})\nurl = 'os-security-group-default-rules'\nresp, body = self.post(url, post_body)\nbody = json.loads(body)\nself.validate_response(schema.create_get_security_group_default_rule, resp, body)\nreturn rest_client.ResponseBody(resp, body)", "resp, body =...
<|body_start_0|> post_body = json.dumps({'security_group_default_rule': kwargs}) url = 'os-security-group-default-rules' resp, body = self.post(url, post_body) body = json.loads(body) self.validate_response(schema.create_get_security_group_default_rule, resp, body) return...
SecurityGroupDefaultRulesClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SecurityGroupDefaultRulesClient: def create_security_default_group_rule(self, **kwargs): """Create security group default rule. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#create-default-security-group-r...
stack_v2_sparse_classes_36k_train_012372
2,984
permissive
[ { "docstring": "Create security group default rule. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#create-default-security-group-rule", "name": "create_security_default_group_rule", "signature": "def create_security_defaul...
4
null
Implement the Python class `SecurityGroupDefaultRulesClient` described below. Class description: Implement the SecurityGroupDefaultRulesClient class. Method signatures and docstrings: - def create_security_default_group_rule(self, **kwargs): Create security group default rule. For a full list of available parameters,...
Implement the Python class `SecurityGroupDefaultRulesClient` described below. Class description: Implement the SecurityGroupDefaultRulesClient class. Method signatures and docstrings: - def create_security_default_group_rule(self, **kwargs): Create security group default rule. For a full list of available parameters,...
3932a799e620a20d7abf7b89e21b520683a1809b
<|skeleton|> class SecurityGroupDefaultRulesClient: def create_security_default_group_rule(self, **kwargs): """Create security group default rule. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#create-default-security-group-r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SecurityGroupDefaultRulesClient: def create_security_default_group_rule(self, **kwargs): """Create security group default rule. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#create-default-security-group-rule""" ...
the_stack_v2_python_sparse
tempest/lib/services/compute/security_group_default_rules_client.py
openstack/tempest
train
270
750b447436090e8c0fb0557f14b8f50704e6aa59
[ "self.logger = get_logger(log_to_screen)\nself._factory = ServerFactory()\nself._factory.protocol = Worker\nself._factory.logger = self.logger\nself._factory.protocol.parser = parser()\nself._port = port\nself._reactor = SelectReactor()\nself._reactor.listenTCP(port, self._factory)\nself._resource_manager = Manager...
<|body_start_0|> self.logger = get_logger(log_to_screen) self._factory = ServerFactory() self._factory.protocol = Worker self._factory.logger = self.logger self._factory.protocol.parser = parser() self._port = port self._reactor = SelectReactor() self._rea...
Resource manager server.
ResourceManagerServer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResourceManagerServer: """Resource manager server.""" def __init__(self, port=RESOURCE_MANAGER_PORT, parser=DEFAULT_PARSER, log_to_screen=True): """Initialize the resource manager server. Args: port (number): client listener port. parser (object): messages parser of type `AbstractPar...
stack_v2_sparse_classes_36k_train_012373
2,498
permissive
[ { "docstring": "Initialize the resource manager server. Args: port (number): client listener port. parser (object): messages parser of type `AbstractParser`. log_to_screen (bool): Enable log prints to screen.", "name": "__init__", "signature": "def __init__(self, port=RESOURCE_MANAGER_PORT, parser=DEFAU...
3
stack_v2_sparse_classes_30k_train_013578
Implement the Python class `ResourceManagerServer` described below. Class description: Resource manager server. Method signatures and docstrings: - def __init__(self, port=RESOURCE_MANAGER_PORT, parser=DEFAULT_PARSER, log_to_screen=True): Initialize the resource manager server. Args: port (number): client listener po...
Implement the Python class `ResourceManagerServer` described below. Class description: Resource manager server. Method signatures and docstrings: - def __init__(self, port=RESOURCE_MANAGER_PORT, parser=DEFAULT_PARSER, log_to_screen=True): Initialize the resource manager server. Args: port (number): client listener po...
746fdc07c4f8de7f98c6ab7fa1d5c95dcadbf6dc
<|skeleton|> class ResourceManagerServer: """Resource manager server.""" def __init__(self, port=RESOURCE_MANAGER_PORT, parser=DEFAULT_PARSER, log_to_screen=True): """Initialize the resource manager server. Args: port (number): client listener port. parser (object): messages parser of type `AbstractPar...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResourceManagerServer: """Resource manager server.""" def __init__(self, port=RESOURCE_MANAGER_PORT, parser=DEFAULT_PARSER, log_to_screen=True): """Initialize the resource manager server. Args: port (number): client listener port. parser (object): messages parser of type `AbstractParser`. log_to_...
the_stack_v2_python_sparse
src/rotest/management/server/main.py
IamShobe/rotest
train
3
77f53bbafd788a02cb176f60090420a83104146f
[ "if 'pow' not in conf['feature']:\n raise Exception('expecting feature to be in power domain')\nself.comp = feature_computer_factory.factory(conf['feature'])(conf)\nself.segment_lengths = segment_lengths\nself.dim = self.comp.get_dim()\nself.nontime_dims = [self.dim]\nsuper(IdealRatioProcessor, self).__init__(co...
<|body_start_0|> if 'pow' not in conf['feature']: raise Exception('expecting feature to be in power domain') self.comp = feature_computer_factory.factory(conf['feature'])(conf) self.segment_lengths = segment_lengths self.dim = self.comp.get_dim() self.nontime_dims = [...
a processor for audio files, this will compute the ideal ratio masks
IdealRatioProcessor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IdealRatioProcessor: """a processor for audio files, this will compute the ideal ratio masks""" def __init__(self, conf, segment_lengths): """IdealRatioProcessor constructor Args: conf: IdealRatioProcessor configuration as a dict of strings segment_lengths: A list containing the desi...
stack_v2_sparse_classes_36k_train_012374
3,843
permissive
[ { "docstring": "IdealRatioProcessor constructor Args: conf: IdealRatioProcessor configuration as a dict of strings segment_lengths: A list containing the desired lengths of segments. Possibly multiple segment lengths", "name": "__init__", "signature": "def __init__(self, conf, segment_lengths)" }, {...
3
null
Implement the Python class `IdealRatioProcessor` described below. Class description: a processor for audio files, this will compute the ideal ratio masks Method signatures and docstrings: - def __init__(self, conf, segment_lengths): IdealRatioProcessor constructor Args: conf: IdealRatioProcessor configuration as a di...
Implement the Python class `IdealRatioProcessor` described below. Class description: a processor for audio files, this will compute the ideal ratio masks Method signatures and docstrings: - def __init__(self, conf, segment_lengths): IdealRatioProcessor constructor Args: conf: IdealRatioProcessor configuration as a di...
5e862cbf846d45b8a317f87588533f3fde9f0726
<|skeleton|> class IdealRatioProcessor: """a processor for audio files, this will compute the ideal ratio masks""" def __init__(self, conf, segment_lengths): """IdealRatioProcessor constructor Args: conf: IdealRatioProcessor configuration as a dict of strings segment_lengths: A list containing the desi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IdealRatioProcessor: """a processor for audio files, this will compute the ideal ratio masks""" def __init__(self, conf, segment_lengths): """IdealRatioProcessor constructor Args: conf: IdealRatioProcessor configuration as a dict of strings segment_lengths: A list containing the desired lengths o...
the_stack_v2_python_sparse
nabu/processing/processors/ideal_ratio_processor.py
JeroenZegers/Nabu-MSSS
train
19
5f74d2d9173fb1ddd102625fc8f122dca8d7b73e
[ "self.script = script\nself.example_command = example_command\nself.searchtext = 'output'", "opt_dict = parse_example_command(self.example_command)\noutputs = {}\nfor key, value in opt_dict.iteritems():\n if self.searchtext in key:\n for i, line in enumerate(self.script):\n line = line.strip(...
<|body_start_0|> self.script = script self.example_command = example_command self.searchtext = 'output' <|end_body_0|> <|body_start_1|> opt_dict = parse_example_command(self.example_command) outputs = {} for key, value in opt_dict.iteritems(): if self.searcht...
Output class for parsing outputs.
Output
[ "CC-BY-2.5", "AFL-2.1", "AFL-3.0", "CC-BY-3.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Output: """Output class for parsing outputs.""" def __init__(self, script, example_command): """Initialize Input with searchtext - output.""" <|body_0|> def find_outputs(self): """Find outputs in example command.""" <|body_1|> <|end_skeleton|> <|body_st...
stack_v2_sparse_classes_36k_train_012375
5,433
permissive
[ { "docstring": "Initialize Input with searchtext - output.", "name": "__init__", "signature": "def __init__(self, script, example_command)" }, { "docstring": "Find outputs in example command.", "name": "find_outputs", "signature": "def find_outputs(self)" } ]
2
null
Implement the Python class `Output` described below. Class description: Output class for parsing outputs. Method signatures and docstrings: - def __init__(self, script, example_command): Initialize Input with searchtext - output. - def find_outputs(self): Find outputs in example command.
Implement the Python class `Output` described below. Class description: Output class for parsing outputs. Method signatures and docstrings: - def __init__(self, script, example_command): Initialize Input with searchtext - output. - def find_outputs(self): Find outputs in example command. <|skeleton|> class Output: ...
063bf0dca5d465466aefa77edaf47df12c4ff932
<|skeleton|> class Output: """Output class for parsing outputs.""" def __init__(self, script, example_command): """Initialize Input with searchtext - output.""" <|body_0|> def find_outputs(self): """Find outputs in example command.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Output: """Output class for parsing outputs.""" def __init__(self, script, example_command): """Initialize Input with searchtext - output.""" self.script = script self.example_command = example_command self.searchtext = 'output' def find_outputs(self): """Find...
the_stack_v2_python_sparse
.venv/lib/python2.7/site-packages/planemo/rscript_parse.py
maumauleon/galaxy-irri-dev
train
1
9dc70d2f0804af2bafa3c0e5873b1f2714d54b22
[ "self.driver.get(home_url)\nhome_page_title_actual = self.driver.get_title()\nhome_page_title_expected = '二手车市场_二手车交易市场_二手车平台-淘车网'\ntt_check.assertEqual(home_page_title_actual, home_page_title_expected, '页面title期望是%s,实际是%s' % (home_page_title_expected, home_page_title_actual))", "self.driver.get(home_url)\nads = ...
<|body_start_0|> self.driver.get(home_url) home_page_title_actual = self.driver.get_title() home_page_title_expected = '二手车市场_二手车交易市场_二手车平台-淘车网' tt_check.assertEqual(home_page_title_actual, home_page_title_expected, '页面title期望是%s,实际是%s' % (home_page_title_expected, home_page_title_actual...
AD
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AD: def test_title(self): """测试首页Title显示是否正确""" <|body_0|> def test_ad_displayed(self): """测试广告位图片请求是否正常""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.driver.get(home_url) home_page_title_actual = self.driver.get_title() home_...
stack_v2_sparse_classes_36k_train_012376
2,686
no_license
[ { "docstring": "测试首页Title显示是否正确", "name": "test_title", "signature": "def test_title(self)" }, { "docstring": "测试广告位图片请求是否正常", "name": "test_ad_displayed", "signature": "def test_ad_displayed(self)" } ]
2
stack_v2_sparse_classes_30k_train_013146
Implement the Python class `AD` described below. Class description: Implement the AD class. Method signatures and docstrings: - def test_title(self): 测试首页Title显示是否正确 - def test_ad_displayed(self): 测试广告位图片请求是否正常
Implement the Python class `AD` described below. Class description: Implement the AD class. Method signatures and docstrings: - def test_title(self): 测试首页Title显示是否正确 - def test_ad_displayed(self): 测试广告位图片请求是否正常 <|skeleton|> class AD: def test_title(self): """测试首页Title显示是否正确""" <|body_0|> de...
204856bd33c06d25f2970eba13799db75d4fd4fe
<|skeleton|> class AD: def test_title(self): """测试首页Title显示是否正确""" <|body_0|> def test_ad_displayed(self): """测试广告位图片请求是否正常""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AD: def test_title(self): """测试首页Title显示是否正确""" self.driver.get(home_url) home_page_title_actual = self.driver.get_title() home_page_title_expected = '二手车市场_二手车交易市场_二手车平台-淘车网' tt_check.assertEqual(home_page_title_actual, home_page_title_expected, '页面title期望是%s,实际是%s' % ...
the_stack_v2_python_sparse
mc/taochePC/test_homepage/test_ad.py
boeai/mc
train
0
371a8df8b933dac8f41e341f88e33f762315a5bc
[ "allure.dynamic.title('Test with empty string')\nallure.dynamic.severity(allure.severity_level.NORMAL)\nallure.dynamic.description_html('<h3>Codewars badge:</h3><img src=\"https://www.codewars.com/users/myFirstCode/badges/large\"><h3>Test Description:</h3><p></p>')\nwith allure.step('Pass empty string and verify th...
<|body_start_0|> allure.dynamic.title('Test with empty string') allure.dynamic.severity(allure.severity_level.NORMAL) allure.dynamic.description_html('<h3>Codewars badge:</h3><img src="https://www.codewars.com/users/myFirstCode/badges/large"><h3>Test Description:</h3><p></p>') with allur...
Testing the solution for 'Reversed Strings' problem
ReversedStringsTestCase
[ "Unlicense", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReversedStringsTestCase: """Testing the solution for 'Reversed Strings' problem""" def test_reversed_strings_empty(self): """Test with empty string :return:""" <|body_0|> def test_reversed_strings_one_char(self): """Test with one char only :return:""" <|b...
stack_v2_sparse_classes_36k_train_012377
3,430
permissive
[ { "docstring": "Test with empty string :return:", "name": "test_reversed_strings_empty", "signature": "def test_reversed_strings_empty(self)" }, { "docstring": "Test with one char only :return:", "name": "test_reversed_strings_one_char", "signature": "def test_reversed_strings_one_char(s...
3
null
Implement the Python class `ReversedStringsTestCase` described below. Class description: Testing the solution for 'Reversed Strings' problem Method signatures and docstrings: - def test_reversed_strings_empty(self): Test with empty string :return: - def test_reversed_strings_one_char(self): Test with one char only :r...
Implement the Python class `ReversedStringsTestCase` described below. Class description: Testing the solution for 'Reversed Strings' problem Method signatures and docstrings: - def test_reversed_strings_empty(self): Test with empty string :return: - def test_reversed_strings_one_char(self): Test with one char only :r...
ba3ea81125b6082d867f0ae34c6c9be15e153966
<|skeleton|> class ReversedStringsTestCase: """Testing the solution for 'Reversed Strings' problem""" def test_reversed_strings_empty(self): """Test with empty string :return:""" <|body_0|> def test_reversed_strings_one_char(self): """Test with one char only :return:""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReversedStringsTestCase: """Testing the solution for 'Reversed Strings' problem""" def test_reversed_strings_empty(self): """Test with empty string :return:""" allure.dynamic.title('Test with empty string') allure.dynamic.severity(allure.severity_level.NORMAL) allure.dynam...
the_stack_v2_python_sparse
kyu_8/reversed_strings/test_reversed_strings.py
qamine-test/codewars
train
0
4c1b9f3afa733f560afcc33eb38b0baf69c2bf7c
[ "super(_SelfAttentionDecoderLayer, self).__init__(**kwargs)\nself.self_attention = transformer.MultiHeadAttention(num_heads, num_units, dropout=attention_dropout, name='masked_multi_head_attention')\nself.self_attention = transformer.TransformerLayerWrapper(self.self_attention, dropout, name='sub_layer_0')\nself.at...
<|body_start_0|> super(_SelfAttentionDecoderLayer, self).__init__(**kwargs) self.self_attention = transformer.MultiHeadAttention(num_heads, num_units, dropout=attention_dropout, name='masked_multi_head_attention') self.self_attention = transformer.TransformerLayerWrapper(self.self_attention, dro...
Implements one self-attention decoding layer.
_SelfAttentionDecoderLayer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _SelfAttentionDecoderLayer: """Implements one self-attention decoding layer.""" def __init__(self, num_units, num_heads, ffn_inner_dim, num_sources=1, dropout=0.1, attention_dropout=0.1, ffn_dropout=0.1, ffn_activation=tf.nn.relu, **kwargs): """Initializes the layer. Args: num_units:...
stack_v2_sparse_classes_36k_train_012378
18,943
permissive
[ { "docstring": "Initializes the layer. Args: num_units: The number of hidden units. num_heads: The number of heads in the multi-head attention. ffn_inner_dim: The number of units of the inner linear transformation in the feed forward layer. num_sources: The number of source contexts. dropout: The probability to...
2
stack_v2_sparse_classes_30k_train_007631
Implement the Python class `_SelfAttentionDecoderLayer` described below. Class description: Implements one self-attention decoding layer. Method signatures and docstrings: - def __init__(self, num_units, num_heads, ffn_inner_dim, num_sources=1, dropout=0.1, attention_dropout=0.1, ffn_dropout=0.1, ffn_activation=tf.nn...
Implement the Python class `_SelfAttentionDecoderLayer` described below. Class description: Implements one self-attention decoding layer. Method signatures and docstrings: - def __init__(self, num_units, num_heads, ffn_inner_dim, num_sources=1, dropout=0.1, attention_dropout=0.1, ffn_dropout=0.1, ffn_activation=tf.nn...
5a9b2e11da04a9777ec6ac4f7b54d076bea040ea
<|skeleton|> class _SelfAttentionDecoderLayer: """Implements one self-attention decoding layer.""" def __init__(self, num_units, num_heads, ffn_inner_dim, num_sources=1, dropout=0.1, attention_dropout=0.1, ffn_dropout=0.1, ffn_activation=tf.nn.relu, **kwargs): """Initializes the layer. Args: num_units:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _SelfAttentionDecoderLayer: """Implements one self-attention decoding layer.""" def __init__(self, num_units, num_heads, ffn_inner_dim, num_sources=1, dropout=0.1, attention_dropout=0.1, ffn_dropout=0.1, ffn_activation=tf.nn.relu, **kwargs): """Initializes the layer. Args: num_units: The number o...
the_stack_v2_python_sparse
opennmt/decoders/self_attention_decoder.py
Parkchanjun/OpenNMT-tf
train
2
929dd5d67761b0c0e0e09fc561a0d68c87d28a29
[ "dirname = 'classifier'\nif extension is not None:\n dirname += '_{:s}'.format(str(extension))\npath = join(dirpath, dirname)\nif not exists(path):\n mkdir(path)\nif data:\n np.save(join(path, 'values.npy'), self._values)\nio = IO()\nio.write_json(join(path, 'parameters.json'), self.parameters)\nif image:\...
<|body_start_0|> dirname = 'classifier' if extension is not None: dirname += '_{:s}'.format(str(extension)) path = join(dirpath, dirname) if not exists(path): mkdir(path) if data: np.save(join(path, 'values.npy'), self._values) io = IO(...
Methods for saving and loading classifier objects.
ClassifierIO
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClassifierIO: """Methods for saving and loading classifier objects.""" def save(self, dirpath, data=False, image=True, extension=None, **kwargs): """Save classifier to specified path. Args: dirpath (str) - directory in which classifier is to be saved data (bool) - if True, save train...
stack_v2_sparse_classes_36k_train_012379
9,044
permissive
[ { "docstring": "Save classifier to specified path. Args: dirpath (str) - directory in which classifier is to be saved data (bool) - if True, save training data image (bool) - if True, save labeled histogram image extension (str) - directory name extension kwargs: keyword arguments for image rendering", "nam...
2
stack_v2_sparse_classes_30k_train_013930
Implement the Python class `ClassifierIO` described below. Class description: Methods for saving and loading classifier objects. Method signatures and docstrings: - def save(self, dirpath, data=False, image=True, extension=None, **kwargs): Save classifier to specified path. Args: dirpath (str) - directory in which cl...
Implement the Python class `ClassifierIO` described below. Class description: Methods for saving and loading classifier objects. Method signatures and docstrings: - def save(self, dirpath, data=False, image=True, extension=None, **kwargs): Save classifier to specified path. Args: dirpath (str) - directory in which cl...
4a622c3f5fed4456c3b9240f5a96428789fde9bd
<|skeleton|> class ClassifierIO: """Methods for saving and loading classifier objects.""" def save(self, dirpath, data=False, image=True, extension=None, **kwargs): """Save classifier to specified path. Args: dirpath (str) - directory in which classifier is to be saved data (bool) - if True, save train...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClassifierIO: """Methods for saving and loading classifier objects.""" def save(self, dirpath, data=False, image=True, extension=None, **kwargs): """Save classifier to specified path. Args: dirpath (str) - directory in which classifier is to be saved data (bool) - if True, save training data imag...
the_stack_v2_python_sparse
flyqma/annotation/classification/classifiers.py
sbernasek/flyqma
train
1
1d7d8ba23a35df2fbd9c6d4bcdc9132f7ae659ec
[ "assert num_bases == len(init_weights)\nself._num_bases = int(num_bases)\nself._converge_epsilon = float(converge_epsilon)\nself._init_weights = Mat([[float(i)] for i in init_weights])\nself._data = []\nself._input = []\nself._label = []\nwith open(file_path, 'r') as file_:\n for line in file_.readlines():\n ...
<|body_start_0|> assert num_bases == len(init_weights) self._num_bases = int(num_bases) self._converge_epsilon = float(converge_epsilon) self._init_weights = Mat([[float(i)] for i in init_weights]) self._data = [] self._input = [] self._label = [] with ope...
Newton's Method Optimization
NewtonMethod
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NewtonMethod: """Newton's Method Optimization""" def __init__(self, file_path, num_bases, converge_epsilon, init_weights): """Get polynomail regression result by Newton's Method Optimization Args ---- file_path : str, path to dataset num_bases : int, degree of polynomial converge_eps...
stack_v2_sparse_classes_36k_train_012380
3,193
no_license
[ { "docstring": "Get polynomail regression result by Newton's Method Optimization Args ---- file_path : str, path to dataset num_bases : int, degree of polynomial converge_epsilon : float, the condition of convergence init_weights : list, shape=[num_bases,] the parameters of polynomial", "name": "__init__", ...
4
stack_v2_sparse_classes_30k_train_004686
Implement the Python class `NewtonMethod` described below. Class description: Newton's Method Optimization Method signatures and docstrings: - def __init__(self, file_path, num_bases, converge_epsilon, init_weights): Get polynomail regression result by Newton's Method Optimization Args ---- file_path : str, path to d...
Implement the Python class `NewtonMethod` described below. Class description: Newton's Method Optimization Method signatures and docstrings: - def __init__(self, file_path, num_bases, converge_epsilon, init_weights): Get polynomail regression result by Newton's Method Optimization Args ---- file_path : str, path to d...
b87c26e215b4ae0358d5cb79e685711691f4ced2
<|skeleton|> class NewtonMethod: """Newton's Method Optimization""" def __init__(self, file_path, num_bases, converge_epsilon, init_weights): """Get polynomail regression result by Newton's Method Optimization Args ---- file_path : str, path to dataset num_bases : int, degree of polynomial converge_eps...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NewtonMethod: """Newton's Method Optimization""" def __init__(self, file_path, num_bases, converge_epsilon, init_weights): """Get polynomail regression result by Newton's Method Optimization Args ---- file_path : str, path to dataset num_bases : int, degree of polynomial converge_epsilon : float,...
the_stack_v2_python_sparse
HW1/Newton.py
chychen/NCTU_ML_2018
train
2
63d9321f25894963ef75a18b8cac17fdd6ccb80a
[ "model = User\nname = 'Users'\nsuper().__init__(model=model, collection_name=name)\nself.__dog_owner_repository = dog_owner_repository", "users = list()\nowners = self.__dog_owner_repository.search(f'dog_id=={dog_id}')\nfor dog_owner in owners.to_list():\n try:\n user = self.read(dog_owner.owner_id)\n ...
<|body_start_0|> model = User name = 'Users' super().__init__(model=model, collection_name=name) self.__dog_owner_repository = dog_owner_repository <|end_body_0|> <|body_start_1|> users = list() owners = self.__dog_owner_repository.search(f'dog_id=={dog_id}') for...
User repository.
UserRepository
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserRepository: """User repository.""" def __init__(self, dog_owner_repository): """Initialize user repository.""" <|body_0|> def read_owners_of_dog(self, dog_id): """Get dogs associated with this user_id.""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_012381
925
no_license
[ { "docstring": "Initialize user repository.", "name": "__init__", "signature": "def __init__(self, dog_owner_repository)" }, { "docstring": "Get dogs associated with this user_id.", "name": "read_owners_of_dog", "signature": "def read_owners_of_dog(self, dog_id)" } ]
2
stack_v2_sparse_classes_30k_train_019053
Implement the Python class `UserRepository` described below. Class description: User repository. Method signatures and docstrings: - def __init__(self, dog_owner_repository): Initialize user repository. - def read_owners_of_dog(self, dog_id): Get dogs associated with this user_id.
Implement the Python class `UserRepository` described below. Class description: User repository. Method signatures and docstrings: - def __init__(self, dog_owner_repository): Initialize user repository. - def read_owners_of_dog(self, dog_id): Get dogs associated with this user_id. <|skeleton|> class UserRepository: ...
129dc7f8213fb3112c35b1551d9ed3d8a14b7fb5
<|skeleton|> class UserRepository: """User repository.""" def __init__(self, dog_owner_repository): """Initialize user repository.""" <|body_0|> def read_owners_of_dog(self, dog_id): """Get dogs associated with this user_id.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserRepository: """User repository.""" def __init__(self, dog_owner_repository): """Initialize user repository.""" model = User name = 'Users' super().__init__(model=model, collection_name=name) self.__dog_owner_repository = dog_owner_repository def read_owner...
the_stack_v2_python_sparse
hugbunadarfr_backend/src/app/repository/repositories/user_repository.py
birna17/veff_hugb
train
0
2384517a4c9d28ca67fad3d19bc1db42df35ea2c
[ "response = session.query(AbilityModel.ID)\nresponse = response.filter(AbilityModel.HeroID == hero_id).all()\nif len(response) == 0:\n report = 'No abilities for this HeroID == {}'.format(hero_id)\n raise ValueError(report)\nmembers_ = [cls.member_type(a[0], patch=patch) for a in response]\nreturn cls(members...
<|body_start_0|> response = session.query(AbilityModel.ID) response = response.filter(AbilityModel.HeroID == hero_id).all() if len(response) == 0: report = 'No abilities for this HeroID == {}'.format(hero_id) raise ValueError(report) members_ = [cls.member_type(a[...
Any amount of abilities as one substance.
Abilities
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Abilities: """Any amount of abilities as one substance.""" def from_hero_id(cls, hero_id, patch=''): """Adds to members all abilities of the hero with `hero_id`.""" <|body_0|> def all(cls): """Creates Abilities object with all heroes' abilities in the game.""" ...
stack_v2_sparse_classes_36k_train_012382
1,392
permissive
[ { "docstring": "Adds to members all abilities of the hero with `hero_id`.", "name": "from_hero_id", "signature": "def from_hero_id(cls, hero_id, patch='')" }, { "docstring": "Creates Abilities object with all heroes' abilities in the game.", "name": "all", "signature": "def all(cls)" }...
2
stack_v2_sparse_classes_30k_train_014345
Implement the Python class `Abilities` described below. Class description: Any amount of abilities as one substance. Method signatures and docstrings: - def from_hero_id(cls, hero_id, patch=''): Adds to members all abilities of the hero with `hero_id`. - def all(cls): Creates Abilities object with all heroes' abiliti...
Implement the Python class `Abilities` described below. Class description: Any amount of abilities as one substance. Method signatures and docstrings: - def from_hero_id(cls, hero_id, patch=''): Adds to members all abilities of the hero with `hero_id`. - def all(cls): Creates Abilities object with all heroes' abiliti...
23fc7072e734c6085a4f630a94998c268a423e20
<|skeleton|> class Abilities: """Any amount of abilities as one substance.""" def from_hero_id(cls, hero_id, patch=''): """Adds to members all abilities of the hero with `hero_id`.""" <|body_0|> def all(cls): """Creates Abilities object with all heroes' abilities in the game.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Abilities: """Any amount of abilities as one substance.""" def from_hero_id(cls, hero_id, patch=''): """Adds to members all abilities of the hero with `hero_id`.""" response = session.query(AbilityModel.ID) response = response.filter(AbilityModel.HeroID == hero_id).all() i...
the_stack_v2_python_sparse
atod/models/abilities.py
gasabr/AtoD
train
6
b7e27af93232c5796fac5c6476a8b4a654a90240
[ "repo_ref = registry_model.lookup_repository(namespace_name, repository_name)\nif repo_ref is None:\n raise NotFound()\nmanifest = registry_model.lookup_manifest_by_digest(repo_ref, manifestref)\nif manifest is None:\n raise NotFound()\nlabel = registry_model.get_manifest_label(manifest, labelid)\nif label is...
<|body_start_0|> repo_ref = registry_model.lookup_repository(namespace_name, repository_name) if repo_ref is None: raise NotFound() manifest = registry_model.lookup_manifest_by_digest(repo_ref, manifestref) if manifest is None: raise NotFound() label = reg...
Resource for managing the labels on a specific repository manifest.
ManageRepositoryManifestLabel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ManageRepositoryManifestLabel: """Resource for managing the labels on a specific repository manifest.""" def get(self, namespace_name, repository_name, manifestref, labelid): """Retrieves the label with the specific ID under the manifest.""" <|body_0|> def delete(self, n...
stack_v2_sparse_classes_36k_train_012383
10,731
permissive
[ { "docstring": "Retrieves the label with the specific ID under the manifest.", "name": "get", "signature": "def get(self, namespace_name, repository_name, manifestref, labelid)" }, { "docstring": "Deletes an existing label from a manifest.", "name": "delete", "signature": "def delete(sel...
2
stack_v2_sparse_classes_30k_train_010857
Implement the Python class `ManageRepositoryManifestLabel` described below. Class description: Resource for managing the labels on a specific repository manifest. Method signatures and docstrings: - def get(self, namespace_name, repository_name, manifestref, labelid): Retrieves the label with the specific ID under th...
Implement the Python class `ManageRepositoryManifestLabel` described below. Class description: Resource for managing the labels on a specific repository manifest. Method signatures and docstrings: - def get(self, namespace_name, repository_name, manifestref, labelid): Retrieves the label with the specific ID under th...
e400a0c22c5f89dd35d571654b13d262b1f6e3b3
<|skeleton|> class ManageRepositoryManifestLabel: """Resource for managing the labels on a specific repository manifest.""" def get(self, namespace_name, repository_name, manifestref, labelid): """Retrieves the label with the specific ID under the manifest.""" <|body_0|> def delete(self, n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ManageRepositoryManifestLabel: """Resource for managing the labels on a specific repository manifest.""" def get(self, namespace_name, repository_name, manifestref, labelid): """Retrieves the label with the specific ID under the manifest.""" repo_ref = registry_model.lookup_repository(nam...
the_stack_v2_python_sparse
endpoints/api/manifest.py
quay/quay
train
2,363
adb2ac5df13847ea6b3c15285f75b8ecd7e118a3
[ "try:\n import spur\nexcept ImportError:\n print('You need to install spur.')\n exit(1)\nQueueBase.__init__(self, max_jobs=max_jobs)\nself._qsub_command = qsub_command\nself._shell = spur.LocalShell()", "if task.get_traverse() is not False:\n return\njob = task.get_job()\ntid = task.get_tid()\nself._s...
<|body_start_0|> try: import spur except ImportError: print('You need to install spur.') exit(1) QueueBase.__init__(self, max_jobs=max_jobs) self._qsub_command = qsub_command self._shell = spur.LocalShell() <|end_body_0|> <|body_start_1|> ...
LocalQueue base class.
LocalQueueBase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LocalQueueBase: """LocalQueue base class.""" def __init__(self, max_jobs=None, qsub_command='qsub'): """Init method.""" <|body_0|> def submit(self, task): """Submit.""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: import spur ...
stack_v2_sparse_classes_36k_train_012384
10,513
no_license
[ { "docstring": "Init method.", "name": "__init__", "signature": "def __init__(self, max_jobs=None, qsub_command='qsub')" }, { "docstring": "Submit.", "name": "submit", "signature": "def submit(self, task)" } ]
2
stack_v2_sparse_classes_30k_train_010594
Implement the Python class `LocalQueueBase` described below. Class description: LocalQueue base class. Method signatures and docstrings: - def __init__(self, max_jobs=None, qsub_command='qsub'): Init method. - def submit(self, task): Submit.
Implement the Python class `LocalQueueBase` described below. Class description: LocalQueue base class. Method signatures and docstrings: - def __init__(self, max_jobs=None, qsub_command='qsub'): Init method. - def submit(self, task): Submit. <|skeleton|> class LocalQueueBase: """LocalQueue base class.""" de...
af5478080be86ad437f831c9895954d0fa0f17e2
<|skeleton|> class LocalQueueBase: """LocalQueue base class.""" def __init__(self, max_jobs=None, qsub_command='qsub'): """Init method.""" <|body_0|> def submit(self, task): """Submit.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LocalQueueBase: """LocalQueue base class.""" def __init__(self, max_jobs=None, qsub_command='qsub'): """Init method.""" try: import spur except ImportError: print('You need to install spur.') exit(1) QueueBase.__init__(self, max_jobs=max...
the_stack_v2_python_sparse
cogue/qsystem/queue.py
atztogo/cogue
train
12
642a58bca1175a1a8d6fb1df852720568e4c8709
[ "agent = Agent.query.filter_by(id=agent_id).first()\nif agent is None:\n return (jsonify(error='Agent %r not found' % agent_id), NOT_FOUND)\nout = []\nfor version in agent.software_versions:\n software_dict = {'software': version.software.software, 'version': version.version}\n out.append(software_dict)\nr...
<|body_start_0|> agent = Agent.query.filter_by(id=agent_id).first() if agent is None: return (jsonify(error='Agent %r not found' % agent_id), NOT_FOUND) out = [] for version in agent.software_versions: software_dict = {'software': version.software.software, 'versi...
SoftwareInAgentIndexAPI
[ "BSD-3-Clause", "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SoftwareInAgentIndexAPI: def get(self, agent_id): """A ``GET`` to this endpoint will return a list of all software versions available on this agent. .. http:get:: /api/v1/agents/<str:agent_id>/software/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/agents/bbf55143-f2b1-4c15-9d41-...
stack_v2_sparse_classes_36k_train_012385
40,281
permissive
[ { "docstring": "A ``GET`` to this endpoint will return a list of all software versions available on this agent. .. http:get:: /api/v1/agents/<str:agent_id>/software/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/agents/bbf55143-f2b1-4c15-9d41-139bd8057931/software/ HTTP/1.1 Accept: application/json **Re...
2
stack_v2_sparse_classes_30k_train_001469
Implement the Python class `SoftwareInAgentIndexAPI` described below. Class description: Implement the SoftwareInAgentIndexAPI class. Method signatures and docstrings: - def get(self, agent_id): A ``GET`` to this endpoint will return a list of all software versions available on this agent. .. http:get:: /api/v1/agent...
Implement the Python class `SoftwareInAgentIndexAPI` described below. Class description: Implement the SoftwareInAgentIndexAPI class. Method signatures and docstrings: - def get(self, agent_id): A ``GET`` to this endpoint will return a list of all software versions available on this agent. .. http:get:: /api/v1/agent...
ea04bbcb807eb669415c569417b4b1b68e75d29d
<|skeleton|> class SoftwareInAgentIndexAPI: def get(self, agent_id): """A ``GET`` to this endpoint will return a list of all software versions available on this agent. .. http:get:: /api/v1/agents/<str:agent_id>/software/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/agents/bbf55143-f2b1-4c15-9d41-...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SoftwareInAgentIndexAPI: def get(self, agent_id): """A ``GET`` to this endpoint will return a list of all software versions available on this agent. .. http:get:: /api/v1/agents/<str:agent_id>/software/ HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/agents/bbf55143-f2b1-4c15-9d41-139bd8057931/s...
the_stack_v2_python_sparse
pyfarm/master/api/agents.py
pyfarm/pyfarm-master
train
2
f57ab9dc9af422ca04c8b4014be0d0b5f43aa892
[ "with open('config.json') as config:\n settings = json.load(config)['Notifications']\nemail = MIMEMultipart()\nemail['From'] = settings['Sender']\nemail['To'] = receiver\nif 'test' in category:\n email, message = self.set_test(email, info)\nelif 'idle' in category:\n email, message = self.set_idle(email, i...
<|body_start_0|> with open('config.json') as config: settings = json.load(config)['Notifications'] email = MIMEMultipart() email['From'] = settings['Sender'] email['To'] = receiver if 'test' in category: email, message = self.set_test(email, info) ...
Module used to send notification emails which may include image attachments to a specified email address
Notifications
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Notifications: """Module used to send notification emails which may include image attachments to a specified email address""" def send(self, receiver, category, attachment_name='', info=None): """Construct the notification email by setting sending and receiving members and the text m...
stack_v2_sparse_classes_36k_train_012386
4,735
no_license
[ { "docstring": "Construct the notification email by setting sending and receiving members and the text message itself Attach any received attachments and finally send the email to the specified receiver address", "name": "send", "signature": "def send(self, receiver, category, attachment_name='', info=N...
5
stack_v2_sparse_classes_30k_train_018127
Implement the Python class `Notifications` described below. Class description: Module used to send notification emails which may include image attachments to a specified email address Method signatures and docstrings: - def send(self, receiver, category, attachment_name='', info=None): Construct the notification emai...
Implement the Python class `Notifications` described below. Class description: Module used to send notification emails which may include image attachments to a specified email address Method signatures and docstrings: - def send(self, receiver, category, attachment_name='', info=None): Construct the notification emai...
cdcdfad34691fb8434f67c69d2f8b037197028cc
<|skeleton|> class Notifications: """Module used to send notification emails which may include image attachments to a specified email address""" def send(self, receiver, category, attachment_name='', info=None): """Construct the notification email by setting sending and receiving members and the text m...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Notifications: """Module used to send notification emails which may include image attachments to a specified email address""" def send(self, receiver, category, attachment_name='', info=None): """Construct the notification email by setting sending and receiving members and the text message itself...
the_stack_v2_python_sparse
notifications.py
Spinarakk/defectmonitor
train
0
fa6deecde967815892cac53b61d6d4438ea78f10
[ "def helper(node):\n if node == None:\n return '#'\n return str(node.val) + '*' + helper(node.left) + helper(node.right)\nreturn helper(root)", "def helper(index):\n if data[index] == '#':\n return (None, index)\n word = ''\n while data[index] != '*':\n word += data[index]\n ...
<|body_start_0|> def helper(node): if node == None: return '#' return str(node.val) + '*' + helper(node.left) + helper(node.right) return helper(root) <|end_body_0|> <|body_start_1|> def helper(index): if data[index] == '#': re...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_012387
4,399
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
00fd1397b65c68a303fcf963db3e28cd35c1c003
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" def helper(node): if node == None: return '#' return str(node.val) + '*' + helper(node.left) + helper(node.right) return helper(root) ...
the_stack_v2_python_sparse
leetcode/449. Serialize and Deserialize BST.py
cuiy0006/Algorithms
train
0
dc7778ff12a2bcc5f6467c400da599fa05252de1
[ "try:\n data = explorer_config.ExplorerConfigModel.Get().to_dict()\n self.RenderJson(data)\nexcept Exception as err:\n self.RenderJson(data={error_fields.MESSAGE: err.message}, status=500)", "try:\n data = json.loads(self.request.body)\n explorer_config.ExplorerConfigModel.Update(data)\nexcept Exce...
<|body_start_0|> try: data = explorer_config.ExplorerConfigModel.Get().to_dict() self.RenderJson(data) except Exception as err: self.RenderJson(data={error_fields.MESSAGE: err.message}, status=500) <|end_body_0|> <|body_start_1|> try: data = json....
Http handler for getting the global config. Returns: JSON representation of the global config.
ConfigHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigHandler: """Http handler for getting the global config. Returns: JSON representation of the global config.""" def get(self): """Returns the global config.""" <|body_0|> def post(self): """Updates the global config based on the request body.""" <|bod...
stack_v2_sparse_classes_36k_train_012388
2,132
permissive
[ { "docstring": "Returns the global config.", "name": "get", "signature": "def get(self)" }, { "docstring": "Updates the global config based on the request body.", "name": "post", "signature": "def post(self)" } ]
2
null
Implement the Python class `ConfigHandler` described below. Class description: Http handler for getting the global config. Returns: JSON representation of the global config. Method signatures and docstrings: - def get(self): Returns the global config. - def post(self): Updates the global config based on the request b...
Implement the Python class `ConfigHandler` described below. Class description: Http handler for getting the global config. Returns: JSON representation of the global config. Method signatures and docstrings: - def get(self): Returns the global config. - def post(self): Updates the global config based on the request b...
9efa61015d50c25f6d753f0212ad3bf16876d496
<|skeleton|> class ConfigHandler: """Http handler for getting the global config. Returns: JSON representation of the global config.""" def get(self): """Returns the global config.""" <|body_0|> def post(self): """Updates the global config based on the request body.""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConfigHandler: """Http handler for getting the global config. Returns: JSON representation of the global config.""" def get(self): """Returns the global config.""" try: data = explorer_config.ExplorerConfigModel.Get().to_dict() self.RenderJson(data) except ...
the_stack_v2_python_sparse
server/perfkit/explorer/handlers/explorer_config.py
GoogleCloudPlatform/PerfKitExplorer
train
292
2e75f3f70ab13799d3b163d4f2873035a0de5839
[ "name = ''.join(filter(str.isalnum, label)).lower()\nif background_color is None:\n background_color = BACKGROUND_COLOR\nLabel.__init__(self, name, label, rect, background_color)\nself.left_click_callback = callback\nself.clicked_counter = 0\nself.redraw()\nreturn", "Label.redraw(self)\nself.image.lock()\npyga...
<|body_start_0|> name = ''.join(filter(str.isalnum, label)).lower() if background_color is None: background_color = BACKGROUND_COLOR Label.__init__(self, name, label, rect, background_color) self.left_click_callback = callback self.clicked_counter = 0 self.red...
A clickndrag plane which displays a text and reacts on mouse clicks. Additional attributes: Button.callback The callback function to be called upon clicking. Button.clicked_counter Counted down when the button is clicked and displays a different color
Button
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Button: """A clickndrag plane which displays a text and reacts on mouse clicks. Additional attributes: Button.callback The callback function to be called upon clicking. Button.clicked_counter Counted down when the button is clicked and displays a different color""" def __init__(self, label, ...
stack_v2_sparse_classes_36k_train_012389
27,668
permissive
[ { "docstring": "Initialise the Button. label is the Text to be written on the button. rect is an instance of pygame.Rect giving the dimensions. callback is the function to be called when the Button is clicked with the left mouse button.", "name": "__init__", "signature": "def __init__(self, label, rect,...
4
stack_v2_sparse_classes_30k_train_009544
Implement the Python class `Button` described below. Class description: A clickndrag plane which displays a text and reacts on mouse clicks. Additional attributes: Button.callback The callback function to be called upon clicking. Button.clicked_counter Counted down when the button is clicked and displays a different c...
Implement the Python class `Button` described below. Class description: A clickndrag plane which displays a text and reacts on mouse clicks. Additional attributes: Button.callback The callback function to be called upon clicking. Button.clicked_counter Counted down when the button is clicked and displays a different c...
c2fc3d4e9beedb8487cfa4bfa13bdf55ec36af97
<|skeleton|> class Button: """A clickndrag plane which displays a text and reacts on mouse clicks. Additional attributes: Button.callback The callback function to be called upon clicking. Button.clicked_counter Counted down when the button is clicked and displays a different color""" def __init__(self, label, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Button: """A clickndrag plane which displays a text and reacts on mouse clicks. Additional attributes: Button.callback The callback function to be called upon clicking. Button.clicked_counter Counted down when the button is clicked and displays a different color""" def __init__(self, label, rect, callbac...
the_stack_v2_python_sparse
reference_scripts/clickndrag-0.4.1/clickndrag/gui.py
stivosaurus/rpi-snippets
train
1
d48eaf3f2ca2f639f53e1be750b170bc47851085
[ "try:\n email = username\n user = self.user_class.objects.get(contact__email_addresses__email_address__iexact=email, contact__email_addresses__is_primary=True)\n if user.is_active and (user.check_password(password) or no_pass):\n return user\n return None\nexcept self.user_class.DoesNotExist:\n ...
<|body_start_0|> try: email = username user = self.user_class.objects.get(contact__email_addresses__email_address__iexact=email, contact__email_addresses__is_primary=True) if user.is_active and (user.check_password(password) or no_pass): return user ...
Authenticate a CustomUser with e-mail address instead of username.
EmailAuthenticationBackend
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmailAuthenticationBackend: """Authenticate a CustomUser with e-mail address instead of username.""" def authenticate(self, username=None, password=None, no_pass=False): """Check if the user is properly authenticated, either logging in by e-mail address and password or programmatical...
stack_v2_sparse_classes_36k_train_012390
1,808
no_license
[ { "docstring": "Check if the user is properly authenticated, either logging in by e-mail address and password or programmatically logged in (e.g. upon activation of account) using no_pass=True.", "name": "authenticate", "signature": "def authenticate(self, username=None, password=None, no_pass=False)" ...
3
stack_v2_sparse_classes_30k_train_012341
Implement the Python class `EmailAuthenticationBackend` described below. Class description: Authenticate a CustomUser with e-mail address instead of username. Method signatures and docstrings: - def authenticate(self, username=None, password=None, no_pass=False): Check if the user is properly authenticated, either lo...
Implement the Python class `EmailAuthenticationBackend` described below. Class description: Authenticate a CustomUser with e-mail address instead of username. Method signatures and docstrings: - def authenticate(self, username=None, password=None, no_pass=False): Check if the user is properly authenticated, either lo...
0a284e2aae3ca08955215418a76bb70ad9af1f81
<|skeleton|> class EmailAuthenticationBackend: """Authenticate a CustomUser with e-mail address instead of username.""" def authenticate(self, username=None, password=None, no_pass=False): """Check if the user is properly authenticated, either logging in by e-mail address and password or programmatical...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EmailAuthenticationBackend: """Authenticate a CustomUser with e-mail address instead of username.""" def authenticate(self, username=None, password=None, no_pass=False): """Check if the user is properly authenticated, either logging in by e-mail address and password or programmatically logged in ...
the_stack_v2_python_sparse
lily/users/auth_backends.py
rmoorman/hellolily
train
0
dc4be14d2d66dac55f33e7bb47a38e6dac681354
[ "super(SiteOrder, self).__init__(parent)\nself.parent = parent\nself.resize(400, 300)\nself.list_site = list_site\nself.populate(self.list_site)", "mainLayout = QtGui.QGridLayout(self)\nself.list_site = QtGui.QListWidget()\nfor i in list_site:\n item = QtGui.QListWidgetItem(i)\n self.list_site.addItem(item)...
<|body_start_0|> super(SiteOrder, self).__init__(parent) self.parent = parent self.resize(400, 300) self.list_site = list_site self.populate(self.list_site) <|end_body_0|> <|body_start_1|> mainLayout = QtGui.QGridLayout(self) self.list_site = QtGui.QListWidget() ...
display playing list
SiteOrder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SiteOrder: """display playing list""" def __init__(self, list_site, parent=None): """initialisation""" <|body_0|> def populate(self, list_site): """create layout""" <|body_1|> def moveUp(self): """up is clicked""" <|body_2|> def ...
stack_v2_sparse_classes_36k_train_012391
2,368
no_license
[ { "docstring": "initialisation", "name": "__init__", "signature": "def __init__(self, list_site, parent=None)" }, { "docstring": "create layout", "name": "populate", "signature": "def populate(self, list_site)" }, { "docstring": "up is clicked", "name": "moveUp", "signatu...
5
null
Implement the Python class `SiteOrder` described below. Class description: display playing list Method signatures and docstrings: - def __init__(self, list_site, parent=None): initialisation - def populate(self, list_site): create layout - def moveUp(self): up is clicked - def moveDown(self): down is clicked - def sa...
Implement the Python class `SiteOrder` described below. Class description: display playing list Method signatures and docstrings: - def __init__(self, list_site, parent=None): initialisation - def populate(self, list_site): create layout - def moveUp(self): up is clicked - def moveDown(self): down is clicked - def sa...
a24b3e4e8acbd4da9ba4c83bf96c0b2d2a2cca9c
<|skeleton|> class SiteOrder: """display playing list""" def __init__(self, list_site, parent=None): """initialisation""" <|body_0|> def populate(self, list_site): """create layout""" <|body_1|> def moveUp(self): """up is clicked""" <|body_2|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SiteOrder: """display playing list""" def __init__(self, list_site, parent=None): """initialisation""" super(SiteOrder, self).__init__(parent) self.parent = parent self.resize(400, 300) self.list_site = list_site self.populate(self.list_site) def popul...
the_stack_v2_python_sparse
gui/menusiteorder.py
sensini42/flvdown
train
0
e081707a39263b622c1f0c7fb48128b0361b3d0d
[ "if type(fndats) is str:\n fndats = [fndats]\nif len(fndats) == 1 and len(fndats) != len(scans):\n fndats *= len(scans)\nelse:\n raise NameError('check fndats/scans input')\nnscans = _check_scans(scans)\nself.fndats = fndats\nself.nscans = nscans\nself.counter = counter\nself.signal = signal\nself.monitor ...
<|body_start_0|> if type(fndats) is str: fndats = [fndats] if len(fndats) == 1 and len(fndats) != len(scans): fndats *= len(scans) else: raise NameError('check fndats/scans input') nscans = _check_scans(scans) self.fndats = fndats self....
wrapper
SpecfileDataCollector
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpecfileDataCollector: """wrapper""" def __init__(self, fndats, scans, counter=1, signal='det_dtc', monitor='I02', seconds='Seconds'): """collects data from a given scan list inside a single SPEC file Parameters ---------- fndats : string or list of strings -> file name(s) scans : li...
stack_v2_sparse_classes_36k_train_012392
3,232
permissive
[ { "docstring": "collects data from a given scan list inside a single SPEC file Parameters ---------- fndats : string or list of strings -> file name(s) scans : list of scans to load (parsed by str2rng) counter : counter name for x [string, 1] signal : counter name for y [string, 'det_dtc'] monitor : counter nam...
2
stack_v2_sparse_classes_30k_train_020587
Implement the Python class `SpecfileDataCollector` described below. Class description: wrapper Method signatures and docstrings: - def __init__(self, fndats, scans, counter=1, signal='det_dtc', monitor='I02', seconds='Seconds'): collects data from a given scan list inside a single SPEC file Parameters ---------- fnda...
Implement the Python class `SpecfileDataCollector` described below. Class description: wrapper Method signatures and docstrings: - def __init__(self, fndats, scans, counter=1, signal='det_dtc', monitor='I02', seconds='Seconds'): collects data from a given scan list inside a single SPEC file Parameters ---------- fnda...
d0ff10530833fa8b0866f7303a6a8c99d5a9b208
<|skeleton|> class SpecfileDataCollector: """wrapper""" def __init__(self, fndats, scans, counter=1, signal='det_dtc', monitor='I02', seconds='Seconds'): """collects data from a given scan list inside a single SPEC file Parameters ---------- fndats : string or list of strings -> file name(s) scans : li...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpecfileDataCollector: """wrapper""" def __init__(self, fndats, scans, counter=1, signal='det_dtc', monitor='I02', seconds='Seconds'): """collects data from a given scan list inside a single SPEC file Parameters ---------- fndats : string or list of strings -> file name(s) scans : list of scans t...
the_stack_v2_python_sparse
sloth/io/specfile_eval_utils.py
maurov/xraysloth
train
6
1096e6f8d2d49dffaaa108b71ca71f84ab5d0e1f
[ "logger.info('Overriding class: Optimizer -> GWO.')\nsuper(GWO, self).__init__()\nself.build(params)\nlogger.info('Class overrided.')", "r1 = r.generate_uniform_random_number()\nr2 = r.generate_uniform_random_number()\nA = 2 * a * r1 - a\nC = 2 * r2\nreturn (A, C)", "space.agents.sort(key=lambda x: x.fit)\nalph...
<|body_start_0|> logger.info('Overriding class: Optimizer -> GWO.') super(GWO, self).__init__() self.build(params) logger.info('Class overrided.') <|end_body_0|> <|body_start_1|> r1 = r.generate_uniform_random_number() r2 = r.generate_uniform_random_number() A = ...
A GWO class, inherited from Optimizer. This is the designed class to define GWO-related variables and methods. References: S. Mirjalili, S. Mirjalili and A. Lewis. Grey Wolf Optimizer. Advances in Engineering Software (2014).
GWO
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GWO: """A GWO class, inherited from Optimizer. This is the designed class to define GWO-related variables and methods. References: S. Mirjalili, S. Mirjalili and A. Lewis. Grey Wolf Optimizer. Advances in Engineering Software (2014).""" def __init__(self, params: Optional[Dict[str, Any]]=Non...
stack_v2_sparse_classes_36k_train_012393
3,064
permissive
[ { "docstring": "Initialization method. Args: params: Contains key-value parameters to the meta-heuristics.", "name": "__init__", "signature": "def __init__(self, params: Optional[Dict[str, Any]]=None) -> None" }, { "docstring": "Calculates the mathematical coefficients. Args: a: Linear constant....
3
null
Implement the Python class `GWO` described below. Class description: A GWO class, inherited from Optimizer. This is the designed class to define GWO-related variables and methods. References: S. Mirjalili, S. Mirjalili and A. Lewis. Grey Wolf Optimizer. Advances in Engineering Software (2014). Method signatures and d...
Implement the Python class `GWO` described below. Class description: A GWO class, inherited from Optimizer. This is the designed class to define GWO-related variables and methods. References: S. Mirjalili, S. Mirjalili and A. Lewis. Grey Wolf Optimizer. Advances in Engineering Software (2014). Method signatures and d...
7326a887ed8e3858bc99c8815048d56d02edf88c
<|skeleton|> class GWO: """A GWO class, inherited from Optimizer. This is the designed class to define GWO-related variables and methods. References: S. Mirjalili, S. Mirjalili and A. Lewis. Grey Wolf Optimizer. Advances in Engineering Software (2014).""" def __init__(self, params: Optional[Dict[str, Any]]=Non...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GWO: """A GWO class, inherited from Optimizer. This is the designed class to define GWO-related variables and methods. References: S. Mirjalili, S. Mirjalili and A. Lewis. Grey Wolf Optimizer. Advances in Engineering Software (2014).""" def __init__(self, params: Optional[Dict[str, Any]]=None) -> None: ...
the_stack_v2_python_sparse
opytimizer/optimizers/population/gwo.py
gugarosa/opytimizer
train
602
a7a480abc54fa1837b16567320b150a8c90f42b7
[ "super(SearchSettingsForm, self).__init__(siteconfig, data, *args, **kwargs)\nrequest = kwargs.get('request')\ncur_search_backend_id = self['search_backend_id'].data or self.fields['search_backend_id'].initial\nchoices = []\nsearch_backend_forms = {}\nfor backend in search_backend_registry:\n search_backend_id =...
<|body_start_0|> super(SearchSettingsForm, self).__init__(siteconfig, data, *args, **kwargs) request = kwargs.get('request') cur_search_backend_id = self['search_backend_id'].data or self.fields['search_backend_id'].initial choices = [] search_backend_forms = {} for backe...
Form for search settings. This form manages the main search settings (enabled, how many results, and what backend to use), as well as displaying per-search backend forms so that they may be configured. For example, Elasticsearch requires a URL and index name, while Whoosh requires a file path to store its index. These ...
SearchSettingsForm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SearchSettingsForm: """Form for search settings. This form manages the main search settings (enabled, how many results, and what backend to use), as well as displaying per-search backend forms so that they may be configured. For example, Elasticsearch requires a URL and index name, while Whoosh r...
stack_v2_sparse_classes_36k_train_012394
7,792
permissive
[ { "docstring": "Initialize the search engine settings form. This will also initialize the settings forms for each search engine backend. Args: site_config (djblets.siteconfig.models.SiteConfiguration): The site configuration handling the server's settings. data (dict, optional): The form data. *args (tuple): Ad...
5
null
Implement the Python class `SearchSettingsForm` described below. Class description: Form for search settings. This form manages the main search settings (enabled, how many results, and what backend to use), as well as displaying per-search backend forms so that they may be configured. For example, Elasticsearch requir...
Implement the Python class `SearchSettingsForm` described below. Class description: Form for search settings. This form manages the main search settings (enabled, how many results, and what backend to use), as well as displaying per-search backend forms so that they may be configured. For example, Elasticsearch requir...
c3a991f1e9d7682239a1ab0e8661cee6da01d537
<|skeleton|> class SearchSettingsForm: """Form for search settings. This form manages the main search settings (enabled, how many results, and what backend to use), as well as displaying per-search backend forms so that they may be configured. For example, Elasticsearch requires a URL and index name, while Whoosh r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SearchSettingsForm: """Form for search settings. This form manages the main search settings (enabled, how many results, and what backend to use), as well as displaying per-search backend forms so that they may be configured. For example, Elasticsearch requires a URL and index name, while Whoosh requires a fil...
the_stack_v2_python_sparse
reviewboard/admin/forms/search_settings.py
reviewboard/reviewboard
train
1,141
754f398ea0de11f9f48312804fa8758f38eccc35
[ "a2b = self.filter(sender=sender, recipient=recipient).select_related('sender', 'recipient')\nb2a = self.filter(sender=recipient, recipient=sender).select_related('sender', 'recipient')\nreturn a2b.union(b2a).order_by('created_at')", "try:\n qs_sent = self.filter(sender=recipient)\n qs_received = self.filte...
<|body_start_0|> a2b = self.filter(sender=sender, recipient=recipient).select_related('sender', 'recipient') b2a = self.filter(sender=recipient, recipient=sender).select_related('sender', 'recipient') return a2b.union(b2a).order_by('created_at') <|end_body_0|> <|body_start_1|> try: ...
MessageQueryset
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MessageQueryset: def get_conversation(self, sender, recipient): """获取用户间的私信会话""" <|body_0|> def get_most_recent_conversation(self, recipient): """获取最近一次的私信互动用户,即登录用户作为接受者,判断最后一条消息是自己发出还是发送者发出""" <|body_1|> <|end_skeleton|> <|body_start_0|> a2b = sel...
stack_v2_sparse_classes_36k_train_012395
3,008
no_license
[ { "docstring": "获取用户间的私信会话", "name": "get_conversation", "signature": "def get_conversation(self, sender, recipient)" }, { "docstring": "获取最近一次的私信互动用户,即登录用户作为接受者,判断最后一条消息是自己发出还是发送者发出", "name": "get_most_recent_conversation", "signature": "def get_most_recent_conversation(self, recipient)...
2
stack_v2_sparse_classes_30k_train_021082
Implement the Python class `MessageQueryset` described below. Class description: Implement the MessageQueryset class. Method signatures and docstrings: - def get_conversation(self, sender, recipient): 获取用户间的私信会话 - def get_most_recent_conversation(self, recipient): 获取最近一次的私信互动用户,即登录用户作为接受者,判断最后一条消息是自己发出还是发送者发出
Implement the Python class `MessageQueryset` described below. Class description: Implement the MessageQueryset class. Method signatures and docstrings: - def get_conversation(self, sender, recipient): 获取用户间的私信会话 - def get_most_recent_conversation(self, recipient): 获取最近一次的私信互动用户,即登录用户作为接受者,判断最后一条消息是自己发出还是发送者发出 <|skel...
221f485c7ee594adc34722f14aa94730e23a8d71
<|skeleton|> class MessageQueryset: def get_conversation(self, sender, recipient): """获取用户间的私信会话""" <|body_0|> def get_most_recent_conversation(self, recipient): """获取最近一次的私信互动用户,即登录用户作为接受者,判断最后一条消息是自己发出还是发送者发出""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MessageQueryset: def get_conversation(self, sender, recipient): """获取用户间的私信会话""" a2b = self.filter(sender=sender, recipient=recipient).select_related('sender', 'recipient') b2a = self.filter(sender=recipient, recipient=sender).select_related('sender', 'recipient') return a2b.un...
the_stack_v2_python_sparse
zanhu/messager/models.py
AlaxHAM/qa
train
0
8279bd86bdc1fd1135c7b63c1facd88d2cb2dba0
[ "sprite.Sprite.__init__(self, node, mMap, position, level)\nself.initialPosition = self.position\nself.move = MT_NONE\nmovements = node.getChildren('movement')\nif movements:\n movementNode = movements[0]\n movementType = movementNode.getAttr('type', data.D_STRING)\n if movementType == 'wander':\n s...
<|body_start_0|> sprite.Sprite.__init__(self, node, mMap, position, level) self.initialPosition = self.position self.move = MT_NONE movements = node.getChildren('movement') if movements: movementNode = movements[0] movementType = movementNode.getAttr('type...
NPC class extending Sprite with auto movements and event scripts.
NPC
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NPC: """NPC class extending Sprite with auto movements and event scripts.""" def __init__(self, node, mMap, position=None, level=None): """Initialise the sprite, and set up movement and scripts. node - the <npc> node. mMap - the map to start on. position - the position to start in. I...
stack_v2_sparse_classes_36k_train_012396
4,934
no_license
[ { "docstring": "Initialise the sprite, and set up movement and scripts. node - the <npc> node. mMap - the map to start on. position - the position to start in. If unspecified gets taken from the <npc> node. level - the level to start on. If unspecified gets taken from the <npc> node.", "name": "__init__", ...
3
null
Implement the Python class `NPC` described below. Class description: NPC class extending Sprite with auto movements and event scripts. Method signatures and docstrings: - def __init__(self, node, mMap, position=None, level=None): Initialise the sprite, and set up movement and scripts. node - the <npc> node. mMap - th...
Implement the Python class `NPC` described below. Class description: NPC class extending Sprite with auto movements and event scripts. Method signatures and docstrings: - def __init__(self, node, mMap, position=None, level=None): Initialise the sprite, and set up movement and scripts. node - the <npc> node. mMap - th...
72841fc503c716ac3b524e42f2311cbd9d18a092
<|skeleton|> class NPC: """NPC class extending Sprite with auto movements and event scripts.""" def __init__(self, node, mMap, position=None, level=None): """Initialise the sprite, and set up movement and scripts. node - the <npc> node. mMap - the map to start on. position - the position to start in. I...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NPC: """NPC class extending Sprite with auto movements and event scripts.""" def __init__(self, node, mMap, position=None, level=None): """Initialise the sprite, and set up movement and scripts. node - the <npc> node. mMap - the map to start on. position - the position to start in. If unspecified...
the_stack_v2_python_sparse
eng/npc.py
andrew-turner/Ditto
train
0
5bf3a626ae092b2fe0d1c2d8623b2609f9d3e34d
[ "if not head:\n return None\nself.reverse_iter(head)\nreturn self.head", "if not node.next:\n self.head = node\n return node\nelse:\n parent = self.reverse_iter(node.next)\n parent.next = ListNode(node.val)\n parent = parent.next\n return parent" ]
<|body_start_0|> if not head: return None self.reverse_iter(head) return self.head <|end_body_0|> <|body_start_1|> if not node.next: self.head = node return node else: parent = self.reverse_iter(node.next) parent.next =...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def reverse_iter(self, node): """:type node: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not head: return None...
stack_v2_sparse_classes_36k_train_012397
1,997
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "reverseList", "signature": "def reverseList(self, head)" }, { "docstring": ":type node: ListNode :rtype: ListNode", "name": "reverse_iter", "signature": "def reverse_iter(self, node)" } ]
2
stack_v2_sparse_classes_30k_train_012867
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 reverse_iter(self, node): :type node: 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 reverse_iter(self, node): :type node: ListNode :rtype: ListNode <|skeleton|> class Solution: def re...
f832227c4d0e0b1c0cc326561187004ef24e2a68
<|skeleton|> class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def reverse_iter(self, node): """:type node: 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""" if not head: return None self.reverse_iter(head) return self.head def reverse_iter(self, node): """:type node: ListNode :rtype: ListNode""" if not node.next: ...
the_stack_v2_python_sparse
206.py
Gackle/leetcode_practice
train
0
1dcb7afdfb5aa1df0f97431d261f89594d143751
[ "if k == 1:\n return [i for i in range(1, n + 1)]\nans = [n]\ndec = True\nfor diff in range(k, 0, -1):\n if dec:\n ans.append(ans[len(ans) - 1] - diff)\n dec = False\n else:\n ans.append(ans[len(ans) - 1] + diff)\n dec = True\nlast = ans[len(ans) - 1]\nif last - 2 > 0:\n ans....
<|body_start_0|> if k == 1: return [i for i in range(1, n + 1)] ans = [n] dec = True for diff in range(k, 0, -1): if dec: ans.append(ans[len(ans) - 1] - diff) dec = False else: ans.append(ans[len(ans) - 1...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def constructArray(self, n, k): """:type n: int :type k: int :rtype: List[int]""" <|body_0|> def constructArray2(self, n, k): """We need k+1 numbers to generate k distinct differences. Put first (n-k-1) elements in order: [1, 2, ..., n-k-1], then for the re...
stack_v2_sparse_classes_36k_train_012398
1,609
no_license
[ { "docstring": ":type n: int :type k: int :rtype: List[int]", "name": "constructArray", "signature": "def constructArray(self, n, k)" }, { "docstring": "We need k+1 numbers to generate k distinct differences. Put first (n-k-1) elements in order: [1, 2, ..., n-k-1], then for the remaining [n-k, n...
2
stack_v2_sparse_classes_30k_train_010668
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def constructArray(self, n, k): :type n: int :type k: int :rtype: List[int] - def constructArray2(self, n, k): We need k+1 numbers to generate k distinct differences. Put first (...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def constructArray(self, n, k): :type n: int :type k: int :rtype: List[int] - def constructArray2(self, n, k): We need k+1 numbers to generate k distinct differences. Put first (...
143aa25f92f3827aa379f29c67a9b7ec3757fef9
<|skeleton|> class Solution: def constructArray(self, n, k): """:type n: int :type k: int :rtype: List[int]""" <|body_0|> def constructArray2(self, n, k): """We need k+1 numbers to generate k distinct differences. Put first (n-k-1) elements in order: [1, 2, ..., n-k-1], then for the re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def constructArray(self, n, k): """:type n: int :type k: int :rtype: List[int]""" if k == 1: return [i for i in range(1, n + 1)] ans = [n] dec = True for diff in range(k, 0, -1): if dec: ans.append(ans[len(ans) - 1] - di...
the_stack_v2_python_sparse
py/leetcode_py/667.py
imsure/tech-interview-prep
train
0
08c3cbab67bb9c6a75f5dbc4f0bca708f0ab3cf2
[ "self.file_itr = None\nself.path = path\nif os.path.isdir(self.path):\n self.file_itr = glob.glob(self.path + '*')\nself.transform_filename_to_tensor = transform_filename_to_tensor", "if self.file_itr is not None:\n return map(self.transform_filename_to_tensor, self.file_itr)\nelse:\n return self.transfo...
<|body_start_0|> self.file_itr = None self.path = path if os.path.isdir(self.path): self.file_itr = glob.glob(self.path + '*') self.transform_filename_to_tensor = transform_filename_to_tensor <|end_body_0|> <|body_start_1|> if self.file_itr is not None: r...
An auxiliary class for iterating through a dataset.
CustomIterableDataset
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomIterableDataset: """An auxiliary class for iterating through a dataset.""" def __init__(self, transform_filename_to_tensor: Callable, path: str) -> None: """Args: transform_filename_to_tensor (Callable): Function to read a data file from path and return a tensor from that file....
stack_v2_sparse_classes_36k_train_012399
1,919
permissive
[ { "docstring": "Args: transform_filename_to_tensor (Callable): Function to read a data file from path and return a tensor from that file. path (str): Path to dataset files. This can be either a path to a directory or a file where input examples are stored.", "name": "__init__", "signature": "def __init_...
2
stack_v2_sparse_classes_30k_train_020292
Implement the Python class `CustomIterableDataset` described below. Class description: An auxiliary class for iterating through a dataset. Method signatures and docstrings: - def __init__(self, transform_filename_to_tensor: Callable, path: str) -> None: Args: transform_filename_to_tensor (Callable): Function to read ...
Implement the Python class `CustomIterableDataset` described below. Class description: An auxiliary class for iterating through a dataset. Method signatures and docstrings: - def __init__(self, transform_filename_to_tensor: Callable, path: str) -> None: Args: transform_filename_to_tensor (Callable): Function to read ...
945c582cc0b08885c4e2bfecb020abdfac0122f3
<|skeleton|> class CustomIterableDataset: """An auxiliary class for iterating through a dataset.""" def __init__(self, transform_filename_to_tensor: Callable, path: str) -> None: """Args: transform_filename_to_tensor (Callable): Function to read a data file from path and return a tensor from that file....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomIterableDataset: """An auxiliary class for iterating through a dataset.""" def __init__(self, transform_filename_to_tensor: Callable, path: str) -> None: """Args: transform_filename_to_tensor (Callable): Function to read a data file from path and return a tensor from that file. path (str): ...
the_stack_v2_python_sparse
captum/concept/_utils/data_iterator.py
pytorch/captum
train
4,230