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
c1523587f90bc9a42b5173aea128d555c4bb7912
[ "super().__init__(**kwargs)\nself.magnitude = magnitude\nself.n_transforms = n_transforms\nself._max_magnitude = 10.0\nself._max_x_shift = 0.1\nself._max_y_shift = 0.2\nself._max_angle = 30\nself._max_contrast = 1\nself._max_brightness = 1", "level = self.magnitude / self._max_magnitude\nangle = self.randomly_neg...
<|body_start_0|> super().__init__(**kwargs) self.magnitude = magnitude self.n_transforms = n_transforms self._max_magnitude = 10.0 self._max_x_shift = 0.1 self._max_y_shift = 0.2 self._max_angle = 30 self._max_contrast = 1 self._max_brightness = 1 ...
Implements the RandAugment procedure on a restricted set of transformations. https://arxiv.org/abs/1909.13719 Possible transformations for segmentations maps are: rotation, horizontal and vertical shift, horizontal flip, identity. Additional transformations for images are brightness adjustment and contrast adjustment.
RandAugmentSlice
[ "MIT", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandAugmentSlice: """Implements the RandAugment procedure on a restricted set of transformations. https://arxiv.org/abs/1909.13719 Possible transformations for segmentations maps are: rotation, horizontal and vertical shift, horizontal flip, identity. Additional transformations for images are bri...
stack_v2_sparse_classes_36k_train_018200
19,979
permissive
[ { "docstring": ":param magnitude: magnitude to apply to the transformations as defined in the RandAugment paper. 1 means a weak transform, 10 is the strongest transform. :param n_transforms: number of transformation to sample for each image.", "name": "__init__", "signature": "def __init__(self, magnitu...
3
stack_v2_sparse_classes_30k_train_017238
Implement the Python class `RandAugmentSlice` described below. Class description: Implements the RandAugment procedure on a restricted set of transformations. https://arxiv.org/abs/1909.13719 Possible transformations for segmentations maps are: rotation, horizontal and vertical shift, horizontal flip, identity. Additi...
Implement the Python class `RandAugmentSlice` described below. Class description: Implements the RandAugment procedure on a restricted set of transformations. https://arxiv.org/abs/1909.13719 Possible transformations for segmentations maps are: rotation, horizontal and vertical shift, horizontal flip, identity. Additi...
12b496093097ef48d5ac8880985c04918d7f76fe
<|skeleton|> class RandAugmentSlice: """Implements the RandAugment procedure on a restricted set of transformations. https://arxiv.org/abs/1909.13719 Possible transformations for segmentations maps are: rotation, horizontal and vertical shift, horizontal flip, identity. Additional transformations for images are bri...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandAugmentSlice: """Implements the RandAugment procedure on a restricted set of transformations. https://arxiv.org/abs/1909.13719 Possible transformations for segmentations maps are: rotation, horizontal and vertical shift, horizontal flip, identity. Additional transformations for images are brightness adjus...
the_stack_v2_python_sparse
InnerEye/ML/utils/augmentation.py
MaxCodeXTC/InnerEye-DeepLearning
train
1
fb4d0df9511817eb85430d4f2962c51ca0883d8c
[ "if root is None:\n return '{}'\nqueue = [root]\nindex = 0\nwhile index < len(queue):\n if queue[index] is not None:\n queue.append(queue[index].left)\n queue.append(queue[index].right)\n index += 1\nwhile queue[-1] is None:\n queue.pop()\nreturn '{%s}' % ','.join((str(node.val) if node is...
<|body_start_0|> if root is None: return '{}' queue = [root] index = 0 while index < len(queue): if queue[index] is not None: queue.append(queue[index].left) queue.append(queue[index].right) index += 1 while queu...
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_018201
5,059
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:...
01ee75be4ec9bbb080f170cb747f3fc443eb4d55
<|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 root is None: return '{}' queue = [root] index = 0 while index < len(queue): if queue[index] is not None: queue.append(...
the_stack_v2_python_sparse
python3/297_Serialize_and_Deserialize_Binary_Tree.py
ytatus94/Leetcode
train
0
b3e87975a505a0082bf88f5c44bd6a39ca71666a
[ "super(SentinelClient, self).__init__(server, params, backend)\nself._client_write = None\nself._client_read = None\nself._connection_string = server", "try:\n connection_params = constring.split('/')\n master_name = connection_params[0]\n servers = [host_port.split(':') for host_port in connection_param...
<|body_start_0|> super(SentinelClient, self).__init__(server, params, backend) self._client_write = None self._client_read = None self._connection_string = server <|end_body_0|> <|body_start_1|> try: connection_params = constring.split('/') master_name = ...
Sentinel client object extending django-redis DefaultClient
SentinelClient
[ "MIT", "LGPL-2.1-or-later", "LGPL-3.0-only" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SentinelClient: """Sentinel client object extending django-redis DefaultClient""" def __init__(self, server, params, backend): """Slightly different logic than connection to multiple Redis servers. Reserve only one write and read descriptors, as they will be closed on exit anyway."""...
stack_v2_sparse_classes_36k_train_018202
5,721
permissive
[ { "docstring": "Slightly different logic than connection to multiple Redis servers. Reserve only one write and read descriptors, as they will be closed on exit anyway.", "name": "__init__", "signature": "def __init__(self, server, params, backend)" }, { "docstring": "Parse connection string in f...
5
stack_v2_sparse_classes_30k_train_008759
Implement the Python class `SentinelClient` described below. Class description: Sentinel client object extending django-redis DefaultClient Method signatures and docstrings: - def __init__(self, server, params, backend): Slightly different logic than connection to multiple Redis servers. Reserve only one write and re...
Implement the Python class `SentinelClient` described below. Class description: Sentinel client object extending django-redis DefaultClient Method signatures and docstrings: - def __init__(self, server, params, backend): Slightly different logic than connection to multiple Redis servers. Reserve only one write and re...
2d708bd0d869d391456e0fb8d644af3b9f031acf
<|skeleton|> class SentinelClient: """Sentinel client object extending django-redis DefaultClient""" def __init__(self, server, params, backend): """Slightly different logic than connection to multiple Redis servers. Reserve only one write and read descriptors, as they will be closed on exit anyway."""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SentinelClient: """Sentinel client object extending django-redis DefaultClient""" def __init__(self, server, params, backend): """Slightly different logic than connection to multiple Redis servers. Reserve only one write and read descriptors, as they will be closed on exit anyway.""" supe...
the_stack_v2_python_sparse
itsm/component/data/sentinel.py
TencentBlueKing/bk-itsm
train
100
124c97729075dc788d84f7b3a36dfd1a0820525b
[ "from pygtt import PyGTT\nself._pygtt = PyGTT()\nself._stop = stop\nself._bus_name = bus_name\nself.bus_list = {}\nself.state_bus = {}", "self.bus_list = self._pygtt.get_by_stop(self._stop)\nself.bus_list.sort(key=get_datetime)\nif self._bus_name is not None:\n self.state_bus = self.get_bus_by_name()\n retu...
<|body_start_0|> from pygtt import PyGTT self._pygtt = PyGTT() self._stop = stop self._bus_name = bus_name self.bus_list = {} self.state_bus = {} <|end_body_0|> <|body_start_1|> self.bus_list = self._pygtt.get_by_stop(self._stop) self.bus_list.sort(key=ge...
Inteface to PyGTT.
GttData
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GttData: """Inteface to PyGTT.""" def __init__(self, stop, bus_name): """Initialize the GttData class.""" <|body_0|> def get_data(self): """Get the data from the api.""" <|body_1|> def get_bus_by_name(self): """Get the bus by name.""" ...
stack_v2_sparse_classes_36k_train_018203
3,266
permissive
[ { "docstring": "Initialize the GttData class.", "name": "__init__", "signature": "def __init__(self, stop, bus_name)" }, { "docstring": "Get the data from the api.", "name": "get_data", "signature": "def get_data(self)" }, { "docstring": "Get the bus by name.", "name": "get_b...
3
stack_v2_sparse_classes_30k_train_003523
Implement the Python class `GttData` described below. Class description: Inteface to PyGTT. Method signatures and docstrings: - def __init__(self, stop, bus_name): Initialize the GttData class. - def get_data(self): Get the data from the api. - def get_bus_by_name(self): Get the bus by name.
Implement the Python class `GttData` described below. Class description: Inteface to PyGTT. Method signatures and docstrings: - def __init__(self, stop, bus_name): Initialize the GttData class. - def get_data(self): Get the data from the api. - def get_bus_by_name(self): Get the bus by name. <|skeleton|> class GttDa...
534eee0796950f3f6aade978316418a194a6b2a1
<|skeleton|> class GttData: """Inteface to PyGTT.""" def __init__(self, stop, bus_name): """Initialize the GttData class.""" <|body_0|> def get_data(self): """Get the data from the api.""" <|body_1|> def get_bus_by_name(self): """Get the bus by name.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GttData: """Inteface to PyGTT.""" def __init__(self, stop, bus_name): """Initialize the GttData class.""" from pygtt import PyGTT self._pygtt = PyGTT() self._stop = stop self._bus_name = bus_name self.bus_list = {} self.state_bus = {} def get_d...
the_stack_v2_python_sparse
homeassistant/custom_components/gtt/sensor.py
eliseomartelli/HomeAutomation-Config
train
32
751351080ebaf462be12548e5e6e16c2fedd7fd5
[ "n = len(nums)\ni = 0\nwhile i < len(nums):\n if nums[i] == 'a':\n i += 1\n continue\n if nums[i] <= 0:\n nums[i] = 0\n elif nums[i] > n:\n nums[i] = 0\n else:\n if i < n and i < nums[i] - 1:\n nums.append(nums[nums[i] - 1])\n nums[nums[i] - 1] = 'a'\...
<|body_start_0|> n = len(nums) i = 0 while i < len(nums): if nums[i] == 'a': i += 1 continue if nums[i] <= 0: nums[i] = 0 elif nums[i] > n: nums[i] = 0 else: if i < n a...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def firstMissingPositive(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def firstMissingPositive0(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(nums) i = ...
stack_v2_sparse_classes_36k_train_018204
1,502
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "firstMissingPositive", "signature": "def firstMissingPositive(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "firstMissingPositive0", "signature": "def firstMissingPositive0(self, nums)" } ]
2
null
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 firstMissingPositive0(self, nums): :type nums: List[int] :rtype: int
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 firstMissingPositive0(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: ...
9e49b2c6003b957276737005d4aaac276b44d251
<|skeleton|> class Solution: def firstMissingPositive(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def firstMissingPositive0(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def firstMissingPositive(self, nums): """:type nums: List[int] :rtype: int""" n = len(nums) i = 0 while i < len(nums): if nums[i] == 'a': i += 1 continue if nums[i] <= 0: nums[i] = 0 e...
the_stack_v2_python_sparse
PythonCode/src/0041_First_Missing_Positive.py
oneyuan/CodeforFun
train
0
1fafc3060125454ea4b577b9191e82e70c1d2f6d
[ "super().__init__(coordinator, description)\nenpower_data = self.data.enpower\nassert enpower_data is not None\nself._attr_unique_id = f'{enpower_data.serial_number}_{description.key}'\nself._attr_device_info = DeviceInfo(identifiers={(DOMAIN, enpower_data.serial_number)}, manufacturer='Enphase', model='Enpower', n...
<|body_start_0|> super().__init__(coordinator, description) enpower_data = self.data.enpower assert enpower_data is not None self._attr_unique_id = f'{enpower_data.serial_number}_{description.key}' self._attr_device_info = DeviceInfo(identifiers={(DOMAIN, enpower_data.serial_numb...
Envoy Enpower sensor entity.
EnvoyEnpowerEntity
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnvoyEnpowerEntity: """Envoy Enpower sensor entity.""" def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerSensorEntityDescription) -> None: """Initialize Enpower entity.""" <|body_0|> def native_value(self) -> datetime.datetime | int | flo...
stack_v2_sparse_classes_36k_train_018205
19,764
permissive
[ { "docstring": "Initialize Enpower entity.", "name": "__init__", "signature": "def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerSensorEntityDescription) -> None" }, { "docstring": "Return the state of the power sensors.", "name": "native_value", "signatu...
2
null
Implement the Python class `EnvoyEnpowerEntity` described below. Class description: Envoy Enpower sensor entity. Method signatures and docstrings: - def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerSensorEntityDescription) -> None: Initialize Enpower entity. - def native_value(self) ...
Implement the Python class `EnvoyEnpowerEntity` described below. Class description: Envoy Enpower sensor entity. Method signatures and docstrings: - def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerSensorEntityDescription) -> None: Initialize Enpower entity. - def native_value(self) ...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class EnvoyEnpowerEntity: """Envoy Enpower sensor entity.""" def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerSensorEntityDescription) -> None: """Initialize Enpower entity.""" <|body_0|> def native_value(self) -> datetime.datetime | int | flo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EnvoyEnpowerEntity: """Envoy Enpower sensor entity.""" def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerSensorEntityDescription) -> None: """Initialize Enpower entity.""" super().__init__(coordinator, description) enpower_data = self.data.enpower ...
the_stack_v2_python_sparse
homeassistant/components/enphase_envoy/sensor.py
home-assistant/core
train
35,501
252f2daf493396c4a54a3091e5bd71e8b993aae1
[ "res = len(nums)\nfor i in range(len(nums)):\n res ^= i\n res ^= nums[i]\nreturn res", "nums.sort()\nfor i in range(len(nums)):\n if i != nums[i]:\n return i\nreturn nums[-1] + 1" ]
<|body_start_0|> res = len(nums) for i in range(len(nums)): res ^= i res ^= nums[i] return res <|end_body_0|> <|body_start_1|> nums.sort() for i in range(len(nums)): if i != nums[i]: return i return nums[-1] + 1 <|end_b...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def missingNumber(self, nums): """' 使用异或 0 ^ 4 = 4 4 ^ 4 = 0 不用求和,直接使用异或运算^进行 抵消,剩下的数字就是缺失的了。 :type nums: List[int] :rtype: int""" <|body_0|> def missingNumber2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_36k_train_018206
1,082
no_license
[ { "docstring": "' 使用异或 0 ^ 4 = 4 4 ^ 4 = 0 不用求和,直接使用异或运算^进行 抵消,剩下的数字就是缺失的了。 :type nums: List[int] :rtype: int", "name": "missingNumber", "signature": "def missingNumber(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "missingNumber2", "signature": "def missing...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def missingNumber(self, nums): ' 使用异或 0 ^ 4 = 4 4 ^ 4 = 0 不用求和,直接使用异或运算^进行 抵消,剩下的数字就是缺失的了。 :type nums: List[int] :rtype: int - def missingNumber2(self, nums): :type nums: List[in...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def missingNumber(self, nums): ' 使用异或 0 ^ 4 = 4 4 ^ 4 = 0 不用求和,直接使用异或运算^进行 抵消,剩下的数字就是缺失的了。 :type nums: List[int] :rtype: int - def missingNumber2(self, nums): :type nums: List[in...
5d3574ccd282d0146c83c286ae28d8baaabd4910
<|skeleton|> class Solution: def missingNumber(self, nums): """' 使用异或 0 ^ 4 = 4 4 ^ 4 = 0 不用求和,直接使用异或运算^进行 抵消,剩下的数字就是缺失的了。 :type nums: List[int] :rtype: int""" <|body_0|> def missingNumber2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def missingNumber(self, nums): """' 使用异或 0 ^ 4 = 4 4 ^ 4 = 0 不用求和,直接使用异或运算^进行 抵消,剩下的数字就是缺失的了。 :type nums: List[int] :rtype: int""" res = len(nums) for i in range(len(nums)): res ^= i res ^= nums[i] return res def missingNumber2(self, nums)...
the_stack_v2_python_sparse
268_缺失数字.py
lovehhf/LeetCode
train
0
5e8b9932734bec2eac26839189e7c997956ec95b
[ "if self.request.version == 'v6':\n return ScaleFileSerializerV6\nelif self.request.version == 'v7':\n return ScaleFileSerializerV6", "if request.version == 'v6':\n return self._list_v6(request)\nelif request.version == 'v7':\n return self._list_v6(request)\nraise Http404()", "countries = rest_util....
<|body_start_0|> if self.request.version == 'v6': return ScaleFileSerializerV6 elif self.request.version == 'v7': return ScaleFileSerializerV6 <|end_body_0|> <|body_start_1|> if request.version == 'v6': return self._list_v6(request) elif request.versi...
This view is the endpoint for retrieving source/product files
FilesView
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FilesView: """This view is the endpoint for retrieving source/product files""" def get_serializer_class(self): """Returns the appropriate serializer based off the requests version of the REST API""" <|body_0|> def list(self, request): """Retrieves the batches and...
stack_v2_sparse_classes_36k_train_018207
19,677
permissive
[ { "docstring": "Returns the appropriate serializer based off the requests version of the REST API", "name": "get_serializer_class", "signature": "def get_serializer_class(self)" }, { "docstring": "Retrieves the batches and returns them in JSON form :param request: the HTTP GET request :type requ...
3
stack_v2_sparse_classes_30k_train_020351
Implement the Python class `FilesView` described below. Class description: This view is the endpoint for retrieving source/product files Method signatures and docstrings: - def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API - def list(self, request): Retr...
Implement the Python class `FilesView` described below. Class description: This view is the endpoint for retrieving source/product files Method signatures and docstrings: - def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API - def list(self, request): Retr...
28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b
<|skeleton|> class FilesView: """This view is the endpoint for retrieving source/product files""" def get_serializer_class(self): """Returns the appropriate serializer based off the requests version of the REST API""" <|body_0|> def list(self, request): """Retrieves the batches and...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FilesView: """This view is the endpoint for retrieving source/product files""" def get_serializer_class(self): """Returns the appropriate serializer based off the requests version of the REST API""" if self.request.version == 'v6': return ScaleFileSerializerV6 elif sel...
the_stack_v2_python_sparse
scale/storage/views.py
kfconsultant/scale
train
0
038e7f4f40bb48ce32ddb6d50eb19eb13c0cea8a
[ "def nodes(node: TreeNode):\n if node is not None:\n yield str(node.val)\n yield from nodes(node.left)\n yield from nodes(node.right)\nreturn ' '.join(nodes(root))", "def restore(lo: int, hi: int) -> Union[TreeNode, None]:\n if items and lo < items[0] < hi:\n num = items.popleft(...
<|body_start_0|> def nodes(node: TreeNode): if node is not None: yield str(node.val) yield from nodes(node.left) yield from nodes(node.right) return ' '.join(nodes(root)) <|end_body_0|> <|body_start_1|> def restore(lo: int, hi: int) ->...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Time/Space: O(n)""" <|body_0|> def deserialize(self, data: str) -> Union[TreeNode, None]: """Time/Space: O(n)""" <|body_1|> <|end_skeleton|> <|body_start_0|> def nodes(node: TreeNode): ...
stack_v2_sparse_classes_36k_train_018208
1,014
no_license
[ { "docstring": "Time/Space: O(n)", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Time/Space: O(n)", "name": "deserialize", "signature": "def deserialize(self, data: str) -> Union[TreeNode, None]" } ]
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Time/Space: O(n) - def deserialize(self, data: str) -> Union[TreeNode, None]: Time/Space: O(n)
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Time/Space: O(n) - def deserialize(self, data: str) -> Union[TreeNode, None]: Time/Space: O(n) <|skeleton|> class Codec: def serialize...
359f3b78da90c41c7e42e5c9e13d49b4fc67fe41
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Time/Space: O(n)""" <|body_0|> def deserialize(self, data: str) -> Union[TreeNode, None]: """Time/Space: O(n)""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root: TreeNode) -> str: """Time/Space: O(n)""" def nodes(node: TreeNode): if node is not None: yield str(node.val) yield from nodes(node.left) yield from nodes(node.right) return ' '.join(nodes(root)...
the_stack_v2_python_sparse
problems/449. Serialize and Deserialize BST/1 - Preorder + Queue.py
Vasilic-Maxim/LeetCode-Problems
train
0
1a2ad286bc144f2698ad28212d23b4531edb2d69
[ "if not head:\n return head\nodd, even, even_head = (head, head.next, head.next)\nwhile even and even.next:\n odd.next = even.next\n odd = odd.next\n even.next = odd.next\n even = even.next\nodd.next = even_head\nreturn head", "if not head or not head.next:\n return head\neven_head = head.next\n...
<|body_start_0|> if not head: return head odd, even, even_head = (head, head.next, head.next) while even and even.next: odd.next = even.next odd = odd.next even.next = odd.next even = even.next odd.next = even_head retur...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def oddEvenList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def oddEvenList_v0(self, head): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not head: return he...
stack_v2_sparse_classes_36k_train_018209
4,099
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "oddEvenList", "signature": "def oddEvenList(self, head)" }, { "docstring": ":type head: ListNode :rtype: ListNode", "name": "oddEvenList_v0", "signature": "def oddEvenList_v0(self, head)" } ]
2
stack_v2_sparse_classes_30k_train_001294
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def oddEvenList(self, head): :type head: ListNode :rtype: ListNode - def oddEvenList_v0(self, head): :type head: ListNode :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def oddEvenList(self, head): :type head: ListNode :rtype: ListNode - def oddEvenList_v0(self, head): :type head: ListNode :rtype: ListNode <|skeleton|> class Solution: def ...
b5e09f24e8e96454dc99e20281e853fb9fcc85ed
<|skeleton|> class Solution: def oddEvenList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def oddEvenList_v0(self, head): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def oddEvenList(self, head): """:type head: ListNode :rtype: ListNode""" if not head: return head odd, even, even_head = (head, head.next, head.next) while even and even.next: odd.next = even.next odd = odd.next even.nex...
the_stack_v2_python_sparse
python/328_Odd_Even_Linked_List.py
Moby5/myleetcode
train
2
bdeccc9fef18eb5aad5d0bf1f75585064b1d3013
[ "from pyramid.testing import DummySecurityPolicy\npolicy = DummySecurityPolicy(userid, groupids, permissive, remember_result, forget_result)\nself.registry.registerUtility(policy, IAuthorizationPolicy)\nself.registry.registerUtility(policy, IAuthenticationPolicy)\nreturn policy", "class DummyTraverserFactory:\n\n...
<|body_start_0|> from pyramid.testing import DummySecurityPolicy policy = DummySecurityPolicy(userid, groupids, permissive, remember_result, forget_result) self.registry.registerUtility(policy, IAuthorizationPolicy) self.registry.registerUtility(policy, IAuthenticationPolicy) ret...
TestingConfiguratorMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestingConfiguratorMixin: def testing_securitypolicy(self, userid=None, groupids=(), permissive=True, remember_result=None, forget_result=None): """Unit/integration testing helper: Registers a pair of faux :app:`Pyramid` security policies: a :term:`authentication policy` and a :term:`aut...
stack_v2_sparse_classes_36k_train_018210
7,302
permissive
[ { "docstring": "Unit/integration testing helper: Registers a pair of faux :app:`Pyramid` security policies: a :term:`authentication policy` and a :term:`authorization policy`. The behavior of the registered :term:`authorization policy` depends on the ``permissive`` argument. If ``permissive`` is true, a permiss...
4
stack_v2_sparse_classes_30k_train_002698
Implement the Python class `TestingConfiguratorMixin` described below. Class description: Implement the TestingConfiguratorMixin class. Method signatures and docstrings: - def testing_securitypolicy(self, userid=None, groupids=(), permissive=True, remember_result=None, forget_result=None): Unit/integration testing he...
Implement the Python class `TestingConfiguratorMixin` described below. Class description: Implement the TestingConfiguratorMixin class. Method signatures and docstrings: - def testing_securitypolicy(self, userid=None, groupids=(), permissive=True, remember_result=None, forget_result=None): Unit/integration testing he...
8d08bb85fcbc28800c2c9b35f370d8cc0813dac9
<|skeleton|> class TestingConfiguratorMixin: def testing_securitypolicy(self, userid=None, groupids=(), permissive=True, remember_result=None, forget_result=None): """Unit/integration testing helper: Registers a pair of faux :app:`Pyramid` security policies: a :term:`authentication policy` and a :term:`aut...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestingConfiguratorMixin: def testing_securitypolicy(self, userid=None, groupids=(), permissive=True, remember_result=None, forget_result=None): """Unit/integration testing helper: Registers a pair of faux :app:`Pyramid` security policies: a :term:`authentication policy` and a :term:`authorization pol...
the_stack_v2_python_sparse
venv/Lib/site-packages/pyramid/config/testing.py
supermax03/Port-Scanner-as-a-Service-2
train
0
f4993869f710f3dba6a7d9316f24bbad6bedacad
[ "if len(password) < 9:\n return False\nreturn True", "pattern = '\\\\d'\nif not re.search(pattern, password):\n return False\nreturn True", "pattern = '\\\\w'\nif not re.search(pattern, password):\n return False\nreturn True", "pattern = '\\\\W'\nif not re.search(pattern, password):\n return False...
<|body_start_0|> if len(password) < 9: return False return True <|end_body_0|> <|body_start_1|> pattern = '\\d' if not re.search(pattern, password): return False return True <|end_body_1|> <|body_start_2|> pattern = '\\w' if not re.search...
密码复杂度检查
CheckPass
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CheckPass: """密码复杂度检查""" def check_length(password): """长度""" <|body_0|> def check_number_exists(password): """数字""" <|body_1|> def check_letter_exists(password): """大小写字母""" <|body_2|> def check_special_exists(password): ...
stack_v2_sparse_classes_36k_train_018211
1,276
no_license
[ { "docstring": "长度", "name": "check_length", "signature": "def check_length(password)" }, { "docstring": "数字", "name": "check_number_exists", "signature": "def check_number_exists(password)" }, { "docstring": "大小写字母", "name": "check_letter_exists", "signature": "def check...
4
null
Implement the Python class `CheckPass` described below. Class description: 密码复杂度检查 Method signatures and docstrings: - def check_length(password): 长度 - def check_number_exists(password): 数字 - def check_letter_exists(password): 大小写字母 - def check_special_exists(password): 特殊字符
Implement the Python class `CheckPass` described below. Class description: 密码复杂度检查 Method signatures and docstrings: - def check_length(password): 长度 - def check_number_exists(password): 数字 - def check_letter_exists(password): 大小写字母 - def check_special_exists(password): 特殊字符 <|skeleton|> class CheckPass: """密码复杂...
04bb7f387633ba8af81148dc73a95c2a6d56a8d1
<|skeleton|> class CheckPass: """密码复杂度检查""" def check_length(password): """长度""" <|body_0|> def check_number_exists(password): """数字""" <|body_1|> def check_letter_exists(password): """大小写字母""" <|body_2|> def check_special_exists(password): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CheckPass: """密码复杂度检查""" def check_length(password): """长度""" if len(password) < 9: return False return True def check_number_exists(password): """数字""" pattern = '\\d' if not re.search(pattern, password): return False r...
the_stack_v2_python_sparse
app/utils/check_pass.py
Rabbit-st/rabbit
train
0
078792af45859978f5e44b8afac3bbd92d69794d
[ "payload_proto = training_job_response_payload_pb2.TrainingJobResponsePayload()\npayload_proto.ParseFromString(self.request.body)\nsignature = payload_proto.signature\nvm_id = payload_proto.vm_id\nreturn classifier_domain.OppiaMLAuthInfo(payload_proto.job_result.SerializeToString(), vm_id, signature)", "payload_p...
<|body_start_0|> payload_proto = training_job_response_payload_pb2.TrainingJobResponsePayload() payload_proto.ParseFromString(self.request.body) signature = payload_proto.signature vm_id = payload_proto.vm_id return classifier_domain.OppiaMLAuthInfo(payload_proto.job_result.Seria...
This handler stores the result of the training job in datastore and updates the status of the job.
TrainedClassifierHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TrainedClassifierHandler: """This handler stores the result of the training job in datastore and updates the status of the job.""" def extract_request_message_vm_id_and_signature(self) -> classifier_domain.OppiaMLAuthInfo: """Returns message, vm_id and signature retrieved from incomi...
stack_v2_sparse_classes_36k_train_018212
11,389
permissive
[ { "docstring": "Returns message, vm_id and signature retrieved from incoming request. Returns: OppiaMLAuthInfo. Message at index 0, vm_id at index 1 and signature at index 2.", "name": "extract_request_message_vm_id_and_signature", "signature": "def extract_request_message_vm_id_and_signature(self) -> c...
3
null
Implement the Python class `TrainedClassifierHandler` described below. Class description: This handler stores the result of the training job in datastore and updates the status of the job. Method signatures and docstrings: - def extract_request_message_vm_id_and_signature(self) -> classifier_domain.OppiaMLAuthInfo: R...
Implement the Python class `TrainedClassifierHandler` described below. Class description: This handler stores the result of the training job in datastore and updates the status of the job. Method signatures and docstrings: - def extract_request_message_vm_id_and_signature(self) -> classifier_domain.OppiaMLAuthInfo: R...
d16fdf23d790eafd63812bd7239532256e30a21d
<|skeleton|> class TrainedClassifierHandler: """This handler stores the result of the training job in datastore and updates the status of the job.""" def extract_request_message_vm_id_and_signature(self) -> classifier_domain.OppiaMLAuthInfo: """Returns message, vm_id and signature retrieved from incomi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TrainedClassifierHandler: """This handler stores the result of the training job in datastore and updates the status of the job.""" def extract_request_message_vm_id_and_signature(self) -> classifier_domain.OppiaMLAuthInfo: """Returns message, vm_id and signature retrieved from incoming request. R...
the_stack_v2_python_sparse
core/controllers/classifier.py
oppia/oppia
train
6,172
d4da298294246ba9fb6f097affa8460719beaff6
[ "super(SceneNode, self).__init__()\nself.name = name\nself.transform = Transform()\nself.world_transform = WorldTransform(self.transform)\ndispatcher.connect(self._on_parent_changed, TreeNode.on_parent_changed, self)", "if old_parent != None:\n old_parent.world_transform.remove_child(self.world_transform)\nif ...
<|body_start_0|> super(SceneNode, self).__init__() self.name = name self.transform = Transform() self.world_transform = WorldTransform(self.transform) dispatcher.connect(self._on_parent_changed, TreeNode.on_parent_changed, self) <|end_body_0|> <|body_start_1|> if old_par...
Base class for Scene Graph objects.
SceneNode
[ "BSD-2-Clause-Views", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SceneNode: """Base class for Scene Graph objects.""" def __init__(self, name): """Creates a SceneNode object with the specified name.""" <|body_0|> def _on_parent_changed(self, old_parent, new_parent): """Event handler for TreeNode's parent events. Manages the ad...
stack_v2_sparse_classes_36k_train_018213
1,670
permissive
[ { "docstring": "Creates a SceneNode object with the specified name.", "name": "__init__", "signature": "def __init__(self, name)" }, { "docstring": "Event handler for TreeNode's parent events. Manages the addition and removal of our world transform from our parent.", "name": "_on_parent_chan...
2
stack_v2_sparse_classes_30k_train_018352
Implement the Python class `SceneNode` described below. Class description: Base class for Scene Graph objects. Method signatures and docstrings: - def __init__(self, name): Creates a SceneNode object with the specified name. - def _on_parent_changed(self, old_parent, new_parent): Event handler for TreeNode's parent e...
Implement the Python class `SceneNode` described below. Class description: Base class for Scene Graph objects. Method signatures and docstrings: - def __init__(self, name): Creates a SceneNode object with the specified name. - def _on_parent_changed(self, old_parent, new_parent): Event handler for TreeNode's parent e...
929d50e2bd8b24f079e6c43d6a54b2ff8e572d5f
<|skeleton|> class SceneNode: """Base class for Scene Graph objects.""" def __init__(self, name): """Creates a SceneNode object with the specified name.""" <|body_0|> def _on_parent_changed(self, old_parent, new_parent): """Event handler for TreeNode's parent events. Manages the ad...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SceneNode: """Base class for Scene Graph objects.""" def __init__(self, name): """Creates a SceneNode object with the specified name.""" super(SceneNode, self).__init__() self.name = name self.transform = Transform() self.world_transform = WorldTransform(self.trans...
the_stack_v2_python_sparse
pygly/scene_node.py
adamlwgriffiths/PyGLy
train
28
8b734006b474033bb71c3699c1f1c9bbc21479db
[ "yMax = 0\nyMin = 0\nif len(logList) == 0:\n logger.debug('Log list length is zero cannot set log depth range')\n return (yMin, yMax)\nelif len(logList[0].z_measure_data) == 0:\n logger.debug('Log depth data length is zero cannot set log depth range')\n return (yMin, yMax)\nyMax = logList[0].z_measure_d...
<|body_start_0|> yMax = 0 yMin = 0 if len(logList) == 0: logger.debug('Log list length is zero cannot set log depth range') return (yMin, yMax) elif len(logList[0].z_measure_data) == 0: logger.debug('Log depth data length is zero cannot set log depth r...
Logic layer wrapper for LogBase
Log
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Log: """Logic layer wrapper for LogBase""" def getDepthRange(self, logList): """finds max and min depth values for all log data supplied returns all logs depth min, max""" <|body_0|> def findLogWithLargestDepthRange(self, logList): """returns longest (log with la...
stack_v2_sparse_classes_36k_train_018214
2,464
permissive
[ { "docstring": "finds max and min depth values for all log data supplied returns all logs depth min, max", "name": "getDepthRange", "signature": "def getDepthRange(self, logList)" }, { "docstring": "returns longest (log with largest depth min, max difference) relies on z_measure_max and z_measur...
3
null
Implement the Python class `Log` described below. Class description: Logic layer wrapper for LogBase Method signatures and docstrings: - def getDepthRange(self, logList): finds max and min depth values for all log data supplied returns all logs depth min, max - def findLogWithLargestDepthRange(self, logList): returns...
Implement the Python class `Log` described below. Class description: Logic layer wrapper for LogBase Method signatures and docstrings: - def getDepthRange(self, logList): finds max and min depth values for all log data supplied returns all logs depth min, max - def findLogWithLargestDepthRange(self, logList): returns...
20fba1b1fd1a42add223d9e8af2d267665bec493
<|skeleton|> class Log: """Logic layer wrapper for LogBase""" def getDepthRange(self, logList): """finds max and min depth values for all log data supplied returns all logs depth min, max""" <|body_0|> def findLogWithLargestDepthRange(self, logList): """returns longest (log with la...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Log: """Logic layer wrapper for LogBase""" def getDepthRange(self, logList): """finds max and min depth values for all log data supplied returns all logs depth min, max""" yMax = 0 yMin = 0 if len(logList) == 0: logger.debug('Log list length is zero cannot set ...
the_stack_v2_python_sparse
db/core/log/log.py
ABV-Hub/qreservoir
train
0
9997f09387522570e5cfb1369655a98206fcf4bb
[ "self.product_code = product_code\nself.description = description\nself.market_price = market_price\nself.rental_price = rental_price", "output_dict = {}\noutput_dict['productCode'] = self.product_code\noutput_dict['description'] = self.description\noutput_dict['marketPrice'] = self.market_price\noutput_dict['ren...
<|body_start_0|> self.product_code = product_code self.description = description self.market_price = market_price self.rental_price = rental_price <|end_body_0|> <|body_start_1|> output_dict = {} output_dict['productCode'] = self.product_code output_dict['descrip...
inventory base class
Inventory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Inventory: """inventory base class""" def __init__(self, product_code, description, market_price, rental_price): """initializing""" <|body_0|> def return_as_dictionary(self): """returns a dictionary""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_018215
772
no_license
[ { "docstring": "initializing", "name": "__init__", "signature": "def __init__(self, product_code, description, market_price, rental_price)" }, { "docstring": "returns a dictionary", "name": "return_as_dictionary", "signature": "def return_as_dictionary(self)" } ]
2
stack_v2_sparse_classes_30k_train_005413
Implement the Python class `Inventory` described below. Class description: inventory base class Method signatures and docstrings: - def __init__(self, product_code, description, market_price, rental_price): initializing - def return_as_dictionary(self): returns a dictionary
Implement the Python class `Inventory` described below. Class description: inventory base class Method signatures and docstrings: - def __init__(self, product_code, description, market_price, rental_price): initializing - def return_as_dictionary(self): returns a dictionary <|skeleton|> class Inventory: """inven...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class Inventory: """inventory base class""" def __init__(self, product_code, description, market_price, rental_price): """initializing""" <|body_0|> def return_as_dictionary(self): """returns a dictionary""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Inventory: """inventory base class""" def __init__(self, product_code, description, market_price, rental_price): """initializing""" self.product_code = product_code self.description = description self.market_price = market_price self.rental_price = rental_price ...
the_stack_v2_python_sparse
students/humberto_gonzalez/lesson01/inventory_management/inventory_class.py
JavaRod/SP_Python220B_2019
train
1
341d8807eb407681ac4a7202b209f63a5642d24b
[ "super().__init__()\nself.msg_function_edge = nn.Sequential(nn.Linear(edge_size, node_size), ShiftedSoftplus(), nn.Linear(node_size, node_size))\nself.msg_function_node = nn.Sequential(nn.Linear(node_size, node_size), ShiftedSoftplus(), nn.Linear(node_size, node_size))", "gates = self.msg_function_edge(edge_state...
<|body_start_0|> super().__init__() self.msg_function_edge = nn.Sequential(nn.Linear(edge_size, node_size), ShiftedSoftplus(), nn.Linear(node_size, node_size)) self.msg_function_node = nn.Sequential(nn.Linear(node_size, node_size), ShiftedSoftplus(), nn.Linear(node_size, node_size)) <|end_body_0...
Message function
SchnetMessageFunction
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SchnetMessageFunction: """Message function""" def __init__(self, node_size, edge_size): """Args: node_size (int): Size of node state edge_size (int): Size of edge state""" <|body_0|> def forward(self, node_state, edge_state): """Args: node_state (tensor): State o...
stack_v2_sparse_classes_36k_train_018216
7,647
no_license
[ { "docstring": "Args: node_size (int): Size of node state edge_size (int): Size of edge state", "name": "__init__", "signature": "def __init__(self, node_size, edge_size)" }, { "docstring": "Args: node_state (tensor): State of each sender node (num_edges, node_size) edge_state (tensor): Edge sta...
2
stack_v2_sparse_classes_30k_train_001324
Implement the Python class `SchnetMessageFunction` described below. Class description: Message function Method signatures and docstrings: - def __init__(self, node_size, edge_size): Args: node_size (int): Size of node state edge_size (int): Size of edge state - def forward(self, node_state, edge_state): Args: node_st...
Implement the Python class `SchnetMessageFunction` described below. Class description: Message function Method signatures and docstrings: - def __init__(self, node_size, edge_size): Args: node_size (int): Size of node state edge_size (int): Size of edge state - def forward(self, node_state, edge_state): Args: node_st...
117b1898d389b4b1727f0531c1f7eb827384f5c8
<|skeleton|> class SchnetMessageFunction: """Message function""" def __init__(self, node_size, edge_size): """Args: node_size (int): Size of node state edge_size (int): Size of edge state""" <|body_0|> def forward(self, node_state, edge_state): """Args: node_state (tensor): State o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SchnetMessageFunction: """Message function""" def __init__(self, node_size, edge_size): """Args: node_size (int): Size of node state edge_size (int): Size of edge state""" super().__init__() self.msg_function_edge = nn.Sequential(nn.Linear(edge_size, node_size), ShiftedSoftplus(),...
the_stack_v2_python_sparse
models/layer.py
bhastrup/RL-on-energy-surfaces
train
0
8a2649388439d558532beb9fe1dfa919978382e9
[ "if key is None or item is None:\n return\nself.cache_data[key] = item", "if key is None or key not in self.cache_data:\n return None\nvalue = self.cache_data.get(key)\nreturn value" ]
<|body_start_0|> if key is None or item is None: return self.cache_data[key] = item <|end_body_0|> <|body_start_1|> if key is None or key not in self.cache_data: return None value = self.cache_data.get(key) return value <|end_body_1|>
class basiccache child class to basecaching
BasicCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasicCache: """class basiccache child class to basecaching""" def put(self, key, item): """Add an item in the cache""" <|body_0|> def get(self, key): """Get an item by key""" <|body_1|> <|end_skeleton|> <|body_start_0|> if key is None or item is...
stack_v2_sparse_classes_36k_train_018217
586
no_license
[ { "docstring": "Add an item in the cache", "name": "put", "signature": "def put(self, key, item)" }, { "docstring": "Get an item by key", "name": "get", "signature": "def get(self, key)" } ]
2
stack_v2_sparse_classes_30k_train_002867
Implement the Python class `BasicCache` described below. Class description: class basiccache child class to basecaching Method signatures and docstrings: - def put(self, key, item): Add an item in the cache - def get(self, key): Get an item by key
Implement the Python class `BasicCache` described below. Class description: class basiccache child class to basecaching Method signatures and docstrings: - def put(self, key, item): Add an item in the cache - def get(self, key): Get an item by key <|skeleton|> class BasicCache: """class basiccache child class to...
c0182a227da7a47fd641b3d9e085243b36b626db
<|skeleton|> class BasicCache: """class basiccache child class to basecaching""" def put(self, key, item): """Add an item in the cache""" <|body_0|> def get(self, key): """Get an item by key""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BasicCache: """class basiccache child class to basecaching""" def put(self, key, item): """Add an item in the cache""" if key is None or item is None: return self.cache_data[key] = item def get(self, key): """Get an item by key""" if key is None or...
the_stack_v2_python_sparse
0x03-caching/0-basic_cache.py
Jilroge7/holbertonschool-web_back_end
train
0
2fe5e1aa02b31005092dcd43d6f3fb2d697408d6
[ "self.base_image = pygame.image.load(image)\nself.images = []\nself.duration = duration\nself.last_change = time()\nself.selected_image = 0\nsprite_w = self.base_image.get_width() / w\nsprite_h = self.base_image.get_height() / h\nself.final_size = final_size\nself.invisible_color = invisible_color\nif final_size is...
<|body_start_0|> self.base_image = pygame.image.load(image) self.images = [] self.duration = duration self.last_change = time() self.selected_image = 0 sprite_w = self.base_image.get_width() / w sprite_h = self.base_image.get_height() / h self.final_size =...
SpriteSheet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpriteSheet: def __init__(self, image: str, w: int, h: int, duration: float=None, final_size: tuple=None, invisible_color: tuple=(0, 0, 1)): """This class is for creating spritesheets :param image: the path to the image of the sheet :param w: the width of each frame in the sheet :param h...
stack_v2_sparse_classes_36k_train_018218
2,468
no_license
[ { "docstring": "This class is for creating spritesheets :param image: the path to the image of the sheet :param w: the width of each frame in the sheet :param h: the height of each frame in the sheet :param duration: the number of seconds to stay on each frame :param final_size: the final size to scale the imag...
3
stack_v2_sparse_classes_30k_train_021651
Implement the Python class `SpriteSheet` described below. Class description: Implement the SpriteSheet class. Method signatures and docstrings: - def __init__(self, image: str, w: int, h: int, duration: float=None, final_size: tuple=None, invisible_color: tuple=(0, 0, 1)): This class is for creating spritesheets :par...
Implement the Python class `SpriteSheet` described below. Class description: Implement the SpriteSheet class. Method signatures and docstrings: - def __init__(self, image: str, w: int, h: int, duration: float=None, final_size: tuple=None, invisible_color: tuple=(0, 0, 1)): This class is for creating spritesheets :par...
e9e68cf3ba4f9f12e66eae81893ca9dcc534835c
<|skeleton|> class SpriteSheet: def __init__(self, image: str, w: int, h: int, duration: float=None, final_size: tuple=None, invisible_color: tuple=(0, 0, 1)): """This class is for creating spritesheets :param image: the path to the image of the sheet :param w: the width of each frame in the sheet :param h...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpriteSheet: def __init__(self, image: str, w: int, h: int, duration: float=None, final_size: tuple=None, invisible_color: tuple=(0, 0, 1)): """This class is for creating spritesheets :param image: the path to the image of the sheet :param w: the width of each frame in the sheet :param h: the height o...
the_stack_v2_python_sparse
Objects/SpriteSheet.py
john-palazzolo/PyGE
train
0
c969c9c9b90dfe4a487a32c12d317b2b663469aa
[ "res = []\n\ndef preOrder(root):\n if root:\n res.append(str(root.val))\n preOrder(root.left)\n preOrder(root.right)\npreOrder(root)\nreturn ' '.join(res)", "vals = collections.deque((val for val in data.split()))\n\ndef build(minVal, maxVal):\n if vals and minVal < vals[0] < maxVal:\n ...
<|body_start_0|> res = [] def preOrder(root): if root: res.append(str(root.val)) preOrder(root.left) preOrder(root.right) preOrder(root) return ' '.join(res) <|end_body_0|> <|body_start_1|> vals = collections.deque((va...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = [] ...
stack_v2_sparse_classes_36k_train_018219
3,330
no_license
[ { "docstring": "Encodes a tree to a single string.", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Decodes your encoded data to tree.", "name": "deserialize", "signature": "def deserialize(self, data: str) -> TreeNode" } ]
2
stack_v2_sparse_classes_30k_train_012018
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. <|skeleton|> class Co...
3fe8c2298a52a15fadec0693e00445d875c4b6ea
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" res = [] def preOrder(root): if root: res.append(str(root.val)) preOrder(root.left) preOrder(root.right) preOrder(root) ...
the_stack_v2_python_sparse
Serialize and Deserialize BST.py
huiyi999/leetcode_python
train
0
f863c52b39e2dc0c857874b6af24dc600c89f412
[ "filters = [('uuid', None, 'str')]\nparams = external_common.parse_arguments(filters, kwargs)\nif not params.uuid:\n raise MissingOrBadArgumentError(\"Mandatory parameter 'uuid' is missing or empty\")\nsql = '\\n /* socorro.external.postgresql.priorityjobs.Priorityjobs.get */\\n SELECT uuid...
<|body_start_0|> filters = [('uuid', None, 'str')] params = external_common.parse_arguments(filters, kwargs) if not params.uuid: raise MissingOrBadArgumentError("Mandatory parameter 'uuid' is missing or empty") sql = '\n /* socorro.external.postgresql.priorityjobs....
Implement the /priorityjobs service with PostgreSQL.
Priorityjobs
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Priorityjobs: """Implement the /priorityjobs service with PostgreSQL.""" def get(self, **kwargs): """Return a job in the priority queue.""" <|body_0|> def create(self, **kwargs): """Add a new job to the priority queue if not already in that queue.""" <|bo...
stack_v2_sparse_classes_36k_train_018220
3,475
no_license
[ { "docstring": "Return a job in the priority queue.", "name": "get", "signature": "def get(self, **kwargs)" }, { "docstring": "Add a new job to the priority queue if not already in that queue.", "name": "create", "signature": "def create(self, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_020174
Implement the Python class `Priorityjobs` described below. Class description: Implement the /priorityjobs service with PostgreSQL. Method signatures and docstrings: - def get(self, **kwargs): Return a job in the priority queue. - def create(self, **kwargs): Add a new job to the priority queue if not already in that q...
Implement the Python class `Priorityjobs` described below. Class description: Implement the /priorityjobs service with PostgreSQL. Method signatures and docstrings: - def get(self, **kwargs): Return a job in the priority queue. - def create(self, **kwargs): Add a new job to the priority queue if not already in that q...
aafd7ed25b3601653584337b4af29254d98b3ade
<|skeleton|> class Priorityjobs: """Implement the /priorityjobs service with PostgreSQL.""" def get(self, **kwargs): """Return a job in the priority queue.""" <|body_0|> def create(self, **kwargs): """Add a new job to the priority queue if not already in that queue.""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Priorityjobs: """Implement the /priorityjobs service with PostgreSQL.""" def get(self, **kwargs): """Return a job in the priority queue.""" filters = [('uuid', None, 'str')] params = external_common.parse_arguments(filters, kwargs) if not params.uuid: raise Mis...
the_stack_v2_python_sparse
socorro/external/postgresql/priorityjobs.py
mpressman/socorro
train
0
f6fc44385200a173674cfb15cbc87bf8dfe7e5cb
[ "columns = []\ncolumns = DownloadAlliesTest.fields_helper(User, columns)\ncolumns = DownloadAlliesTest.fields_helper(Ally, columns)\ncolumns = DownloadAlliesTest.fields_helper(StudentCategories, columns)\nallies = Ally.objects.all()\ndata = []\nfor user in allies:\n categories = StudentCategories.objects.filter(...
<|body_start_0|> columns = [] columns = DownloadAlliesTest.fields_helper(User, columns) columns = DownloadAlliesTest.fields_helper(Ally, columns) columns = DownloadAlliesTest.fields_helper(StudentCategories, columns) allies = Ally.objects.all() data = [] for user ...
Unit tests for upload feature
UploadFileTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UploadFileTest: """Unit tests for upload feature""" def make_frame(): """helper function for upload file test""" <|body_0|> def setUp(self): """Set up the test""" <|body_1|> def test_post_not_staff(self): """upload file: testing files that ha...
stack_v2_sparse_classes_36k_train_018221
44,760
no_license
[ { "docstring": "helper function for upload file test", "name": "make_frame", "signature": "def make_frame()" }, { "docstring": "Set up the test", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "upload file: testing files that has inappropriate input", "name...
5
stack_v2_sparse_classes_30k_train_004373
Implement the Python class `UploadFileTest` described below. Class description: Unit tests for upload feature Method signatures and docstrings: - def make_frame(): helper function for upload file test - def setUp(self): Set up the test - def test_post_not_staff(self): upload file: testing files that has inappropriate...
Implement the Python class `UploadFileTest` described below. Class description: Unit tests for upload feature Method signatures and docstrings: - def make_frame(): helper function for upload file test - def setUp(self): Set up the test - def test_post_not_staff(self): upload file: testing files that has inappropriate...
cafd691a7bb5e78e03d93a7c8f46ae3a69f1a01e
<|skeleton|> class UploadFileTest: """Unit tests for upload feature""" def make_frame(): """helper function for upload file test""" <|body_0|> def setUp(self): """Set up the test""" <|body_1|> def test_post_not_staff(self): """upload file: testing files that ha...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UploadFileTest: """Unit tests for upload feature""" def make_frame(): """helper function for upload file test""" columns = [] columns = DownloadAlliesTest.fields_helper(User, columns) columns = DownloadAlliesTest.fields_helper(Ally, columns) columns = DownloadAllie...
the_stack_v2_python_sparse
sap/tests_v3.py
zshanahmed/SAP
train
2
9a43b92e4bb5334fd39f8c837b1e679c197cb7c5
[ "logging.info('*** 登录功能 - 正常登录用例:登录成功 ***')\ninit_driver['lp'].login(LD.correct_data['account'], LD.correct_data['password'])\ntime.sleep(0.5)\nassert init_driver['driver'].current_url == LD.correct_data['check_url']", "logging.info('*** 登陆功能 - 异常用例 - 用户名不能为空/密码不能为空 ***')\ninit_driver['lp'].login(case['account'],...
<|body_start_0|> logging.info('*** 登录功能 - 正常登录用例:登录成功 ***') init_driver['lp'].login(LD.correct_data['account'], LD.correct_data['password']) time.sleep(0.5) assert init_driver['driver'].current_url == LD.correct_data['check_url'] <|end_body_0|> <|body_start_1|> logging.info('***...
TestLogin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestLogin: def test_login_success(self, init_driver): """正常场景 -- 登录成功 :param init_driver: 使用前置后置的返回值 :return:""" <|body_0|> def test_login_failed(self, case, init_driver): """异常用例 - 用户名不能为空/密码不能为空 :param case: 数据驱动,使用 LD.wrong_data 传递的参数 :param init_driver: 使用前置后置的返回...
stack_v2_sparse_classes_36k_train_018222
2,650
no_license
[ { "docstring": "正常场景 -- 登录成功 :param init_driver: 使用前置后置的返回值 :return:", "name": "test_login_success", "signature": "def test_login_success(self, init_driver)" }, { "docstring": "异常用例 - 用户名不能为空/密码不能为空 :param case: 数据驱动,使用 LD.wrong_data 传递的参数 :param init_driver: 使用前置后置的返回值 :return:", "name": "t...
2
null
Implement the Python class `TestLogin` described below. Class description: Implement the TestLogin class. Method signatures and docstrings: - def test_login_success(self, init_driver): 正常场景 -- 登录成功 :param init_driver: 使用前置后置的返回值 :return: - def test_login_failed(self, case, init_driver): 异常用例 - 用户名不能为空/密码不能为空 :param c...
Implement the Python class `TestLogin` described below. Class description: Implement the TestLogin class. Method signatures and docstrings: - def test_login_success(self, init_driver): 正常场景 -- 登录成功 :param init_driver: 使用前置后置的返回值 :return: - def test_login_failed(self, case, init_driver): 异常用例 - 用户名不能为空/密码不能为空 :param c...
cfadd3132c2c7c518c784589e0dab6510a662a6c
<|skeleton|> class TestLogin: def test_login_success(self, init_driver): """正常场景 -- 登录成功 :param init_driver: 使用前置后置的返回值 :return:""" <|body_0|> def test_login_failed(self, case, init_driver): """异常用例 - 用户名不能为空/密码不能为空 :param case: 数据驱动,使用 LD.wrong_data 传递的参数 :param init_driver: 使用前置后置的返回...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestLogin: def test_login_success(self, init_driver): """正常场景 -- 登录成功 :param init_driver: 使用前置后置的返回值 :return:""" logging.info('*** 登录功能 - 正常登录用例:登录成功 ***') init_driver['lp'].login(LD.correct_data['account'], LD.correct_data['password']) time.sleep(0.5) assert init_drive...
the_stack_v2_python_sparse
lemon/Python_ketangpai/test_cases/test_login.py
songyongzhuang/PythonCode_office
train
0
30320a9cfbeb7999bf7cebd6f29d244942537849
[ "self._threshold = threshold\nself._partner_defections = 0\nself._ready_to_interact = False\nself._cooperate_resource_index = 0\nself._defect_resource_index = 1\nself._column_player_is_focal = True", "interaction_inventories = observation['INTERACTION_INVENTORIES']\nrow_inventory = interaction_inventories[0]\ncol...
<|body_start_0|> self._threshold = threshold self._partner_defections = 0 self._ready_to_interact = False self._cooperate_resource_index = 0 self._defect_resource_index = 1 self._column_player_is_focal = True <|end_body_0|> <|body_start_1|> interaction_inventorie...
Puppeteer function for a GRIM strategy in two resource *_in_the_matrix.
GrimTwoResourceInTheMatrix
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GrimTwoResourceInTheMatrix: """Puppeteer function for a GRIM strategy in two resource *_in_the_matrix.""" def __init__(self, threshold: int) -> None: """Initializes the puppeteer. Args: threshold: number of defections after which it will switch behavior.""" <|body_0|> de...
stack_v2_sparse_classes_36k_train_018223
7,109
permissive
[ { "docstring": "Initializes the puppeteer. Args: threshold: number of defections after which it will switch behavior.", "name": "__init__", "signature": "def __init__(self, threshold: int) -> None" }, { "docstring": "Returns the focal and partner inventories from the latest interaction.", "n...
4
stack_v2_sparse_classes_30k_train_005818
Implement the Python class `GrimTwoResourceInTheMatrix` described below. Class description: Puppeteer function for a GRIM strategy in two resource *_in_the_matrix. Method signatures and docstrings: - def __init__(self, threshold: int) -> None: Initializes the puppeteer. Args: threshold: number of defections after whi...
Implement the Python class `GrimTwoResourceInTheMatrix` described below. Class description: Puppeteer function for a GRIM strategy in two resource *_in_the_matrix. Method signatures and docstrings: - def __init__(self, threshold: int) -> None: Initializes the puppeteer. Args: threshold: number of defections after whi...
e42b916b32771f7af5ad4eccbdf4ded410735299
<|skeleton|> class GrimTwoResourceInTheMatrix: """Puppeteer function for a GRIM strategy in two resource *_in_the_matrix.""" def __init__(self, threshold: int) -> None: """Initializes the puppeteer. Args: threshold: number of defections after which it will switch behavior.""" <|body_0|> de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GrimTwoResourceInTheMatrix: """Puppeteer function for a GRIM strategy in two resource *_in_the_matrix.""" def __init__(self, threshold: int) -> None: """Initializes the puppeteer. Args: threshold: number of defections after which it will switch behavior.""" self._threshold = threshold ...
the_stack_v2_python_sparse
meltingpot/python/utils/bots/puppeteer_functions.py
classicvalues/meltingpot
train
0
624cda2a86d315ead7c117e1cf9798ac677a0311
[ "if len(s) == 0:\n return 0\nStact = [-1]\nmaxLens = 0\nfor i, ch in enumerate(s):\n if ch == '(':\n Stact.append(i)\n else:\n Stact.pop()\n if len(Stact) == 0:\n Stact.append(i)\n else:\n maxLens = max(maxLens, i - Stact[-1])\nreturn maxLens", "left, rig...
<|body_start_0|> if len(s) == 0: return 0 Stact = [-1] maxLens = 0 for i, ch in enumerate(s): if ch == '(': Stact.append(i) else: Stact.pop() if len(Stact) == 0: Stact.append(i) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestValidParentheses(self, s: str) -> int: """使用堆栈,堆栈存下标 :param s: :return:""" <|body_0|> def longestValidParentheses2(self, s: str) -> int: """两遍遍历 :param s: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(s) == 0: ...
stack_v2_sparse_classes_36k_train_018224
1,896
no_license
[ { "docstring": "使用堆栈,堆栈存下标 :param s: :return:", "name": "longestValidParentheses", "signature": "def longestValidParentheses(self, s: str) -> int" }, { "docstring": "两遍遍历 :param s: :return:", "name": "longestValidParentheses2", "signature": "def longestValidParentheses2(self, s: str) -> ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestValidParentheses(self, s: str) -> int: 使用堆栈,堆栈存下标 :param s: :return: - def longestValidParentheses2(self, s: str) -> int: 两遍遍历 :param s: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestValidParentheses(self, s: str) -> int: 使用堆栈,堆栈存下标 :param s: :return: - def longestValidParentheses2(self, s: str) -> int: 两遍遍历 :param s: :return: <|skeleton|> class S...
837957ea22aa07ce28a6c23ea0419bd2011e1f88
<|skeleton|> class Solution: def longestValidParentheses(self, s: str) -> int: """使用堆栈,堆栈存下标 :param s: :return:""" <|body_0|> def longestValidParentheses2(self, s: str) -> int: """两遍遍历 :param s: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestValidParentheses(self, s: str) -> int: """使用堆栈,堆栈存下标 :param s: :return:""" if len(s) == 0: return 0 Stact = [-1] maxLens = 0 for i, ch in enumerate(s): if ch == '(': Stact.append(i) else: ...
the_stack_v2_python_sparse
华为题库/最长有效括号.py
2226171237/Algorithmpractice
train
0
639a624c10f5b44ed90385709220e66cbb3ba471
[ "self.__threads = threads\nself.__count = 0\nself.__main = _thread.allocate_lock()\nself.__exit = _thread.allocate_lock()\nself.__exit.acquire()", "self.__main.acquire()\nself.__count += 1\nif self.__count < self.__threads:\n self.__main.release()\nelse:\n self.__exit.release()\nself.__exit.acquire()\nself....
<|body_start_0|> self.__threads = threads self.__count = 0 self.__main = _thread.allocate_lock() self.__exit = _thread.allocate_lock() self.__exit.acquire() <|end_body_0|> <|body_start_1|> self.__main.acquire() self.__count += 1 if self.__count < self.__t...
Sync(threads) -> Sync
Sync
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Sync: """Sync(threads) -> Sync""" def __init__(self, threads): """Initialize the Sync object.""" <|body_0|> def sync(self): """Automatically syncronize calling threads.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.__threads = threads ...
stack_v2_sparse_classes_36k_train_018225
1,230
no_license
[ { "docstring": "Initialize the Sync object.", "name": "__init__", "signature": "def __init__(self, threads)" }, { "docstring": "Automatically syncronize calling threads.", "name": "sync", "signature": "def sync(self)" } ]
2
null
Implement the Python class `Sync` described below. Class description: Sync(threads) -> Sync Method signatures and docstrings: - def __init__(self, threads): Initialize the Sync object. - def sync(self): Automatically syncronize calling threads.
Implement the Python class `Sync` described below. Class description: Sync(threads) -> Sync Method signatures and docstrings: - def __init__(self, threads): Initialize the Sync object. - def sync(self): Automatically syncronize calling threads. <|skeleton|> class Sync: """Sync(threads) -> Sync""" def __init...
45837fc39f99b5f7f69919ed2f6732e6b7bec936
<|skeleton|> class Sync: """Sync(threads) -> Sync""" def __init__(self, threads): """Initialize the Sync object.""" <|body_0|> def sync(self): """Automatically syncronize calling threads.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Sync: """Sync(threads) -> Sync""" def __init__(self, threads): """Initialize the Sync object.""" self.__threads = threads self.__count = 0 self.__main = _thread.allocate_lock() self.__exit = _thread.allocate_lock() self.__exit.acquire() def sync(self):...
the_stack_v2_python_sparse
Python 2.X/ZERO/Experiments/Client-Server Demo/Working Example/prog/sync.py
jacobbridges/my-chaos
train
0
e13723b025110410024b86c27a0ddea9d70e377e
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MembersAddedEventMessageDetail()", "from .event_message_detail import EventMessageDetail\nfrom .identity_set import IdentitySet\nfrom .teamwork_user_identity import TeamworkUserIdentity\nfrom .event_message_detail import EventMessageDe...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return MembersAddedEventMessageDetail() <|end_body_0|> <|body_start_1|> from .event_message_detail import EventMessageDetail from .identity_set import IdentitySet from .teamwork_user_id...
MembersAddedEventMessageDetail
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MembersAddedEventMessageDetail: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MembersAddedEventMessageDetail: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v...
stack_v2_sparse_classes_36k_train_018226
3,235
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: MembersAddedEventMessageDetail", "name": "create_from_discriminator_value", "signature": "def create_from_di...
3
null
Implement the Python class `MembersAddedEventMessageDetail` described below. Class description: Implement the MembersAddedEventMessageDetail class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MembersAddedEventMessageDetail: Creates a new instance of...
Implement the Python class `MembersAddedEventMessageDetail` described below. Class description: Implement the MembersAddedEventMessageDetail class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MembersAddedEventMessageDetail: Creates a new instance of...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class MembersAddedEventMessageDetail: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MembersAddedEventMessageDetail: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MembersAddedEventMessageDetail: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MembersAddedEventMessageDetail: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and creat...
the_stack_v2_python_sparse
msgraph/generated/models/members_added_event_message_detail.py
microsoftgraph/msgraph-sdk-python
train
135
9d014f4ae52e42e9dcb2ad26031379c8d2bd7d44
[ "super(ConvNetFeatureExtractor, self).__init__()\nself.feature_layer = feature_layer\nself.pretrained_params = pretrained_params\nself.pretrained_meta = pretrained_meta\nself.center_only = center_only\nself.convnet = DecafNet(self.pretrained_params, self.pretrained_meta)", "img = self.convnet.oversample(img, cent...
<|body_start_0|> super(ConvNetFeatureExtractor, self).__init__() self.feature_layer = feature_layer self.pretrained_params = pretrained_params self.pretrained_meta = pretrained_meta self.center_only = center_only self.convnet = DecafNet(self.pretrained_params, self.pretra...
ConvNetFeatureExtractor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConvNetFeatureExtractor: def __init__(self, feature_layer='fc7_cudanet_out', pretrained_params='imagenet.decafnet.epoch90', pretrained_meta='imagenet.decafnet.meta', center_only=True): """:param feature_layer: The ConvNet layer that's used for feature extraction. Defaults to `fc7_cudanet...
stack_v2_sparse_classes_36k_train_018227
3,051
no_license
[ { "docstring": ":param feature_layer: The ConvNet layer that's used for feature extraction. Defaults to `fc7_cudanet_out`. A description of all available layers for the ImageNet-1k-pretrained ConvNet is found in the DeCAF wiki. They are: - `pool5_cudanet_out` - `fc6_cudanet_out` - `fc6_neuron_cudanet_out` - `fc...
2
stack_v2_sparse_classes_30k_train_004977
Implement the Python class `ConvNetFeatureExtractor` described below. Class description: Implement the ConvNetFeatureExtractor class. Method signatures and docstrings: - def __init__(self, feature_layer='fc7_cudanet_out', pretrained_params='imagenet.decafnet.epoch90', pretrained_meta='imagenet.decafnet.meta', center_...
Implement the Python class `ConvNetFeatureExtractor` described below. Class description: Implement the ConvNetFeatureExtractor class. Method signatures and docstrings: - def __init__(self, feature_layer='fc7_cudanet_out', pretrained_params='imagenet.decafnet.epoch90', pretrained_meta='imagenet.decafnet.meta', center_...
6fc9c749194f8a348f773aa989183ab9c751b008
<|skeleton|> class ConvNetFeatureExtractor: def __init__(self, feature_layer='fc7_cudanet_out', pretrained_params='imagenet.decafnet.epoch90', pretrained_meta='imagenet.decafnet.meta', center_only=True): """:param feature_layer: The ConvNet layer that's used for feature extraction. Defaults to `fc7_cudanet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConvNetFeatureExtractor: def __init__(self, feature_layer='fc7_cudanet_out', pretrained_params='imagenet.decafnet.epoch90', pretrained_meta='imagenet.decafnet.meta', center_only=True): """:param feature_layer: The ConvNet layer that's used for feature extraction. Defaults to `fc7_cudanet_out`. A descr...
the_stack_v2_python_sparse
src/feature_extractors/conv_net_feature_extractor.py
ktisha/object_class_recognition
train
0
a19770a27e469c5c481825c3e653fcffe2b28bab
[ "def traverse(node, cur_sum):\n if not node:\n return\n if not node.left and (not node.right):\n if cur_sum - node.val == 0:\n self.bool = True\n return\n if node.left:\n traverse(node.left, cur_sum - node.val)\n if node.right:\n traverse(node.right, cur_sum...
<|body_start_0|> def traverse(node, cur_sum): if not node: return if not node.left and (not node.right): if cur_sum - node.val == 0: self.bool = True return if node.left: traverse(node.left, c...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: """Purpose: Returns a boolean indicating whether a binary tree has a root-to-leaf path such that all values along the path add to `targetSum`.""" <|body_0|> def pathSumII(self, root, targetSum): ...
stack_v2_sparse_classes_36k_train_018228
3,110
no_license
[ { "docstring": "Purpose: Returns a boolean indicating whether a binary tree has a root-to-leaf path such that all values along the path add to `targetSum`.", "name": "hasPathSum", "signature": "def hasPathSum(self, root: TreeNode, targetSum: int) -> bool" }, { "docstring": "Purpose: Returns a li...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: Purpose: Returns a boolean indicating whether a binary tree has a root-to-leaf path such that all values along the p...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: Purpose: Returns a boolean indicating whether a binary tree has a root-to-leaf path such that all values along the p...
95a86cbbca28d0c0f6d72d28a2f1cb5a86327934
<|skeleton|> class Solution: def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: """Purpose: Returns a boolean indicating whether a binary tree has a root-to-leaf path such that all values along the path add to `targetSum`.""" <|body_0|> def pathSumII(self, root, targetSum): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: """Purpose: Returns a boolean indicating whether a binary tree has a root-to-leaf path such that all values along the path add to `targetSum`.""" def traverse(node, cur_sum): if not node: return...
the_stack_v2_python_sparse
pathSumMethods.py
tashakim/puzzles_python
train
8
205a72bd295953f65bf374c61a3efa7c02c839ec
[ "super().__init__()\nself.dim = dim\nself.dim_out = dim_out\nself.norm1 = norm_layer(dim)\nkernel_skip = [s + 1 if s > 1 else s for s in stride_q]\nstride_skip = stride_q\npadding_skip = [int(skip // 2) for skip in kernel_skip]\nself.attn = MultiScaleAttention(dim, num_heads=num_heads, qkv_bias=qkv_bias, dropout_ra...
<|body_start_0|> super().__init__() self.dim = dim self.dim_out = dim_out self.norm1 = norm_layer(dim) kernel_skip = [s + 1 if s > 1 else s for s in stride_q] stride_skip = stride_q padding_skip = [int(skip // 2) for skip in kernel_skip] self.attn = MultiS...
Implementation of a multiscale vision transformer block. Each block contains a multiscale attention layer and a Mlp layer. :: Input |-------------------+ ↓ | Norm | ↓ | MultiScaleAttention Pool ↓ | DropPath | ↓ | Summation ←-------------+ | |-------------------+ ↓ | Norm | ↓ | Mlp Proj ↓ | DropPath | ↓ | Summation ←---...
MultiScaleBlock
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiScaleBlock: """Implementation of a multiscale vision transformer block. Each block contains a multiscale attention layer and a Mlp layer. :: Input |-------------------+ ↓ | Norm | ↓ | MultiScaleAttention Pool ↓ | DropPath | ↓ | Summation ←-------------+ | |-------------------+ ↓ | Norm | ↓ |...
stack_v2_sparse_classes_36k_train_018229
21,342
permissive
[ { "docstring": "Args: dim (int): Input feature dimension. dim_out (int): Output feature dimension. num_heads (int): Number of heads in the attention layer. mlp_ratio (float): Mlp ratio which controls the feature dimension in the hidden layer of the Mlp block. qkv_bias (bool): If set to False, the qkv layer will...
2
stack_v2_sparse_classes_30k_train_016143
Implement the Python class `MultiScaleBlock` described below. Class description: Implementation of a multiscale vision transformer block. Each block contains a multiscale attention layer and a Mlp layer. :: Input |-------------------+ ↓ | Norm | ↓ | MultiScaleAttention Pool ↓ | DropPath | ↓ | Summation ←-------------+...
Implement the Python class `MultiScaleBlock` described below. Class description: Implementation of a multiscale vision transformer block. Each block contains a multiscale attention layer and a Mlp layer. :: Input |-------------------+ ↓ | Norm | ↓ | MultiScaleAttention Pool ↓ | DropPath | ↓ | Summation ←-------------+...
16f2abf2f8aa174915316007622bbb260215dee8
<|skeleton|> class MultiScaleBlock: """Implementation of a multiscale vision transformer block. Each block contains a multiscale attention layer and a Mlp layer. :: Input |-------------------+ ↓ | Norm | ↓ | MultiScaleAttention Pool ↓ | DropPath | ↓ | Summation ←-------------+ | |-------------------+ ↓ | Norm | ↓ |...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiScaleBlock: """Implementation of a multiscale vision transformer block. Each block contains a multiscale attention layer and a Mlp layer. :: Input |-------------------+ ↓ | Norm | ↓ | MultiScaleAttention Pool ↓ | DropPath | ↓ | Summation ←-------------+ | |-------------------+ ↓ | Norm | ↓ | Mlp Proj ↓ |...
the_stack_v2_python_sparse
pytorchvideo/layers/attention.py
xchani/pytorchvideo
train
0
5831972a5794dcf8aa9e0e00aea64dc737110f5c
[ "full_path = self._DISCOVERY_API_PATH_PREFIX + path\nheaders = {'Content-type': 'application/json'}\nconnection = httplib.HTTPSConnection(self._DISCOVERY_PROXY_HOST)\ntry:\n connection.request('POST', full_path, body, headers)\n response = connection.getresponse()\n response_body = response.read()\n if ...
<|body_start_0|> full_path = self._DISCOVERY_API_PATH_PREFIX + path headers = {'Content-type': 'application/json'} connection = httplib.HTTPSConnection(self._DISCOVERY_PROXY_HOST) try: connection.request('POST', full_path, body, headers) response = connection.getr...
Proxies discovery service requests to a known cloud endpoint.
DiscoveryApiProxy
[ "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DiscoveryApiProxy: """Proxies discovery service requests to a known cloud endpoint.""" def _dispatch_request(self, path, body): """Proxies GET request to discovery service API. Args: path: A string containing the URL path relative to discovery service. body: A string containing the H...
stack_v2_sparse_classes_36k_train_018230
3,900
permissive
[ { "docstring": "Proxies GET request to discovery service API. Args: path: A string containing the URL path relative to discovery service. body: A string containing the HTTP POST request body. Returns: HTTP response body or None if it failed.", "name": "_dispatch_request", "signature": "def _dispatch_req...
4
null
Implement the Python class `DiscoveryApiProxy` described below. Class description: Proxies discovery service requests to a known cloud endpoint. Method signatures and docstrings: - def _dispatch_request(self, path, body): Proxies GET request to discovery service API. Args: path: A string containing the URL path relat...
Implement the Python class `DiscoveryApiProxy` described below. Class description: Proxies discovery service requests to a known cloud endpoint. Method signatures and docstrings: - def _dispatch_request(self, path, body): Proxies GET request to discovery service API. Args: path: A string containing the URL path relat...
53102de187a48ac2cfc241fef54dcbc29c453a8e
<|skeleton|> class DiscoveryApiProxy: """Proxies discovery service requests to a known cloud endpoint.""" def _dispatch_request(self, path, body): """Proxies GET request to discovery service API. Args: path: A string containing the URL path relative to discovery service. body: A string containing the H...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DiscoveryApiProxy: """Proxies discovery service requests to a known cloud endpoint.""" def _dispatch_request(self, path, body): """Proxies GET request to discovery service API. Args: path: A string containing the URL path relative to discovery service. body: A string containing the HTTP POST requ...
the_stack_v2_python_sparse
third_party/google-endpoints/endpoints/discovery_api_proxy.py
catapult-project/catapult
train
2,032
8676856f96acc37f8505db7309cc431a5ab3b4b1
[ "df = pd.read_csv(csv_file, index_col=0)\ndf['ratio'] = df['count'].div(df['count'].shift(1)) - 1\ndf = df.dropna(subset=['ratio'])[['yearpd', 'ratio']]\nprint(df)", "df_armed = pd.read_csv(csv_shootings_armed, usecols=['race_name', 'armed', 'count'])\ndf_unarmed = pd.read_csv(csv_shootings_unarmed, usecols=['rac...
<|body_start_0|> df = pd.read_csv(csv_file, index_col=0) df['ratio'] = df['count'].div(df['count'].shift(1)) - 1 df = df.dropna(subset=['ratio'])[['yearpd', 'ratio']] print(df) <|end_body_0|> <|body_start_1|> df_armed = pd.read_csv(csv_shootings_armed, usecols=['race_name', 'arm...
MetricEvaluator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetricEvaluator: def m1(self, csv_file): """Computes the rate of increase for crime by year input: crimes_trend.csv""" <|body_0|> def m2(self, csv_shootings_armed, csv_shootings_unarmed): """Computes and compare the ratio of armed/not armed blacks dead with whites in...
stack_v2_sparse_classes_36k_train_018231
5,126
no_license
[ { "docstring": "Computes the rate of increase for crime by year input: crimes_trend.csv", "name": "m1", "signature": "def m1(self, csv_file)" }, { "docstring": "Computes and compare the ratio of armed/not armed blacks dead with whites input: armed.csv, unarmed.csv", "name": "m2", "signat...
5
stack_v2_sparse_classes_30k_train_020335
Implement the Python class `MetricEvaluator` described below. Class description: Implement the MetricEvaluator class. Method signatures and docstrings: - def m1(self, csv_file): Computes the rate of increase for crime by year input: crimes_trend.csv - def m2(self, csv_shootings_armed, csv_shootings_unarmed): Computes...
Implement the Python class `MetricEvaluator` described below. Class description: Implement the MetricEvaluator class. Method signatures and docstrings: - def m1(self, csv_file): Computes the rate of increase for crime by year input: crimes_trend.csv - def m2(self, csv_shootings_armed, csv_shootings_unarmed): Computes...
0f957f56e7df5beffdc6554375def95456841e87
<|skeleton|> class MetricEvaluator: def m1(self, csv_file): """Computes the rate of increase for crime by year input: crimes_trend.csv""" <|body_0|> def m2(self, csv_shootings_armed, csv_shootings_unarmed): """Computes and compare the ratio of armed/not armed blacks dead with whites in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MetricEvaluator: def m1(self, csv_file): """Computes the rate of increase for crime by year input: crimes_trend.csv""" df = pd.read_csv(csv_file, index_col=0) df['ratio'] = df['count'].div(df['count'].shift(1)) - 1 df = df.dropna(subset=['ratio'])[['yearpd', 'ratio']] p...
the_stack_v2_python_sparse
metrics.py
domk11/BigDataProjectCrimes
train
0
9fcf56722eb12d308e917e9dc1fd65371bb3ecfd
[ "self.account_id = account_id\nself.conference_id = conference_id\nself.name = name\nself.recording_id = recording_id\nself.duration = duration\nself.channels = channels\nself.start_time = APIHelper.RFC3339DateTime(start_time) if start_time else None\nself.end_time = APIHelper.RFC3339DateTime(end_time) if end_time ...
<|body_start_0|> self.account_id = account_id self.conference_id = conference_id self.name = name self.recording_id = recording_id self.duration = duration self.channels = channels self.start_time = APIHelper.RFC3339DateTime(start_time) if start_time else None ...
Implementation of the 'ConferenceRecordingMetadata' model. TODO: type model description here. Attributes: account_id (string): TODO: type description here. conference_id (string): TODO: type description here. name (string): TODO: type description here. recording_id (string): TODO: type description here. duration (strin...
ConferenceRecordingMetadata
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConferenceRecordingMetadata: """Implementation of the 'ConferenceRecordingMetadata' model. TODO: type model description here. Attributes: account_id (string): TODO: type description here. conference_id (string): TODO: type description here. name (string): TODO: type description here. recording_id...
stack_v2_sparse_classes_36k_train_018232
4,419
permissive
[ { "docstring": "Constructor for the ConferenceRecordingMetadata class", "name": "__init__", "signature": "def __init__(self, account_id=None, conference_id=None, name=None, recording_id=None, duration=None, channels=None, start_time=None, end_time=None, file_format=None, status=None, media_url=None)" ...
2
stack_v2_sparse_classes_30k_train_004916
Implement the Python class `ConferenceRecordingMetadata` described below. Class description: Implementation of the 'ConferenceRecordingMetadata' model. TODO: type model description here. Attributes: account_id (string): TODO: type description here. conference_id (string): TODO: type description here. name (string): TO...
Implement the Python class `ConferenceRecordingMetadata` described below. Class description: Implementation of the 'ConferenceRecordingMetadata' model. TODO: type model description here. Attributes: account_id (string): TODO: type description here. conference_id (string): TODO: type description here. name (string): TO...
447df3cc8cb7acaf3361d842630c432a9c31ce6e
<|skeleton|> class ConferenceRecordingMetadata: """Implementation of the 'ConferenceRecordingMetadata' model. TODO: type model description here. Attributes: account_id (string): TODO: type description here. conference_id (string): TODO: type description here. name (string): TODO: type description here. recording_id...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConferenceRecordingMetadata: """Implementation of the 'ConferenceRecordingMetadata' model. TODO: type model description here. Attributes: account_id (string): TODO: type description here. conference_id (string): TODO: type description here. name (string): TODO: type description here. recording_id (string): TO...
the_stack_v2_python_sparse
bandwidth/voice/models/conference_recording_metadata.py
Bandwidth/python-sdk
train
10
2c7ce517e2e7c10e7e1df4569b9ae5020580c498
[ "factor_collection = DB_CONN[factor]\nfactor_cursor = factor_collection.find({'code': code, 'date': {'$gte': begin_date, '$lte': end_date}}, sort=[('date', ASCENDING)])\nfactor_df = DataFrame([{'date': x['date'], factor: x[factor], 'code': x['code']} for x in factor_cursor])\nreturn factor_df", "factor_collection...
<|body_start_0|> factor_collection = DB_CONN[factor] factor_cursor = factor_collection.find({'code': code, 'date': {'$gte': begin_date, '$lte': end_date}}, sort=[('date', ASCENDING)]) factor_df = DataFrame([{'date': x['date'], factor: x[factor], 'code': x['code']} for x in factor_cursor]) ...
FactorModule
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FactorModule: def get_single_stock_factors(self, code, factor, begin_date, end_date): """获取某只股票的某个因子在一段时间内的值 :param code: 股票代码 :param factor: 因子名称 :param begin_date: 开始日期 :param end_date: 结束日期 :return: DataFrame(columns=['code',factor, 'date'])""" <|body_0|> def get_single_d...
stack_v2_sparse_classes_36k_train_018233
1,605
no_license
[ { "docstring": "获取某只股票的某个因子在一段时间内的值 :param code: 股票代码 :param factor: 因子名称 :param begin_date: 开始日期 :param end_date: 结束日期 :return: DataFrame(columns=['code',factor, 'date'])", "name": "get_single_stock_factors", "signature": "def get_single_stock_factors(self, code, factor, begin_date, end_date)" }, {...
2
stack_v2_sparse_classes_30k_train_000278
Implement the Python class `FactorModule` described below. Class description: Implement the FactorModule class. Method signatures and docstrings: - def get_single_stock_factors(self, code, factor, begin_date, end_date): 获取某只股票的某个因子在一段时间内的值 :param code: 股票代码 :param factor: 因子名称 :param begin_date: 开始日期 :param end_date:...
Implement the Python class `FactorModule` described below. Class description: Implement the FactorModule class. Method signatures and docstrings: - def get_single_stock_factors(self, code, factor, begin_date, end_date): 获取某只股票的某个因子在一段时间内的值 :param code: 股票代码 :param factor: 因子名称 :param begin_date: 开始日期 :param end_date:...
d93a55fda84052068ccd5c483f67eec6ffbec3f4
<|skeleton|> class FactorModule: def get_single_stock_factors(self, code, factor, begin_date, end_date): """获取某只股票的某个因子在一段时间内的值 :param code: 股票代码 :param factor: 因子名称 :param begin_date: 开始日期 :param end_date: 结束日期 :return: DataFrame(columns=['code',factor, 'date'])""" <|body_0|> def get_single_d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FactorModule: def get_single_stock_factors(self, code, factor, begin_date, end_date): """获取某只股票的某个因子在一段时间内的值 :param code: 股票代码 :param factor: 因子名称 :param begin_date: 开始日期 :param end_date: 结束日期 :return: DataFrame(columns=['code',factor, 'date'])""" factor_collection = DB_CONN[factor] fa...
the_stack_v2_python_sparse
xiaoxiang/06.第六课:交易决策子系统的实现—信号计算、仓位管理、风险管理/第6课代码/factor/factor_module.py
webclinic017/quantBigA
train
0
2c5b3255f2bc9fa3d96f5af3b5885f817ee45e34
[ "if minimum >= maximum:\n raise Error(\"Can't normalize to empty range: \" + f'[{(self.minimum, self.maximum)}]')\nself.minimum = tf.constant(minimum, dtype=tf.float32)\nself.maximum = tf.constant(maximum, dtype=tf.float32)\nsuper().__init__()", "length = self.maximum - self.minimum\nrange_too_large = tf.math....
<|body_start_0|> if minimum >= maximum: raise Error("Can't normalize to empty range: " + f'[{(self.minimum, self.maximum)}]') self.minimum = tf.constant(minimum, dtype=tf.float32) self.maximum = tf.constant(maximum, dtype=tf.float32) super().__init__() <|end_body_0|> <|body_...
Normalize a number in a given range to the range -1, 1.
NormalizeRange
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NormalizeRange: """Normalize a number in a given range to the range -1, 1.""" def __init__(self, minimum: float, maximum: float): """Create a NormalizeRange layer with the indicated range. Args: minimum: A float scalar representing the lower bound on the range. maximum: A float scala...
stack_v2_sparse_classes_36k_train_018234
14,886
permissive
[ { "docstring": "Create a NormalizeRange layer with the indicated range. Args: minimum: A float scalar representing the lower bound on the range. maximum: A float scalar representing the upper bound on the range. Raises: Error: If an empty range is specified.", "name": "__init__", "signature": "def __ini...
2
stack_v2_sparse_classes_30k_train_002697
Implement the Python class `NormalizeRange` described below. Class description: Normalize a number in a given range to the range -1, 1. Method signatures and docstrings: - def __init__(self, minimum: float, maximum: float): Create a NormalizeRange layer with the indicated range. Args: minimum: A float scalar represen...
Implement the Python class `NormalizeRange` described below. Class description: Normalize a number in a given range to the range -1, 1. Method signatures and docstrings: - def __init__(self, minimum: float, maximum: float): Create a NormalizeRange layer with the indicated range. Args: minimum: A float scalar represen...
26ab377a6853463b2efce40970e54d44b91e79ca
<|skeleton|> class NormalizeRange: """Normalize a number in a given range to the range -1, 1.""" def __init__(self, minimum: float, maximum: float): """Create a NormalizeRange layer with the indicated range. Args: minimum: A float scalar representing the lower bound on the range. maximum: A float scala...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NormalizeRange: """Normalize a number in a given range to the range -1, 1.""" def __init__(self, minimum: float, maximum: float): """Create a NormalizeRange layer with the indicated range. Args: minimum: A float scalar representing the lower bound on the range. maximum: A float scalar representin...
the_stack_v2_python_sparse
service/learner/brains/layers.py
stewartmiles/falken
train
1
c891ea6c60d4b38eeb7717a4f9bb87c812324201
[ "c = 1\nself.weight = weight\nself.age = age\nself.color = color\nc = 1", "c = 1\nres = super().__new__(cls)\nc = 1\nreturn res" ]
<|body_start_0|> c = 1 self.weight = weight self.age = age self.color = color c = 1 <|end_body_0|> <|body_start_1|> c = 1 res = super().__new__(cls) c = 1 return res <|end_body_1|>
Matryoshka
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Matryoshka: def __init__(self, weight, age, color): """Раскрашивает нашу болванку""" <|body_0|> def __new__(cls, *args, **kwargs): """Изготавливает пустую болванку""" <|body_1|> <|end_skeleton|> <|body_start_0|> c = 1 self.weight = weight ...
stack_v2_sparse_classes_36k_train_018235
8,031
no_license
[ { "docstring": "Раскрашивает нашу болванку", "name": "__init__", "signature": "def __init__(self, weight, age, color)" }, { "docstring": "Изготавливает пустую болванку", "name": "__new__", "signature": "def __new__(cls, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_002690
Implement the Python class `Matryoshka` described below. Class description: Implement the Matryoshka class. Method signatures and docstrings: - def __init__(self, weight, age, color): Раскрашивает нашу болванку - def __new__(cls, *args, **kwargs): Изготавливает пустую болванку
Implement the Python class `Matryoshka` described below. Class description: Implement the Matryoshka class. Method signatures and docstrings: - def __init__(self, weight, age, color): Раскрашивает нашу болванку - def __new__(cls, *args, **kwargs): Изготавливает пустую болванку <|skeleton|> class Matryoshka: def...
b3c1bc09a35d706d84a6ae67a484c7ae359cede8
<|skeleton|> class Matryoshka: def __init__(self, weight, age, color): """Раскрашивает нашу болванку""" <|body_0|> def __new__(cls, *args, **kwargs): """Изготавливает пустую болванку""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Matryoshka: def __init__(self, weight, age, color): """Раскрашивает нашу болванку""" c = 1 self.weight = weight self.age = age self.color = color c = 1 def __new__(cls, *args, **kwargs): """Изготавливает пустую болванку""" c = 1 res ...
the_stack_v2_python_sparse
dasha_folder/lesson_17.py
Totoro2205/for_my_shiny_students
train
0
6e61fc1cae406dabd9bba67eaa6a53f1565e2b51
[ "if amount == 0:\n return 1\nif not coins:\n return 0\nif amount < coins[0]:\n return 0\nglobal c\nc = 0\ncoins.sort()\n\ndef helper(i, count):\n global c\n if count == amount:\n c += 1\n return\n for j in range(i, len(coins)):\n if count + coins[j] > amount:\n brea...
<|body_start_0|> if amount == 0: return 1 if not coins: return 0 if amount < coins[0]: return 0 global c c = 0 coins.sort() def helper(i, count): global c if count == amount: c += 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def change(self, amount, coins): """回溯法,使用模板,排序解决重复使用问题 超出时间限制 :type amount: int :type coins: List[int] :rtype: int""" <|body_0|> def change2(self, amount, coins): """动态规划,完全背包问题 :param amount: :param coins: :return:""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_018236
2,253
no_license
[ { "docstring": "回溯法,使用模板,排序解决重复使用问题 超出时间限制 :type amount: int :type coins: List[int] :rtype: int", "name": "change", "signature": "def change(self, amount, coins)" }, { "docstring": "动态规划,完全背包问题 :param amount: :param coins: :return:", "name": "change2", "signature": "def change2(self, amo...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def change(self, amount, coins): 回溯法,使用模板,排序解决重复使用问题 超出时间限制 :type amount: int :type coins: List[int] :rtype: int - def change2(self, amount, coins): 动态规划,完全背包问题 :param amount: :p...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def change(self, amount, coins): 回溯法,使用模板,排序解决重复使用问题 超出时间限制 :type amount: int :type coins: List[int] :rtype: int - def change2(self, amount, coins): 动态规划,完全背包问题 :param amount: :p...
95dddb78bccd169d9d219a473627361fe739ab5e
<|skeleton|> class Solution: def change(self, amount, coins): """回溯法,使用模板,排序解决重复使用问题 超出时间限制 :type amount: int :type coins: List[int] :rtype: int""" <|body_0|> def change2(self, amount, coins): """动态规划,完全背包问题 :param amount: :param coins: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def change(self, amount, coins): """回溯法,使用模板,排序解决重复使用问题 超出时间限制 :type amount: int :type coins: List[int] :rtype: int""" if amount == 0: return 1 if not coins: return 0 if amount < coins[0]: return 0 global c c = 0 ...
the_stack_v2_python_sparse
DrasticPlan/coinChange2.py
Philex5/codingPractice
train
0
e4791412da0cc3439476c78f0b8df7db19e05957
[ "if self.instance.status != FinancialAidStatus.PENDING_DOCS:\n raise ValidationError('Cannot indicate documents sent for an application that is not pending documents')\nreturn data", "self.instance.status = FinancialAidStatus.DOCS_SENT\nself.instance.date_documents_sent = self.validated_data['date_documents_se...
<|body_start_0|> if self.instance.status != FinancialAidStatus.PENDING_DOCS: raise ValidationError('Cannot indicate documents sent for an application that is not pending documents') return data <|end_body_0|> <|body_start_1|> self.instance.status = FinancialAidStatus.DOCS_SENT ...
Serializer for indicating financial documents have been sent
FinancialAidSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FinancialAidSerializer: """Serializer for indicating financial documents have been sent""" def validate(self, data): """Validate method for this serializer""" <|body_0|> def save(self): """Save method for this serializer""" <|body_1|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_018237
6,670
no_license
[ { "docstring": "Validate method for this serializer", "name": "validate", "signature": "def validate(self, data)" }, { "docstring": "Save method for this serializer", "name": "save", "signature": "def save(self)" } ]
2
stack_v2_sparse_classes_30k_train_002715
Implement the Python class `FinancialAidSerializer` described below. Class description: Serializer for indicating financial documents have been sent Method signatures and docstrings: - def validate(self, data): Validate method for this serializer - def save(self): Save method for this serializer
Implement the Python class `FinancialAidSerializer` described below. Class description: Serializer for indicating financial documents have been sent Method signatures and docstrings: - def validate(self, data): Validate method for this serializer - def save(self): Save method for this serializer <|skeleton|> class F...
3c166bc52dfe8d7aa04f922134f4f6deeff49eb6
<|skeleton|> class FinancialAidSerializer: """Serializer for indicating financial documents have been sent""" def validate(self, data): """Validate method for this serializer""" <|body_0|> def save(self): """Save method for this serializer""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FinancialAidSerializer: """Serializer for indicating financial documents have been sent""" def validate(self, data): """Validate method for this serializer""" if self.instance.status != FinancialAidStatus.PENDING_DOCS: raise ValidationError('Cannot indicate documents sent for ...
the_stack_v2_python_sparse
financialaid/serializers.py
avontd2868/micromasters
train
0
e2f915cf1d9ac338204783620731e4efc1bf5f83
[ "params = request.GET\ncomment_id = params.get('comment_id')\nif comment_id:\n try:\n return Comment.objects.get(pk=comment_id, is_removed=False, is_public=True)\n except Comment.DoesNotExist:\n return rc.NOT_HERE\ntid = params.get('tid')\nct = ContentType.objects.get_by_natural_key('kinger', 't...
<|body_start_0|> params = request.GET comment_id = params.get('comment_id') if comment_id: try: return Comment.objects.get(pk=comment_id, is_removed=False, is_public=True) except Comment.DoesNotExist: return rc.NOT_HERE tid = params...
Api for comments resource
CommentHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommentHandler: """Api for comments resource""" def get(self, request): """获得某条瓦片的评论详细信息 ``GET`` `comments/show/ <http://192.168.1.222:8080/v1/comments/show>`_ :param tid: 瓦片 id. :param comment_id: 某条评论的 id""" <|body_0|> def post(self, request): """发布一条评论 ``POST`...
stack_v2_sparse_classes_36k_train_018238
5,451
no_license
[ { "docstring": "获得某条瓦片的评论详细信息 ``GET`` `comments/show/ <http://192.168.1.222:8080/v1/comments/show>`_ :param tid: 瓦片 id. :param comment_id: 某条评论的 id", "name": "get", "signature": "def get(self, request)" }, { "docstring": "发布一条评论 ``POST`` `comments/create/ <http://192.168.1.222:8080/v1/comments/c...
3
null
Implement the Python class `CommentHandler` described below. Class description: Api for comments resource Method signatures and docstrings: - def get(self, request): 获得某条瓦片的评论详细信息 ``GET`` `comments/show/ <http://192.168.1.222:8080/v1/comments/show>`_ :param tid: 瓦片 id. :param comment_id: 某条评论的 id - def post(self, req...
Implement the Python class `CommentHandler` described below. Class description: Api for comments resource Method signatures and docstrings: - def get(self, request): 获得某条瓦片的评论详细信息 ``GET`` `comments/show/ <http://192.168.1.222:8080/v1/comments/show>`_ :param tid: 瓦片 id. :param comment_id: 某条评论的 id - def post(self, req...
1b1fbe4c66df731f63f10c57dee20cb0bb4edb4c
<|skeleton|> class CommentHandler: """Api for comments resource""" def get(self, request): """获得某条瓦片的评论详细信息 ``GET`` `comments/show/ <http://192.168.1.222:8080/v1/comments/show>`_ :param tid: 瓦片 id. :param comment_id: 某条评论的 id""" <|body_0|> def post(self, request): """发布一条评论 ``POST`...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommentHandler: """Api for comments resource""" def get(self, request): """获得某条瓦片的评论详细信息 ``GET`` `comments/show/ <http://192.168.1.222:8080/v1/comments/show>`_ :param tid: 瓦片 id. :param comment_id: 某条评论的 id""" params = request.GET comment_id = params.get('comment_id') if c...
the_stack_v2_python_sparse
apiv2/handlers/comment.py
nuannuanwu/weixiao
train
1
a855b2d8d75c73709dfd91c3ac9d2e49ebe96ff3
[ "if not nums:\n return []\nres, root = ([], [])\n\ndef backref(nums, res, root):\n if len(root) == len(nums):\n res.append(root[:])\n return\n for i in nums:\n if i in root:\n continue\n root.append(i)\n backref(nums, res, root)\n root.remove(i)\nbackref...
<|body_start_0|> if not nums: return [] res, root = ([], []) def backref(nums, res, root): if len(root) == len(nums): res.append(root[:]) return for i in nums: if i in root: continue ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def permute(self, nums: list) -> list: """针对没有重复元素的全排列""" <|body_0|> def permute_1(self, nums: list) -> list: """和上面的思路基本一致""" <|body_1|> def permute_2(self, nums: list) -> list: """针对有重复元素的全排列""" <|body_2|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_018239
2,834
no_license
[ { "docstring": "针对没有重复元素的全排列", "name": "permute", "signature": "def permute(self, nums: list) -> list" }, { "docstring": "和上面的思路基本一致", "name": "permute_1", "signature": "def permute_1(self, nums: list) -> list" }, { "docstring": "针对有重复元素的全排列", "name": "permute_2", "signat...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def permute(self, nums: list) -> list: 针对没有重复元素的全排列 - def permute_1(self, nums: list) -> list: 和上面的思路基本一致 - def permute_2(self, nums: list) -> list: 针对有重复元素的全排列
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def permute(self, nums: list) -> list: 针对没有重复元素的全排列 - def permute_1(self, nums: list) -> list: 和上面的思路基本一致 - def permute_2(self, nums: list) -> list: 针对有重复元素的全排列 <|skeleton|> cla...
3508e1ce089131b19603c3206aab4cf43023bb19
<|skeleton|> class Solution: def permute(self, nums: list) -> list: """针对没有重复元素的全排列""" <|body_0|> def permute_1(self, nums: list) -> list: """和上面的思路基本一致""" <|body_1|> def permute_2(self, nums: list) -> list: """针对有重复元素的全排列""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def permute(self, nums: list) -> list: """针对没有重复元素的全排列""" if not nums: return [] res, root = ([], []) def backref(nums, res, root): if len(root) == len(nums): res.append(root[:]) return for i in nums...
the_stack_v2_python_sparse
algorithm/leetcode/backtracking/01-全排列.py
lxconfig/UbuntuCode_bak
train
0
dfcf93c63081b448b7919b041633701edd045b27
[ "base_url = 'https://stores.joann.com/{}'\nfor state in STATES:\n state_url = base_url.format(state)\n request = scrapy.Request(state_url, callback=self.parse_state, headers=HEADERS)\n request.meta['state'] = state\n yield request", "state_url = 'stores.joann.com/{}*'.format(response.meta['state'])\ne...
<|body_start_0|> base_url = 'https://stores.joann.com/{}' for state in STATES: state_url = base_url.format(state) request = scrapy.Request(state_url, callback=self.parse_state, headers=HEADERS) request.meta['state'] = state yield request <|end_body_0|> <|...
JoAnnFabricsSpider
[ "MIT", "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JoAnnFabricsSpider: def start_requests(self): """Yields a scrapy.Request object for each state in the USA""" <|body_0|> def parse_state(self, response): """Yields a scrapy.Request object for each city with a store in the state""" <|body_1|> def parse_cit...
stack_v2_sparse_classes_36k_train_018240
3,220
permissive
[ { "docstring": "Yields a scrapy.Request object for each state in the USA", "name": "start_requests", "signature": "def start_requests(self)" }, { "docstring": "Yields a scrapy.Request object for each city with a store in the state", "name": "parse_state", "signature": "def parse_state(se...
5
null
Implement the Python class `JoAnnFabricsSpider` described below. Class description: Implement the JoAnnFabricsSpider class. Method signatures and docstrings: - def start_requests(self): Yields a scrapy.Request object for each state in the USA - def parse_state(self, response): Yields a scrapy.Request object for each ...
Implement the Python class `JoAnnFabricsSpider` described below. Class description: Implement the JoAnnFabricsSpider class. Method signatures and docstrings: - def start_requests(self): Yields a scrapy.Request object for each state in the USA - def parse_state(self, response): Yields a scrapy.Request object for each ...
ac4d4783572d55c0799fe6aeb5f6c0e72fad55fb
<|skeleton|> class JoAnnFabricsSpider: def start_requests(self): """Yields a scrapy.Request object for each state in the USA""" <|body_0|> def parse_state(self, response): """Yields a scrapy.Request object for each city with a store in the state""" <|body_1|> def parse_cit...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JoAnnFabricsSpider: def start_requests(self): """Yields a scrapy.Request object for each state in the USA""" base_url = 'https://stores.joann.com/{}' for state in STATES: state_url = base_url.format(state) request = scrapy.Request(state_url, callback=self.parse_...
the_stack_v2_python_sparse
locations/spiders/joann_fabrics.py
thomas536/alltheplaces
train
0
d7b106f05df134d2fa2d3bfd997385fdd56236ec
[ "requestor = Requestor(local_api_key=api_key)\nurl = cls.class_url()\nwrapped_params = {cls.snakecase_name(): params}\nresponse, api_key = requestor.request(method=RequestMethod.POST, url=url, params=wrapped_params)\nreturn convert_to_easypost_object(response=response, api_key=api_key)", "if not easypost_id:\n ...
<|body_start_0|> requestor = Requestor(local_api_key=api_key) url = cls.class_url() wrapped_params = {cls.snakecase_name(): params} response, api_key = requestor.request(method=RequestMethod.POST, url=url, params=wrapped_params) return convert_to_easypost_object(response=response...
User
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class User: def create(cls, api_key: Optional[str]=None, **params) -> 'User': """Create a child user.""" <|body_0|> def retrieve(cls, easypost_id: Optional[str]=None, api_key: Optional[str]=None, **params) -> 'User': """Retrieve a user.""" <|body_1|> def retri...
stack_v2_sparse_classes_36k_train_018241
3,246
permissive
[ { "docstring": "Create a child user.", "name": "create", "signature": "def create(cls, api_key: Optional[str]=None, **params) -> 'User'" }, { "docstring": "Retrieve a user.", "name": "retrieve", "signature": "def retrieve(cls, easypost_id: Optional[str]=None, api_key: Optional[str]=None,...
6
stack_v2_sparse_classes_30k_train_011013
Implement the Python class `User` described below. Class description: Implement the User class. Method signatures and docstrings: - def create(cls, api_key: Optional[str]=None, **params) -> 'User': Create a child user. - def retrieve(cls, easypost_id: Optional[str]=None, api_key: Optional[str]=None, **params) -> 'Use...
Implement the Python class `User` described below. Class description: Implement the User class. Method signatures and docstrings: - def create(cls, api_key: Optional[str]=None, **params) -> 'User': Create a child user. - def retrieve(cls, easypost_id: Optional[str]=None, api_key: Optional[str]=None, **params) -> 'Use...
c8f7a3f2472ae5fea13a5b596b4618bd55f3be0c
<|skeleton|> class User: def create(cls, api_key: Optional[str]=None, **params) -> 'User': """Create a child user.""" <|body_0|> def retrieve(cls, easypost_id: Optional[str]=None, api_key: Optional[str]=None, **params) -> 'User': """Retrieve a user.""" <|body_1|> def retri...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class User: def create(cls, api_key: Optional[str]=None, **params) -> 'User': """Create a child user.""" requestor = Requestor(local_api_key=api_key) url = cls.class_url() wrapped_params = {cls.snakecase_name(): params} response, api_key = requestor.request(method=RequestMeth...
the_stack_v2_python_sparse
easypost/user.py
dsanders11/easypost-python
train
0
518c717cd995a97c9decd1e4cf08f2e9e8c9ad81
[ "super(AutoEncoderEnvironmentModel, self).__init__()\nself.encoder = encoder\nself.decoder = decoder\nself.observation_shape = observation_shape\nself.num_actions = num_actions\nself.reward_size = reward_size\nself.use_cuda = use_cuda\nself.reward_fc = nn.Linear(self.encoder.get_feature_shape(), self.reward_size)\n...
<|body_start_0|> super(AutoEncoderEnvironmentModel, self).__init__() self.encoder = encoder self.decoder = decoder self.observation_shape = observation_shape self.num_actions = num_actions self.reward_size = reward_size self.use_cuda = use_cuda self.reward...
AutoEncoderEnvironmentModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AutoEncoderEnvironmentModel: def __init__(self, encoder, decoder, observation_shape, num_actions, reward_size, use_cuda=False): """:param encoder: :param decoder: :param observation_shape: shape depth x height x width. :param num_actions: number of actions that are available in the envir...
stack_v2_sparse_classes_36k_train_018242
2,222
permissive
[ { "docstring": ":param encoder: :param decoder: :param observation_shape: shape depth x height x width. :param num_actions: number of actions that are available in the environment. :param reward_size: number of dimensions of the reward vector. Eventhough OpenAI Gym Interface always provides scalar reward functi...
2
stack_v2_sparse_classes_30k_train_005403
Implement the Python class `AutoEncoderEnvironmentModel` described below. Class description: Implement the AutoEncoderEnvironmentModel class. Method signatures and docstrings: - def __init__(self, encoder, decoder, observation_shape, num_actions, reward_size, use_cuda=False): :param encoder: :param decoder: :param ob...
Implement the Python class `AutoEncoderEnvironmentModel` described below. Class description: Implement the AutoEncoderEnvironmentModel class. Method signatures and docstrings: - def __init__(self, encoder, decoder, observation_shape, num_actions, reward_size, use_cuda=False): :param encoder: :param decoder: :param ob...
825c7dacf955a3e2f6c658c0ecb879a0ca036c1a
<|skeleton|> class AutoEncoderEnvironmentModel: def __init__(self, encoder, decoder, observation_shape, num_actions, reward_size, use_cuda=False): """:param encoder: :param decoder: :param observation_shape: shape depth x height x width. :param num_actions: number of actions that are available in the envir...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AutoEncoderEnvironmentModel: def __init__(self, encoder, decoder, observation_shape, num_actions, reward_size, use_cuda=False): """:param encoder: :param decoder: :param observation_shape: shape depth x height x width. :param num_actions: number of actions that are available in the environment. :param...
the_stack_v2_python_sparse
regym/rl_algorithms/algorithms/I2A/autoencoder_environment_model.py
Near32/Regym
train
4
3d4e524d94a9dca353e995268487e3bb6a147be5
[ "compound_list = []\ncompound_entry = info_dict.get('Compounds')\nif compound_entry:\n for family_annotation in compound_entry.split(','):\n compounds = family_annotation.split(':')[-1].split('|')\n for compound in compounds:\n splitted_compound = compound.split('>')\n compoun...
<|body_start_0|> compound_list = [] compound_entry = info_dict.get('Compounds') if compound_entry: for family_annotation in compound_entry.split(','): compounds = family_annotation.split(':')[-1].split('|') for compound in compounds: ...
Mixin class to store methods that deals with parsing annotations
AnnotationExtras
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnnotationExtras: """Mixin class to store methods that deals with parsing annotations""" def _add_compounds(self, variant_obj, info_dict): """Check if there are any compounds and add them to the variant The compounds that are added should be sorted on rank score""" <|body_0|>...
stack_v2_sparse_classes_36k_train_018243
3,385
permissive
[ { "docstring": "Check if there are any compounds and add them to the variant The compounds that are added should be sorted on rank score", "name": "_add_compounds", "signature": "def _add_compounds(self, variant_obj, info_dict)" }, { "docstring": "Add the cadd score to the variant Args: variant_...
4
stack_v2_sparse_classes_30k_train_018890
Implement the Python class `AnnotationExtras` described below. Class description: Mixin class to store methods that deals with parsing annotations Method signatures and docstrings: - def _add_compounds(self, variant_obj, info_dict): Check if there are any compounds and add them to the variant The compounds that are a...
Implement the Python class `AnnotationExtras` described below. Class description: Mixin class to store methods that deals with parsing annotations Method signatures and docstrings: - def _add_compounds(self, variant_obj, info_dict): Check if there are any compounds and add them to the variant The compounds that are a...
9476f05b416d3a5135d25492cb31411fdf831c58
<|skeleton|> class AnnotationExtras: """Mixin class to store methods that deals with parsing annotations""" def _add_compounds(self, variant_obj, info_dict): """Check if there are any compounds and add them to the variant The compounds that are added should be sorted on rank score""" <|body_0|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AnnotationExtras: """Mixin class to store methods that deals with parsing annotations""" def _add_compounds(self, variant_obj, info_dict): """Check if there are any compounds and add them to the variant The compounds that are added should be sorted on rank score""" compound_list = [] ...
the_stack_v2_python_sparse
puzzle/plugins/vcf/mixins/variant_extras/annotations.py
haoziyeung/puzzle
train
0
c5f5490146234380dcb74910bddcb9bbdd8399c6
[ "s = math.factorial(n)\nl = 0\nfor i in reversed(str(s)):\n if i == '0':\n l += 1\n else:\n return l\nreturn l", "if n == 0:\n return 0\nreturn n / 5 + self.trailingZeroes(n - 1) if n % 5 == 0 else self.trailingZeroes(n - 1)", "if n == 0:\n return 0\nreturn n / 5 + self.trailingZeroes(...
<|body_start_0|> s = math.factorial(n) l = 0 for i in reversed(str(s)): if i == '0': l += 1 else: return l return l <|end_body_0|> <|body_start_1|> if n == 0: return 0 return n / 5 + self.trailingZeroes(...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _trailingZeroes(self, n): """:type n: int :rtype: int""" <|body_0|> def __trailingZeroes(self, n): """:type n: int :rtype: int""" <|body_1|> def trailingZeroes(self, n): """:type n: int :rtype: int""" <|body_2|> def ___...
stack_v2_sparse_classes_36k_train_018244
1,964
permissive
[ { "docstring": ":type n: int :rtype: int", "name": "_trailingZeroes", "signature": "def _trailingZeroes(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "__trailingZeroes", "signature": "def __trailingZeroes(self, n)" }, { "docstring": ":type n: int :rtype: int", ...
4
stack_v2_sparse_classes_30k_train_020011
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _trailingZeroes(self, n): :type n: int :rtype: int - def __trailingZeroes(self, n): :type n: int :rtype: int - def trailingZeroes(self, n): :type n: int :rtype: int - def ___...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _trailingZeroes(self, n): :type n: int :rtype: int - def __trailingZeroes(self, n): :type n: int :rtype: int - def trailingZeroes(self, n): :type n: int :rtype: int - def ___...
0dd67edca4e0b0323cb5a7239f02ea46383cd15a
<|skeleton|> class Solution: def _trailingZeroes(self, n): """:type n: int :rtype: int""" <|body_0|> def __trailingZeroes(self, n): """:type n: int :rtype: int""" <|body_1|> def trailingZeroes(self, n): """:type n: int :rtype: int""" <|body_2|> def ___...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def _trailingZeroes(self, n): """:type n: int :rtype: int""" s = math.factorial(n) l = 0 for i in reversed(str(s)): if i == '0': l += 1 else: return l return l def __trailingZeroes(self, n): ...
the_stack_v2_python_sparse
172.factorial-trailing-zeroes.py
windard/leeeeee
train
0
5861cc01c4a420be5f5f333481614ec63a6891f1
[ "if len(directory_path) > 0:\n if not os.path.isdir(directory_path):\n raise Exception('Path {} for '.format(directory_path) + 'StructDict construction was not a directory.')\n self.update(read(directory_path, file_format=file_format))", "if type(struct) == dict:\n for key, value in struct.items()...
<|body_start_0|> if len(directory_path) > 0: if not os.path.isdir(directory_path): raise Exception('Path {} for '.format(directory_path) + 'StructDict construction was not a directory.') self.update(read(directory_path, file_format=file_format)) <|end_body_0|> <|body_sta...
Specifies the behavior of a StructDict which is abbreviated as struct_dict throughout the code base. The StructDict behaves exactly the same as a Python dictionary where each key is the struct_id and each value is a Structure.
StructDict
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StructDict: """Specifies the behavior of a StructDict which is abbreviated as struct_dict throughout the code base. The StructDict behaves exactly the same as a Python dictionary where each key is the struct_id and each value is a Structure.""" def __init__(self, directory_path='', file_form...
stack_v2_sparse_classes_36k_train_018245
8,467
permissive
[ { "docstring": "Creates StructDict for the optional input directory path.", "name": "__init__", "signature": "def __init__(self, directory_path='', file_format='')" }, { "docstring": "Behaves as a wrapper to append", "name": "update", "signature": "def update(self, struct)" }, { ...
3
stack_v2_sparse_classes_30k_train_007704
Implement the Python class `StructDict` described below. Class description: Specifies the behavior of a StructDict which is abbreviated as struct_dict throughout the code base. The StructDict behaves exactly the same as a Python dictionary where each key is the struct_id and each value is a Structure. Method signatur...
Implement the Python class `StructDict` described below. Class description: Specifies the behavior of a StructDict which is abbreviated as struct_dict throughout the code base. The StructDict behaves exactly the same as a Python dictionary where each key is the struct_id and each value is a Structure. Method signatur...
142d6f6b4f852b23aa8cfdae1593db207363e30e
<|skeleton|> class StructDict: """Specifies the behavior of a StructDict which is abbreviated as struct_dict throughout the code base. The StructDict behaves exactly the same as a Python dictionary where each key is the struct_id and each value is a Structure.""" def __init__(self, directory_path='', file_form...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StructDict: """Specifies the behavior of a StructDict which is abbreviated as struct_dict throughout the code base. The StructDict behaves exactly the same as a Python dictionary where each key is the struct_id and each value is a Structure.""" def __init__(self, directory_path='', file_format=''): ...
the_stack_v2_python_sparse
mcse/core/struct_dict.py
manny405/mcse
train
6
2c56abeb2396749edb0ac6a156b985fc6cf2b939
[ "form_opts = self.request.GET.copy()\ntry:\n del form_opts['page']\nexcept KeyError:\n pass\nself.form = self.form_class(form_opts or self.form_class.defaults)\nif self.form.is_valid():\n search_opts = self.form.cleaned_data\n if search_opts['content_type'] != 'all':\n if search_opts['content_typ...
<|body_start_0|> form_opts = self.request.GET.copy() try: del form_opts['page'] except KeyError: pass self.form = self.form_class(form_opts or self.form_class.defaults) if self.form.is_valid(): search_opts = self.form.cleaned_data i...
SearchView
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SearchView: def get(self, *args, **kwargs): """Process form for :class:`SearchView`.""" <|body_0|> def get_context_data(self, **kwargs): """Retrieve Solr queries for :class:`SearchView` context.""" <|body_1|> <|end_skeleton|> <|body_start_0|> form_o...
stack_v2_sparse_classes_36k_train_018246
37,410
permissive
[ { "docstring": "Process form for :class:`SearchView`.", "name": "get", "signature": "def get(self, *args, **kwargs)" }, { "docstring": "Retrieve Solr queries for :class:`SearchView` context.", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_019580
Implement the Python class `SearchView` described below. Class description: Implement the SearchView class. Method signatures and docstrings: - def get(self, *args, **kwargs): Process form for :class:`SearchView`. - def get_context_data(self, **kwargs): Retrieve Solr queries for :class:`SearchView` context.
Implement the Python class `SearchView` described below. Class description: Implement the SearchView class. Method signatures and docstrings: - def get(self, *args, **kwargs): Process form for :class:`SearchView`. - def get_context_data(self, **kwargs): Retrieve Solr queries for :class:`SearchView` context. <|skelet...
6371bb1266d7751af59aeaa3426ef7ac02a1fe17
<|skeleton|> class SearchView: def get(self, *args, **kwargs): """Process form for :class:`SearchView`.""" <|body_0|> def get_context_data(self, **kwargs): """Retrieve Solr queries for :class:`SearchView` context.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SearchView: def get(self, *args, **kwargs): """Process form for :class:`SearchView`.""" form_opts = self.request.GET.copy() try: del form_opts['page'] except KeyError: pass self.form = self.form_class(form_opts or self.form_class.defaults) ...
the_stack_v2_python_sparse
derrida/books/views.py
Princeton-CDH/derrida-django
train
13
85068b845fc62bc3ca6b9307072225de0f5d380f
[ "self.w = width\nself.h = height\nself.food = deque(food)\nself.body = deque([(0, 0)])\nself.dirs = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}\nself.eat = 0", "x, y = self.body[0]\ndx, dy = self.dirs[direction]\nx += dx\ny += dy\nfx, fy = self.food[0] if self.food else (-1, -1)\nif x == fx and y == fy...
<|body_start_0|> self.w = width self.h = height self.food = deque(food) self.body = deque([(0, 0)]) self.dirs = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)} self.eat = 0 <|end_body_0|> <|body_start_1|> x, y = self.body[0] dx, dy = self.dirs[dire...
SnakeGame
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SnakeGame: def __init__(self, width, height, food): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ...
stack_v2_sparse_classes_36k_train_018247
2,043
permissive
[ { "docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]", ...
2
null
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E...
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E...
cbbd4a67ab342ada2421e13f82d660b1d47d4d20
<|skeleton|> class SnakeGame: def __init__(self, width, height, food): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SnakeGame: def __init__(self, width, height, food): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :...
the_stack_v2_python_sparse
353 Design Snake Game.py
Aminaba123/LeetCode
train
1
3f2fc192072a292440709ab2683b38c607d4c722
[ "assert fanouts, 'fanouts must be specified'\nconfig = dict(fanouts=fanouts)\nconfig.update(kwargs)\nsuper().__init__(config=config)\nself.fanouts = fanouts\nself.fanouts_list = get_fanouts_list(fanouts)\nself.fanouts_dim = sum(self.fanouts_list)\nself.fanouts_indices = get_fanouts_indices(fanouts)\nself.sort_indic...
<|body_start_0|> assert fanouts, 'fanouts must be specified' config = dict(fanouts=fanouts) config.update(kwargs) super().__init__(config=config) self.fanouts = fanouts self.fanouts_list = get_fanouts_list(fanouts) self.fanouts_dim = sum(self.fanouts_list) ...
\\brief transform multi hops to relation graph \\details a relation graph is a dict: \\code{.py} dict( relation_indices=tensor, relation_weight=tensor, target_indices=tensor, ) \\endcode relation_indices is a [2,E] int tensor, E is number of edges,\\n indices of relation/edge of graph relation_weight is a [E,1] float t...
RelationTransform
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-2-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelationTransform: """\\brief transform multi hops to relation graph \\details a relation graph is a dict: \\code{.py} dict( relation_indices=tensor, relation_weight=tensor, target_indices=tensor, ) \\endcode relation_indices is a [2,E] int tensor, E is number of edges,\\n indices of relation/edg...
stack_v2_sparse_classes_36k_train_018248
4,420
permissive
[ { "docstring": "\\\\param fanouts number of multi hop \\\\param sort_indices sort relation indices", "name": "__init__", "signature": "def __init__(self, fanouts: list, sort_indices: bool=False, **kwargs)" }, { "docstring": "\\\\param inputs list or tuple or \\\\n dict(indices=tensor, edge_weigh...
2
null
Implement the Python class `RelationTransform` described below. Class description: \\brief transform multi hops to relation graph \\details a relation graph is a dict: \\code{.py} dict( relation_indices=tensor, relation_weight=tensor, target_indices=tensor, ) \\endcode relation_indices is a [2,E] int tensor, E is numb...
Implement the Python class `RelationTransform` described below. Class description: \\brief transform multi hops to relation graph \\details a relation graph is a dict: \\code{.py} dict( relation_indices=tensor, relation_weight=tensor, target_indices=tensor, ) \\endcode relation_indices is a [2,E] int tensor, E is numb...
48099ec3f0331196c6812208ceb080ba618a588b
<|skeleton|> class RelationTransform: """\\brief transform multi hops to relation graph \\details a relation graph is a dict: \\code{.py} dict( relation_indices=tensor, relation_weight=tensor, target_indices=tensor, ) \\endcode relation_indices is a [2,E] int tensor, E is number of edges,\\n indices of relation/edg...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RelationTransform: """\\brief transform multi hops to relation graph \\details a relation graph is a dict: \\code{.py} dict( relation_indices=tensor, relation_weight=tensor, target_indices=tensor, ) \\endcode relation_indices is a [2,E] int tensor, E is number of edges,\\n indices of relation/edge of graph re...
the_stack_v2_python_sparse
galileo/framework/pytorch/python/transforms/relation.py
2012fang1/galileo
train
0
76b7d00085e4188bb4ae21443fea4e2d3d10f90a
[ "try:\n page = abs(int(self.get_argument('page', '1')))\n step = abs(int(self.get_argument('step', '20')))\n start = (page - 1) * step\nexcept (ValueError, KeyError):\n return await self.finish({'code': response_code.ParameterError})\nasync with aiomysql.create_pool(host='192.168.80.128', port=3306, use...
<|body_start_0|> try: page = abs(int(self.get_argument('page', '1'))) step = abs(int(self.get_argument('step', '20'))) start = (page - 1) * step except (ValueError, KeyError): return await self.finish({'code': response_code.ParameterError}) async w...
技战法管理器
TacticsManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TacticsManager: """技战法管理器""" async def get(self) -> None: """根据字典type值获取相关字典数据,动态资源 :param manager_id: :return:""" <|body_0|> async def post(self) -> None: """添加技战法处理 :return:""" <|body_1|> async def put(self) -> None: """修改技战法 :param manager...
stack_v2_sparse_classes_36k_train_018249
19,675
no_license
[ { "docstring": "根据字典type值获取相关字典数据,动态资源 :param manager_id: :return:", "name": "get", "signature": "async def get(self) -> None" }, { "docstring": "添加技战法处理 :return:", "name": "post", "signature": "async def post(self) -> None" }, { "docstring": "修改技战法 :param manager_id: :return:", ...
3
stack_v2_sparse_classes_30k_train_018426
Implement the Python class `TacticsManager` described below. Class description: 技战法管理器 Method signatures and docstrings: - async def get(self) -> None: 根据字典type值获取相关字典数据,动态资源 :param manager_id: :return: - async def post(self) -> None: 添加技战法处理 :return: - async def put(self) -> None: 修改技战法 :param manager_id: :return:
Implement the Python class `TacticsManager` described below. Class description: 技战法管理器 Method signatures and docstrings: - async def get(self) -> None: 根据字典type值获取相关字典数据,动态资源 :param manager_id: :return: - async def post(self) -> None: 添加技战法处理 :return: - async def put(self) -> None: 修改技战法 :param manager_id: :return: ...
e2fc98c7262cc06f7687530d23a626f250dabb58
<|skeleton|> class TacticsManager: """技战法管理器""" async def get(self) -> None: """根据字典type值获取相关字典数据,动态资源 :param manager_id: :return:""" <|body_0|> async def post(self) -> None: """添加技战法处理 :return:""" <|body_1|> async def put(self) -> None: """修改技战法 :param manager...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TacticsManager: """技战法管理器""" async def get(self) -> None: """根据字典type值获取相关字典数据,动态资源 :param manager_id: :return:""" try: page = abs(int(self.get_argument('page', '1'))) step = abs(int(self.get_argument('step', '20'))) start = (page - 1) * step ex...
the_stack_v2_python_sparse
tornado_test/filehandler.py
yanghusf/Code
train
0
aefc90c00da4d0b3e669e90055fa5a8d70b530cf
[ "if not host or (not host.ips and (not host.name)):\n raise ValueError('Invalid host')\nif host.name:\n osh = ObjectStateHolder(self.CIT)\n osh.setStringAttribute('name', host.name)\nelse:\n osh = self.build_complete_host(str(host.ips[0]))\nif host.fqdns:\n osh.setStringAttribute('primary_dns_name', ...
<|body_start_0|> if not host or (not host.ips and (not host.name)): raise ValueError('Invalid host') if host.name: osh = ObjectStateHolder(self.CIT) osh.setStringAttribute('name', host.name) else: osh = self.build_complete_host(str(host.ips[0])) ...
Builder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Builder: def build_host(self, host): """@types: host_base_parser.HostDescriptor -> ObjectStateHolder""" <|body_0|> def build_complete_host(self, key): """Build generic host @types: str -> ObjectSateHolder @raise ValueError: Host key is not specified""" <|body...
stack_v2_sparse_classes_36k_train_018250
2,763
no_license
[ { "docstring": "@types: host_base_parser.HostDescriptor -> ObjectStateHolder", "name": "build_host", "signature": "def build_host(self, host)" }, { "docstring": "Build generic host @types: str -> ObjectSateHolder @raise ValueError: Host key is not specified", "name": "build_complete_host", ...
2
stack_v2_sparse_classes_30k_train_016117
Implement the Python class `Builder` described below. Class description: Implement the Builder class. Method signatures and docstrings: - def build_host(self, host): @types: host_base_parser.HostDescriptor -> ObjectStateHolder - def build_complete_host(self, key): Build generic host @types: str -> ObjectSateHolder @r...
Implement the Python class `Builder` described below. Class description: Implement the Builder class. Method signatures and docstrings: - def build_host(self, host): @types: host_base_parser.HostDescriptor -> ObjectStateHolder - def build_complete_host(self, key): Build generic host @types: str -> ObjectSateHolder @r...
c431e809e8d0f82e1bca7e3429dd0245560b5680
<|skeleton|> class Builder: def build_host(self, host): """@types: host_base_parser.HostDescriptor -> ObjectStateHolder""" <|body_0|> def build_complete_host(self, key): """Build generic host @types: str -> ObjectSateHolder @raise ValueError: Host key is not specified""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Builder: def build_host(self, host): """@types: host_base_parser.HostDescriptor -> ObjectStateHolder""" if not host or (not host.ips and (not host.name)): raise ValueError('Invalid host') if host.name: osh = ObjectStateHolder(self.CIT) osh.setStringA...
the_stack_v2_python_sparse
reference/ucmdb/discovery/host_topology.py
madmonkyang/cda-record
train
0
1ed96fb4456af7633fd2d8ffa6fc40bc6059bf08
[ "assert _dir is None or _dir == '', 'Cannot use _dir with TextDataReader.'\nif isinstance(sequences, str):\n sequences = DataReaderBase._read_file(sequences)\nfor i, seq in enumerate(sequences):\n if isinstance(seq, six.binary_type):\n seq = seq.decode('utf-8')\n yield {side: seq, 'indices': i}", ...
<|body_start_0|> assert _dir is None or _dir == '', 'Cannot use _dir with TextDataReader.' if isinstance(sequences, str): sequences = DataReaderBase._read_file(sequences) for i, seq in enumerate(sequences): if isinstance(seq, six.binary_type): seq = seq.de...
NewsDataReader
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NewsDataReader: def read(self, sequences, side, _dir=None): """Read text data from disk. Read from both src and tgt files. Args: sequences (str or Iterable[str]): path to text file or iterable of the actual text data. side (str): Prefix used in return dict. Usually ``"src"`` or ``"tgt"``...
stack_v2_sparse_classes_36k_train_018251
47,907
permissive
[ { "docstring": "Read text data from disk. Read from both src and tgt files. Args: sequences (str or Iterable[str]): path to text file or iterable of the actual text data. side (str): Prefix used in return dict. Usually ``\"src\"`` or ``\"tgt\"``. _dir (NoneType): Leave as ``None``. This parameter exists to conf...
2
null
Implement the Python class `NewsDataReader` described below. Class description: Implement the NewsDataReader class. Method signatures and docstrings: - def read(self, sequences, side, _dir=None): Read text data from disk. Read from both src and tgt files. Args: sequences (str or Iterable[str]): path to text file or i...
Implement the Python class `NewsDataReader` described below. Class description: Implement the NewsDataReader class. Method signatures and docstrings: - def read(self, sequences, side, _dir=None): Read text data from disk. Read from both src and tgt files. Args: sequences (str or Iterable[str]): path to text file or i...
d16bf09e21521a6854ff3c7fe6eb271412914960
<|skeleton|> class NewsDataReader: def read(self, sequences, side, _dir=None): """Read text data from disk. Read from both src and tgt files. Args: sequences (str or Iterable[str]): path to text file or iterable of the actual text data. side (str): Prefix used in return dict. Usually ``"src"`` or ``"tgt"``...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NewsDataReader: def read(self, sequences, side, _dir=None): """Read text data from disk. Read from both src and tgt files. Args: sequences (str or Iterable[str]): path to text file or iterable of the actual text data. side (str): Prefix used in return dict. Usually ``"src"`` or ``"tgt"``. _dir (NoneTy...
the_stack_v2_python_sparse
onmt/inputters/news_dataset.py
memray/OpenNMT-kpg-release
train
222
5326ae2b783ce1a52c3f1cdf37f112f3f971a2c8
[ "decorator_name = ''.join(('@', MPMDMPI.__name__.lower()))\nself.decorator_name = decorator_name\nself.args = args\nself.kwargs = kwargs\nself.scope = CONTEXT.in_pycompss()\nself.core_element = None\nself.core_element_configured = False\nself.task_type = 'mpmd_mpi'\nself.processes = 0\nif self.scope:\n if __debu...
<|body_start_0|> decorator_name = ''.join(('@', MPMDMPI.__name__.lower())) self.decorator_name = decorator_name self.args = args self.kwargs = kwargs self.scope = CONTEXT.in_pycompss() self.core_element = None self.core_element_configured = False self.task...
MPMDMPI decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on mpmd_mpi task creation.
MPMDMPI
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MPMDMPI: """MPMDMPI decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on mpmd_mpi task creation.""" def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: """Store arguments passed to the decorator. self =...
stack_v2_sparse_classes_36k_train_018252
8,390
permissive
[ { "docstring": "Store arguments passed to the decorator. self = itself. args = not used. kwargs = dictionary with the given mpi parameters. :param args: Arguments :param kwargs: Keyword arguments", "name": "__init__", "signature": "def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None" }...
5
null
Implement the Python class `MPMDMPI` described below. Class description: MPMDMPI decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on mpmd_mpi task creation. Method signatures and docstrings: - def __init__(self, *args: typing.Any, **kwargs: typing.Any)...
Implement the Python class `MPMDMPI` described below. Class description: MPMDMPI decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on mpmd_mpi task creation. Method signatures and docstrings: - def __init__(self, *args: typing.Any, **kwargs: typing.Any)...
5f7a31436d0e6f5acbeb66fa36ab8aad18dc4092
<|skeleton|> class MPMDMPI: """MPMDMPI decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on mpmd_mpi task creation.""" def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: """Store arguments passed to the decorator. self =...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MPMDMPI: """MPMDMPI decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on mpmd_mpi task creation.""" def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: """Store arguments passed to the decorator. self = itself. args...
the_stack_v2_python_sparse
compss/programming_model/bindings/python/src/pycompss/api/mpmd_mpi.py
bsc-wdc/compss
train
39
2ef6b2cd95bb6fd892032e027489765f92510afb
[ "self.pctls = pctls\npctls_v = np.percentile(X, pctls, axis=1)\nself.X_sc = X / np.diff(pctls_v, n=1, axis=0).squeeze()[:, None]", "pctls_v = np.percentile(Y, self.pctls, axis=lam_axis)\na = np.diff(pctls_v, n=1, axis=0).squeeze()\nY_sc = Y / a[None, ...]\nreturn (Y_sc, a)" ]
<|body_start_0|> self.pctls = pctls pctls_v = np.percentile(X, pctls, axis=1) self.X_sc = X / np.diff(pctls_v, n=1, axis=0).squeeze()[:, None] <|end_body_0|> <|body_start_1|> pctls_v = np.percentile(Y, self.pctls, axis=lam_axis) a = np.diff(pctls_v, n=1, axis=0).squeeze() ...
scale spectra to unit dispersion
SpecScaler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpecScaler: """scale spectra to unit dispersion""" def __init__(self, X, pctls=(16.0, 84.0)): """params: - X (nspec, nl): array of spectra""" <|body_0|> def __call__(self, Y, lam_axis=0, map_axis=(1, 2)): """apply the same scaling as is fit""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_018253
18,611
permissive
[ { "docstring": "params: - X (nspec, nl): array of spectra", "name": "__init__", "signature": "def __init__(self, X, pctls=(16.0, 84.0))" }, { "docstring": "apply the same scaling as is fit", "name": "__call__", "signature": "def __call__(self, Y, lam_axis=0, map_axis=(1, 2))" } ]
2
stack_v2_sparse_classes_30k_train_019489
Implement the Python class `SpecScaler` described below. Class description: scale spectra to unit dispersion Method signatures and docstrings: - def __init__(self, X, pctls=(16.0, 84.0)): params: - X (nspec, nl): array of spectra - def __call__(self, Y, lam_axis=0, map_axis=(1, 2)): apply the same scaling as is fit
Implement the Python class `SpecScaler` described below. Class description: scale spectra to unit dispersion Method signatures and docstrings: - def __init__(self, X, pctls=(16.0, 84.0)): params: - X (nspec, nl): array of spectra - def __call__(self, Y, lam_axis=0, map_axis=(1, 2)): apply the same scaling as is fit ...
6d7f3e8e4d3d637432d1bac6ed17a837c0ca9c75
<|skeleton|> class SpecScaler: """scale spectra to unit dispersion""" def __init__(self, X, pctls=(16.0, 84.0)): """params: - X (nspec, nl): array of spectra""" <|body_0|> def __call__(self, Y, lam_axis=0, map_axis=(1, 2)): """apply the same scaling as is fit""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpecScaler: """scale spectra to unit dispersion""" def __init__(self, X, pctls=(16.0, 84.0)): """params: - X (nspec, nl): array of spectra""" self.pctls = pctls pctls_v = np.percentile(X, pctls, axis=1) self.X_sc = X / np.diff(pctls_v, n=1, axis=0).squeeze()[:, None] ...
the_stack_v2_python_sparse
utils.py
CSwigg/stellarmass_pca
train
0
0eb89f9958d583727ed838f03b7d621dacf19dca
[ "super(StageToRedshiftOperator, self).__init__(*args, **kwargs)\nself.arn = arn\nself.aws_credentials_id = aws_credentials_id\nself.conn_id = conn_id\nself.execution_date = kwargs.get('execution_date')\nself.jsonformat = jsonformat\nself.s3_bucket = s3_bucket\nself.s3_key = s3_key\nself.region = region\nself.table ...
<|body_start_0|> super(StageToRedshiftOperator, self).__init__(*args, **kwargs) self.arn = arn self.aws_credentials_id = aws_credentials_id self.conn_id = conn_id self.execution_date = kwargs.get('execution_date') self.jsonformat = jsonformat self.s3_bucket = s3_b...
Copy Data from S3 onto Redshift Props: - arn, path, conn_id, region, table: see __init__ docstring - qf_truncate: SQL to TRUNCATE the table. Qf means Query Formatted. - qf_copy: SQL to COPY FROM.
StageToRedshiftOperator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StageToRedshiftOperator: """Copy Data from S3 onto Redshift Props: - arn, path, conn_id, region, table: see __init__ docstring - qf_truncate: SQL to TRUNCATE the table. Qf means Query Formatted. - qf_copy: SQL to COPY FROM.""" def __init__(self, arn='', aws_credentials_id='', conn_id='', reg...
stack_v2_sparse_classes_36k_train_018254
3,004
no_license
[ { "docstring": "Args: arn (str): name of ARN role assumed by the Redshift cluster aws_credentials_id (str): AWS credentials in Airflow s3_bucket (str): path to file(s) s3_key (str): path to file(s) conn_id (str): Redshift connection ID in Airflow region (str): AWS region table (str): Redshift table name **kwarg...
2
stack_v2_sparse_classes_30k_train_003874
Implement the Python class `StageToRedshiftOperator` described below. Class description: Copy Data from S3 onto Redshift Props: - arn, path, conn_id, region, table: see __init__ docstring - qf_truncate: SQL to TRUNCATE the table. Qf means Query Formatted. - qf_copy: SQL to COPY FROM. Method signatures and docstrings:...
Implement the Python class `StageToRedshiftOperator` described below. Class description: Copy Data from S3 onto Redshift Props: - arn, path, conn_id, region, table: see __init__ docstring - qf_truncate: SQL to TRUNCATE the table. Qf means Query Formatted. - qf_copy: SQL to COPY FROM. Method signatures and docstrings:...
ec7f881b6e11d7e3294176128290fdd1ad684fc0
<|skeleton|> class StageToRedshiftOperator: """Copy Data from S3 onto Redshift Props: - arn, path, conn_id, region, table: see __init__ docstring - qf_truncate: SQL to TRUNCATE the table. Qf means Query Formatted. - qf_copy: SQL to COPY FROM.""" def __init__(self, arn='', aws_credentials_id='', conn_id='', reg...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StageToRedshiftOperator: """Copy Data from S3 onto Redshift Props: - arn, path, conn_id, region, table: see __init__ docstring - qf_truncate: SQL to TRUNCATE the table. Qf means Query Formatted. - qf_copy: SQL to COPY FROM.""" def __init__(self, arn='', aws_credentials_id='', conn_id='', region='', s3_bu...
the_stack_v2_python_sparse
p5_pipeline_airflow/airflowcode/plugins/operators/stage_redshift.py
ogierpaul/Udacity-Data-Engineer-NanoDegree
train
1
225b166357d764d1c3a79970e8e0ca90c2adca4d
[ "from django.conf.urls import url\n\ndef wrap(view):\n\n def wrapper(*args, **kwargs):\n return self.admin_site.admin_view(view)(*args, **kwargs)\n return update_wrapper(wrapper, view)\ninfo = (self.model._meta.app_label, self.model._meta.model_name)\nreturn [url('^import-data/$', wrap(self.import_data...
<|body_start_0|> from django.conf.urls import url def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = (self.model._meta.app_label, self.model._meta.model_name)...
AttendeeAdmin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttendeeAdmin: def get_urls(self): """Override to add URL to import data.""" <|body_0|> def import_data(self, request): """Admin view to import data from Ticketea.""" <|body_1|> <|end_skeleton|> <|body_start_0|> from django.conf.urls import url ...
stack_v2_sparse_classes_36k_train_018255
2,595
permissive
[ { "docstring": "Override to add URL to import data.", "name": "get_urls", "signature": "def get_urls(self)" }, { "docstring": "Admin view to import data from Ticketea.", "name": "import_data", "signature": "def import_data(self, request)" } ]
2
null
Implement the Python class `AttendeeAdmin` described below. Class description: Implement the AttendeeAdmin class. Method signatures and docstrings: - def get_urls(self): Override to add URL to import data. - def import_data(self, request): Admin view to import data from Ticketea.
Implement the Python class `AttendeeAdmin` described below. Class description: Implement the AttendeeAdmin class. Method signatures and docstrings: - def get_urls(self): Override to add URL to import data. - def import_data(self, request): Admin view to import data from Ticketea. <|skeleton|> class AttendeeAdmin: ...
618deb55168f7b93f9569b0813f6fa26274b45ee
<|skeleton|> class AttendeeAdmin: def get_urls(self): """Override to add URL to import data.""" <|body_0|> def import_data(self, request): """Admin view to import data from Ticketea.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AttendeeAdmin: def get_urls(self): """Override to add URL to import data.""" from django.conf.urls import url def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, ...
the_stack_v2_python_sparse
pycones/attendees/admin.py
python-spain/PyConES-2016
train
4
4695784a3f157e9a6d3e17212f1f079d42b282fc
[ "assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nBOARDS = ['Shore Catch Reports NESA', 'Lure Fishing NESA', 'Lure Catch Reports NESA', 'Boat Catch Reports NESA', 'Boat Fishing NESA']\nURLS = ['https://www.nesa.co.uk/forums/shore-catch-reports/', 'https://www.nesa.co.uk/forums/lure-fishing/', 'h...
<|body_start_0|> assert isinstance(response, scrapy.http.response.html.HtmlResponse) BOARDS = ['Shore Catch Reports NESA', 'Lure Fishing NESA', 'Lure Catch Reports NESA', 'Boat Catch Reports NESA', 'Boat Fishing NESA'] URLS = ['https://www.nesa.co.uk/forums/shore-catch-reports/', 'https://www.ne...
scrape reports from angling addicts forum
NESASpiderShoreExtraAfloat
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NESASpiderShoreExtraAfloat: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board""" <|body_0|> def crawl_board_threads(self, response): """crawl""" <|body_1|> def parse_thread(self, response...
stack_v2_sparse_classes_36k_train_018256
13,051
no_license
[ { "docstring": "generate links to pages in a board", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "crawl", "name": "crawl_board_threads", "signature": "def crawl_board_threads(self, response)" }, { "docstring": "open a report thread and parse first ...
3
null
Implement the Python class `NESASpiderShoreExtraAfloat` described below. Class description: scrape reports from angling addicts forum Method signatures and docstrings: - def parse(self, response): generate links to pages in a board - def crawl_board_threads(self, response): crawl - def parse_thread(self, response): o...
Implement the Python class `NESASpiderShoreExtraAfloat` described below. Class description: scrape reports from angling addicts forum Method signatures and docstrings: - def parse(self, response): generate links to pages in a board - def crawl_board_threads(self, response): crawl - def parse_thread(self, response): o...
9123aa6baf538b662143b9098d963d55165e8409
<|skeleton|> class NESASpiderShoreExtraAfloat: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board""" <|body_0|> def crawl_board_threads(self, response): """crawl""" <|body_1|> def parse_thread(self, response...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NESASpiderShoreExtraAfloat: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board""" assert isinstance(response, scrapy.http.response.html.HtmlResponse) BOARDS = ['Shore Catch Reports NESA', 'Lure Fishing NESA', 'Lure Catc...
the_stack_v2_python_sparse
imgscrape/spiders/nesa.py
gmonkman/python
train
0
4d872759fa35674d42f80d59a1bc7c236f5f1ad4
[ "while True:\n try:\n args = qin.get_nowait()\n except Empty:\n return\n qout.put(func(args))", "if nworkers < 1:\n raise ValueError(f'Invalid number of workers: {nworkers}')\nqin = Queue()\nfor arg in args:\n qin.put(arg)\nqout = Queue()\nprocesses = []\nfor _ in range(nworkers):\n ...
<|body_start_0|> while True: try: args = qin.get_nowait() except Empty: return qout.put(func(args)) <|end_body_0|> <|body_start_1|> if nworkers < 1: raise ValueError(f'Invalid number of workers: {nworkers}') qin = Q...
ParallerRunner
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParallerRunner: def _sub_func(qin, qout, func): """Single worker called by `run()`.""" <|body_0|> def run(nworkers, func, args): """Run a given function in parallel and return the list of their return values. Parameters ---------- nworkers : int The number of workers...
stack_v2_sparse_classes_36k_train_018257
8,239
permissive
[ { "docstring": "Single worker called by `run()`.", "name": "_sub_func", "signature": "def _sub_func(qin, qout, func)" }, { "docstring": "Run a given function in parallel and return the list of their return values. Parameters ---------- nworkers : int The number of workers to spawn. func : lambda...
2
stack_v2_sparse_classes_30k_train_001002
Implement the Python class `ParallerRunner` described below. Class description: Implement the ParallerRunner class. Method signatures and docstrings: - def _sub_func(qin, qout, func): Single worker called by `run()`. - def run(nworkers, func, args): Run a given function in parallel and return the list of their return...
Implement the Python class `ParallerRunner` described below. Class description: Implement the ParallerRunner class. Method signatures and docstrings: - def _sub_func(qin, qout, func): Single worker called by `run()`. - def run(nworkers, func, args): Run a given function in parallel and return the list of their return...
b8a10b69add71760bd1036e54e67eb191dacc039
<|skeleton|> class ParallerRunner: def _sub_func(qin, qout, func): """Single worker called by `run()`.""" <|body_0|> def run(nworkers, func, args): """Run a given function in parallel and return the list of their return values. Parameters ---------- nworkers : int The number of workers...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ParallerRunner: def _sub_func(qin, qout, func): """Single worker called by `run()`.""" while True: try: args = qin.get_nowait() except Empty: return qout.put(func(args)) def run(nworkers, func, args): """Run a giv...
the_stack_v2_python_sparse
uiiit/utils.py
liwen96/netsquid
train
0
23787fc865f134b31e77ffccdee6a860b99ba01e
[ "if not root:\n return ''\nleft = self.serialize(root.left)\nright = self.serialize(root.right)\nserialized = str(root.val) + 'R' + '[' + left + ']' + right\nreturn serialized", "if not data:\n return None\nleft_index = data.index('R')\nroot = TreeNode(int(data[:left_index]))\nlr = data[left_index + 1:]\nl,...
<|body_start_0|> if not root: return '' left = self.serialize(root.left) right = self.serialize(root.right) serialized = str(root.val) + 'R' + '[' + left + ']' + right return serialized <|end_body_0|> <|body_start_1|> if not data: return None ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root: ...
stack_v2_sparse_classes_36k_train_018258
1,453
no_license
[ { "docstring": "Encodes a tree to a single string.", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Decodes your encoded data to tree.", "name": "deserialize", "signature": "def deserialize(self, data: str) -> TreeNode" } ]
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. <|skeleton|> class Co...
00bf9a8164008aa17507b1c87ce72a3374bcb7b9
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" if not root: return '' left = self.serialize(root.left) right = self.serialize(root.right) serialized = str(root.val) + 'R' + '[' + left + ']' + right return ...
the_stack_v2_python_sparse
solutions/449.serialize-and-deserialize-bst.py
quixoteji/Leetcode
train
1
ac2b9a4348543ce1c9ad4a3cefd2fe31343db183
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ConditionalAccessApplications()", "from .conditional_access_filter import ConditionalAccessFilter\nfrom .conditional_access_filter import ConditionalAccessFilter\nfields: Dict[str, Callable[[Any], None]] = {'applicationFilter': lambda ...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return ConditionalAccessApplications() <|end_body_0|> <|body_start_1|> from .conditional_access_filter import ConditionalAccessFilter from .conditional_access_filter import ConditionalAccessFil...
ConditionalAccessApplications
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConditionalAccessApplications: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessApplications: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator val...
stack_v2_sparse_classes_36k_train_018259
4,721
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ConditionalAccessApplications", "name": "create_from_discriminator_value", "signature": "def create_from_dis...
3
stack_v2_sparse_classes_30k_train_013573
Implement the Python class `ConditionalAccessApplications` described below. Class description: Implement the ConditionalAccessApplications class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessApplications: Creates a new instance of th...
Implement the Python class `ConditionalAccessApplications` described below. Class description: Implement the ConditionalAccessApplications class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessApplications: Creates a new instance of th...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class ConditionalAccessApplications: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessApplications: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator val...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConditionalAccessApplications: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessApplications: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create ...
the_stack_v2_python_sparse
msgraph/generated/models/conditional_access_applications.py
microsoftgraph/msgraph-sdk-python
train
135
1d6fbb9df7bc76945733639373fec09b99b04d5b
[ "dp = [[0.0] * (r + 1) for r in range(query_row + 1)]\ndp[0][0] = poured\nfor r in range(query_row):\n for c in range(r + 1):\n exceeds = (dp[r][c] - 1.0) / 2.0\n if exceeds > 0:\n dp[r + 1][c] += exceeds\n dp[r + 1][c + 1] += exceeds\nreturn min(1.0, dp[query_row][query_glass...
<|body_start_0|> dp = [[0.0] * (r + 1) for r in range(query_row + 1)] dp[0][0] = poured for r in range(query_row): for c in range(r + 1): exceeds = (dp[r][c] - 1.0) / 2.0 if exceeds > 0: dp[r + 1][c] += exceeds d...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: """Calculate the total champagne flow through each glass. For example, if poured 10 cups, the only glass on the first row has 9 cups flowed through; then the two glasses on the second row has 3.5 ...
stack_v2_sparse_classes_36k_train_018260
1,508
no_license
[ { "docstring": "Calculate the total champagne flow through each glass. For example, if poured 10 cups, the only glass on the first row has 9 cups flowed through; then the two glasses on the second row has 3.5 cups flowed through each.", "name": "champagneTower", "signature": "def champagneTower(self, po...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: Calculate the total champagne flow through each glass. For example, if poured 10 cups, the only ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: Calculate the total champagne flow through each glass. For example, if poured 10 cups, the only ...
edb870f83f0c4568cce0cacec04ee70cf6b545bf
<|skeleton|> class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: """Calculate the total champagne flow through each glass. For example, if poured 10 cups, the only glass on the first row has 9 cups flowed through; then the two glasses on the second row has 3.5 ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: """Calculate the total champagne flow through each glass. For example, if poured 10 cups, the only glass on the first row has 9 cups flowed through; then the two glasses on the second row has 3.5 cups flowed th...
the_stack_v2_python_sparse
2020/champagne_tower.py
eronekogin/leetcode
train
0
246197011a78ce13d7dfa7841fa8450d9d60d67c
[ "super().__init__()\nself.memory_dim = memory_dim\nself.variational_dropout = variational_dropout\nself.dropout = dropout\nself.read_dropout = nn.Dropout(self.dropout)\nself.mem_proj = xavier_uniform_linear(self.memory_dim, self.memory_dim)\nself.kb_proj = xavier_uniform_linear(self.memory_dim, self.memory_dim)\nse...
<|body_start_0|> super().__init__() self.memory_dim = memory_dim self.variational_dropout = variational_dropout self.dropout = dropout self.read_dropout = nn.Dropout(self.dropout) self.mem_proj = xavier_uniform_linear(self.memory_dim, self.memory_dim) self.kb_proj...
A MAC recurrent cell read unit.
ReadUnit
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReadUnit: """A MAC recurrent cell read unit.""" def __init__(self, memory_dim: int=512, variational_dropout: bool=True, dropout: float=0.15): """Initialise the read unit.""" <|body_0|> def forward(self, memories: Sequence[torch.Tensor], know: torch.Tensor, controls: Sequ...
stack_v2_sparse_classes_36k_train_018261
2,897
no_license
[ { "docstring": "Initialise the read unit.", "name": "__init__", "signature": "def __init__(self, memory_dim: int=512, variational_dropout: bool=True, dropout: float=0.15)" }, { "docstring": "Propagate data through the model.", "name": "forward", "signature": "def forward(self, memories: ...
2
stack_v2_sparse_classes_30k_train_014161
Implement the Python class `ReadUnit` described below. Class description: A MAC recurrent cell read unit. Method signatures and docstrings: - def __init__(self, memory_dim: int=512, variational_dropout: bool=True, dropout: float=0.15): Initialise the read unit. - def forward(self, memories: Sequence[torch.Tensor], kn...
Implement the Python class `ReadUnit` described below. Class description: A MAC recurrent cell read unit. Method signatures and docstrings: - def __init__(self, memory_dim: int=512, variational_dropout: bool=True, dropout: float=0.15): Initialise the read unit. - def forward(self, memories: Sequence[torch.Tensor], kn...
78c479f8d0b3209ece9f9ccbbf63810802293f61
<|skeleton|> class ReadUnit: """A MAC recurrent cell read unit.""" def __init__(self, memory_dim: int=512, variational_dropout: bool=True, dropout: float=0.15): """Initialise the read unit.""" <|body_0|> def forward(self, memories: Sequence[torch.Tensor], know: torch.Tensor, controls: Sequ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReadUnit: """A MAC recurrent cell read unit.""" def __init__(self, memory_dim: int=512, variational_dropout: bool=True, dropout: float=0.15): """Initialise the read unit.""" super().__init__() self.memory_dim = memory_dim self.variational_dropout = variational_dropout ...
the_stack_v2_python_sparse
gat_vqa/modules/reasoning/mac/read.py
alexmirrington/gat-vqa
train
4
70fca5eea5a5bc74e7556970c89b284e1dc6341a
[ "client = queries.QuizClientMissMatch.getInstance()\nclient.setUp(1, 2)\nself.assertEqual(client, False)", "client = queries.QuizClientMissMatch.getInstance()\nclient.setUp(1, 1)\nself.assertEqual(client, False)" ]
<|body_start_0|> client = queries.QuizClientMissMatch.getInstance() client.setUp(1, 2) self.assertEqual(client, False) <|end_body_0|> <|body_start_1|> client = queries.QuizClientMissMatch.getInstance() client.setUp(1, 1) self.assertEqual(client, False) <|end_body_1|>
QuizClientMissMatchTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QuizClientMissMatchTest: def session_vaild_missmatch(self): """Check if there's a missmatch""" <|body_0|> def session_vaild_match(self): """Check if there's a match""" <|body_1|> <|end_skeleton|> <|body_start_0|> client = queries.QuizClientMissMatch...
stack_v2_sparse_classes_36k_train_018262
15,976
no_license
[ { "docstring": "Check if there's a missmatch", "name": "session_vaild_missmatch", "signature": "def session_vaild_missmatch(self)" }, { "docstring": "Check if there's a match", "name": "session_vaild_match", "signature": "def session_vaild_match(self)" } ]
2
stack_v2_sparse_classes_30k_train_013301
Implement the Python class `QuizClientMissMatchTest` described below. Class description: Implement the QuizClientMissMatchTest class. Method signatures and docstrings: - def session_vaild_missmatch(self): Check if there's a missmatch - def session_vaild_match(self): Check if there's a match
Implement the Python class `QuizClientMissMatchTest` described below. Class description: Implement the QuizClientMissMatchTest class. Method signatures and docstrings: - def session_vaild_missmatch(self): Check if there's a missmatch - def session_vaild_match(self): Check if there's a match <|skeleton|> class QuizCl...
58081fd46749e9ca5dea1597f479025c872bccfe
<|skeleton|> class QuizClientMissMatchTest: def session_vaild_missmatch(self): """Check if there's a missmatch""" <|body_0|> def session_vaild_match(self): """Check if there's a match""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QuizClientMissMatchTest: def session_vaild_missmatch(self): """Check if there's a missmatch""" client = queries.QuizClientMissMatch.getInstance() client.setUp(1, 2) self.assertEqual(client, False) def session_vaild_match(self): """Check if there's a match""" ...
the_stack_v2_python_sparse
triviaQuiz/tests.py
Bradenm1/Django-quiz
train
0
b7429a64befe2c04c0844c1f4cbdc429a345aa5f
[ "if treeNode is None:\n return\nprint(treeNode.data.data)\nself.middleOrderTraversalRecursion(treeNode.leftChild)\nself.middleOrderTraversalRecursion(treeNode.rightChild)", "stack = []\nresult = []\nwhile treeNode or stack:\n if treeNode:\n result.append(treeNode.data.data)\n stack.append(tree...
<|body_start_0|> if treeNode is None: return print(treeNode.data.data) self.middleOrderTraversalRecursion(treeNode.leftChild) self.middleOrderTraversalRecursion(treeNode.rightChild) <|end_body_0|> <|body_start_1|> stack = [] result = [] while treeNode...
MiddleOrderTraversal
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MiddleOrderTraversal: def middleOrderTraversalRecursion(self, treeNode): """先序遍历的递归实现 :param treeNode: :return:""" <|body_0|> def middleOrderTraversalNotRecursion(self, treeNode): """先序遍历的非递归实现 :param treeNode: :return:""" <|body_1|> <|end_skeleton|> <|body...
stack_v2_sparse_classes_36k_train_018263
2,289
no_license
[ { "docstring": "先序遍历的递归实现 :param treeNode: :return:", "name": "middleOrderTraversalRecursion", "signature": "def middleOrderTraversalRecursion(self, treeNode)" }, { "docstring": "先序遍历的非递归实现 :param treeNode: :return:", "name": "middleOrderTraversalNotRecursion", "signature": "def middleOr...
2
stack_v2_sparse_classes_30k_train_014274
Implement the Python class `MiddleOrderTraversal` described below. Class description: Implement the MiddleOrderTraversal class. Method signatures and docstrings: - def middleOrderTraversalRecursion(self, treeNode): 先序遍历的递归实现 :param treeNode: :return: - def middleOrderTraversalNotRecursion(self, treeNode): 先序遍历的非递归实现 ...
Implement the Python class `MiddleOrderTraversal` described below. Class description: Implement the MiddleOrderTraversal class. Method signatures and docstrings: - def middleOrderTraversalRecursion(self, treeNode): 先序遍历的递归实现 :param treeNode: :return: - def middleOrderTraversalNotRecursion(self, treeNode): 先序遍历的非递归实现 ...
cded97a52c422f98b55f2b3527a054d23541d5a4
<|skeleton|> class MiddleOrderTraversal: def middleOrderTraversalRecursion(self, treeNode): """先序遍历的递归实现 :param treeNode: :return:""" <|body_0|> def middleOrderTraversalNotRecursion(self, treeNode): """先序遍历的非递归实现 :param treeNode: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MiddleOrderTraversal: def middleOrderTraversalRecursion(self, treeNode): """先序遍历的递归实现 :param treeNode: :return:""" if treeNode is None: return print(treeNode.data.data) self.middleOrderTraversalRecursion(treeNode.leftChild) self.middleOrderTraversalRecursion...
the_stack_v2_python_sparse
chapter5/先序遍历.py
AnJian2020/Leetcode
train
1
f8b3ea6bdf77ce81af3b9f50b07a3bce034c65fb
[ "line = line.split()\nself.nevery = int(line[1])\nself.x_store = np.zeros((nsteps / self.nevery, natoms))\nself.y_store = np.zeros((nsteps / self.nevery, natoms))\nself.scprod = np.zeros((nsteps / self.nevery, natoms))\nself.counter = 0\nreturn", "if step % self.nevery != 0:\n return\ncos = np.cos(phi)\nsin = ...
<|body_start_0|> line = line.split() self.nevery = int(line[1]) self.x_store = np.zeros((nsteps / self.nevery, natoms)) self.y_store = np.zeros((nsteps / self.nevery, natoms)) self.scprod = np.zeros((nsteps / self.nevery, natoms)) self.counter = 0 return <|end_bod...
OrientVel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrientVel: def __init__(self, nsteps, natoms, line): """initialize: allocate density array""" <|body_0|> def compute(self, step, x, y, vx, vy, phi, natoms, plot='False'): """compute a density distribution and a histogram of the density distribution""" <|body_...
stack_v2_sparse_classes_36k_train_018264
1,754
no_license
[ { "docstring": "initialize: allocate density array", "name": "__init__", "signature": "def __init__(self, nsteps, natoms, line)" }, { "docstring": "compute a density distribution and a histogram of the density distribution", "name": "compute", "signature": "def compute(self, step, x, y, ...
2
stack_v2_sparse_classes_30k_train_001864
Implement the Python class `OrientVel` described below. Class description: Implement the OrientVel class. Method signatures and docstrings: - def __init__(self, nsteps, natoms, line): initialize: allocate density array - def compute(self, step, x, y, vx, vy, phi, natoms, plot='False'): compute a density distribution ...
Implement the Python class `OrientVel` described below. Class description: Implement the OrientVel class. Method signatures and docstrings: - def __init__(self, nsteps, natoms, line): initialize: allocate density array - def compute(self, step, x, y, vx, vy, phi, natoms, plot='False'): compute a density distribution ...
7d2659bee85c955c680eda019cbff6e2b93ecff2
<|skeleton|> class OrientVel: def __init__(self, nsteps, natoms, line): """initialize: allocate density array""" <|body_0|> def compute(self, step, x, y, vx, vy, phi, natoms, plot='False'): """compute a density distribution and a histogram of the density distribution""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OrientVel: def __init__(self, nsteps, natoms, line): """initialize: allocate density array""" line = line.split() self.nevery = int(line[1]) self.x_store = np.zeros((nsteps / self.nevery, natoms)) self.y_store = np.zeros((nsteps / self.nevery, natoms)) self.scpr...
the_stack_v2_python_sparse
analyse_collective/orientvel.py
melampyge/CollectiveFilament
train
0
b59300fadfcbb5ea24be202f588d2ebdd165a0d1
[ "super(SentimentRNN, self).__init__()\nself.output_size = output_size\nself.n_layers = n_layers\nself.hidden_dim = hidden_dim\nself.embedding = nn.Embedding(vocab_size, embedding_dim)\nself.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=drop_prob, batch_first=True)\nself.dropout = nn.Dropout(0.3)\nself...
<|body_start_0|> super(SentimentRNN, self).__init__() self.output_size = output_size self.n_layers = n_layers self.hidden_dim = hidden_dim self.embedding = nn.Embedding(vocab_size, embedding_dim) self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=drop_prob, ...
The RNN models that will be used to perform Sentiment analysis.
SentimentRNN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SentimentRNN: """The RNN models that will be used to perform Sentiment analysis.""" def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5): """Initialize the models by setting up the layers.""" <|body_0|> def forward(self, x, hidd...
stack_v2_sparse_classes_36k_train_018265
3,087
no_license
[ { "docstring": "Initialize the models by setting up the layers.", "name": "__init__", "signature": "def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5)" }, { "docstring": "Perform a forward pass of our models on some input and hidden state.", "name...
3
stack_v2_sparse_classes_30k_train_021000
Implement the Python class `SentimentRNN` described below. Class description: The RNN models that will be used to perform Sentiment analysis. Method signatures and docstrings: - def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5): Initialize the models by setting up the lay...
Implement the Python class `SentimentRNN` described below. Class description: The RNN models that will be used to perform Sentiment analysis. Method signatures and docstrings: - def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5): Initialize the models by setting up the lay...
aa9d9a6e99abc5b2fbee8a724e02a65232d2eb60
<|skeleton|> class SentimentRNN: """The RNN models that will be used to perform Sentiment analysis.""" def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5): """Initialize the models by setting up the layers.""" <|body_0|> def forward(self, x, hidd...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SentimentRNN: """The RNN models that will be used to perform Sentiment analysis.""" def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5): """Initialize the models by setting up the layers.""" super(SentimentRNN, self).__init__() self.outp...
the_stack_v2_python_sparse
sentiment_analysis/model.py
ilyarudyak/tv_script_gen
train
1
506d7a651b513b3474ac3b5cc718e0a9e9331929
[ "length = 0\nhead_0 = head\nwhile head_0 is not None:\n head_0 = head_0.next\n length += 1\nidx_n = length - n\nif idx_n == 0:\n head = head.next\n return head\nhead_0, cur, idx = (head, head_0, 0)\nwhile idx < idx_n:\n cur, head_0 = (head_0, head_0.next)\n idx += 1\nif head_0 is None:\n cur.ne...
<|body_start_0|> length = 0 head_0 = head while head_0 is not None: head_0 = head_0.next length += 1 idx_n = length - n if idx_n == 0: head = head.next return head head_0, cur, idx = (head, head_0, 0) while idx < idx...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def removeNthFromEnd1(self, head, n): """:type head: ListNode :type n: int :rtype: ListNode""" <|body_0|> def removeNthFromEnd(self, head, n): """:type head: ListNode :type n: int :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_018266
1,857
no_license
[ { "docstring": ":type head: ListNode :type n: int :rtype: ListNode", "name": "removeNthFromEnd1", "signature": "def removeNthFromEnd1(self, head, n)" }, { "docstring": ":type head: ListNode :type n: int :rtype: ListNode", "name": "removeNthFromEnd", "signature": "def removeNthFromEnd(sel...
2
stack_v2_sparse_classes_30k_train_018796
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeNthFromEnd1(self, head, n): :type head: ListNode :type n: int :rtype: ListNode - def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeNthFromEnd1(self, head, n): :type head: ListNode :type n: int :rtype: ListNode - def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode...
96e847591aa6ea7ea285dbcfc1c9bcfc32026de5
<|skeleton|> class Solution: def removeNthFromEnd1(self, head, n): """:type head: ListNode :type n: int :rtype: ListNode""" <|body_0|> def removeNthFromEnd(self, head, n): """:type head: ListNode :type n: int :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def removeNthFromEnd1(self, head, n): """:type head: ListNode :type n: int :rtype: ListNode""" length = 0 head_0 = head while head_0 is not None: head_0 = head_0.next length += 1 idx_n = length - n if idx_n == 0: hea...
the_stack_v2_python_sparse
LinkList/L19_remove-nth-node-from-end-of-list.py
lihujun101/LeetCode
train
0
0540fb9754f4cc101eae2e36c02e365448f6c1c1
[ "result = []\nqe = Queue.Queue(maxsize=0)\nqe.put(root)\nwhile not qe.empty():\n node = qe.get()\n if not node:\n result.append('None')\n else:\n result.append(str(node.val))\n qe.put(node.left)\n qe.put(node.right)\nreturn ','.join(result)", "qe = Queue.Queue(maxsize=0)\nspli...
<|body_start_0|> result = [] qe = Queue.Queue(maxsize=0) qe.put(root) while not qe.empty(): node = qe.get() if not node: result.append('None') else: result.append(str(node.val)) qe.put(node.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_018267
1,567
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:...
c8bf33af30569177c5276ffcd72a8d93ba4c402a
<|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""" result = [] qe = Queue.Queue(maxsize=0) qe.put(root) while not qe.empty(): node = qe.get() if not node: result.append('Non...
the_stack_v2_python_sparse
LCOF/31-40/37/37.py
xuychen/Leetcode
train
0
81531b11ebb37d9ccf312feb7be24d91b1dcd327
[ "super(ResidualRecurrentEncoder, self).__init__()\nself.batch_first = batch_first\nself.rnn_layers = nn.ModuleList()\nself.rnn_layers.append(EmuBidirLSTM(hidden_size, hidden_size, num_layers=1, bias=bias, batch_first=batch_first, bidirectional=True))\nself.rnn_layers.append(nn.LSTM(2 * hidden_size, hidden_size, num...
<|body_start_0|> super(ResidualRecurrentEncoder, self).__init__() self.batch_first = batch_first self.rnn_layers = nn.ModuleList() self.rnn_layers.append(EmuBidirLSTM(hidden_size, hidden_size, num_layers=1, bias=bias, batch_first=batch_first, bidirectional=True)) self.rnn_layers....
Encoder with Embedding, LSTM layers, residual connections and optional dropout. The first LSTM layer is bidirectional and uses variable sequence length API, the remaining (num_layers-1) layers are unidirectional. Residual connections are enabled after third LSTM layer, dropout is applied between LSTM layers.
ResidualRecurrentEncoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResidualRecurrentEncoder: """Encoder with Embedding, LSTM layers, residual connections and optional dropout. The first LSTM layer is bidirectional and uses variable sequence length API, the remaining (num_layers-1) layers are unidirectional. Residual connections are enabled after third LSTM layer...
stack_v2_sparse_classes_36k_train_018268
6,026
permissive
[ { "docstring": "Constructor for the ResidualRecurrentEncoder. :param vocab_size: size of vocabulary :param hidden_size: hidden size for LSTM layers :param num_layers: number of LSTM layers, 1st layer is bidirectional :param bias: enables bias in LSTM layers :param dropout: probability of dropout (between LSTM l...
2
null
Implement the Python class `ResidualRecurrentEncoder` described below. Class description: Encoder with Embedding, LSTM layers, residual connections and optional dropout. The first LSTM layer is bidirectional and uses variable sequence length API, the remaining (num_layers-1) layers are unidirectional. Residual connect...
Implement the Python class `ResidualRecurrentEncoder` described below. Class description: Encoder with Embedding, LSTM layers, residual connections and optional dropout. The first LSTM layer is bidirectional and uses variable sequence length API, the remaining (num_layers-1) layers are unidirectional. Residual connect...
7db6a1c3e64996d5b319faec6ca38cb31bfea1c4
<|skeleton|> class ResidualRecurrentEncoder: """Encoder with Embedding, LSTM layers, residual connections and optional dropout. The first LSTM layer is bidirectional and uses variable sequence length API, the remaining (num_layers-1) layers are unidirectional. Residual connections are enabled after third LSTM layer...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResidualRecurrentEncoder: """Encoder with Embedding, LSTM layers, residual connections and optional dropout. The first LSTM layer is bidirectional and uses variable sequence length API, the remaining (num_layers-1) layers are unidirectional. Residual connections are enabled after third LSTM layer, dropout is ...
the_stack_v2_python_sparse
runtime/translation/seq2seq/models/encoder.py
msr-fiddle/pipedream
train
356
df031083da352c5a0ffd4fc93cd0e764c1fdef00
[ "startup_program = paddle.static.Program()\ntrain_program = paddle.static.Program()\nwith paddle.static.program_guard(train_program, startup_program):\n input_word = paddle.static.data(name='input_word', shape=[None, 1], dtype='int64')\n param_attr = paddle.ParamAttr(name='emb', initializer=paddle.nn.initiali...
<|body_start_0|> startup_program = paddle.static.Program() train_program = paddle.static.Program() with paddle.static.program_guard(train_program, startup_program): input_word = paddle.static.data(name='input_word', shape=[None, 1], dtype='int64') param_attr = paddle.Para...
test paddleslim.quant.quant_embedding
TestQuantEmbedding
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestQuantEmbedding: """test paddleslim.quant.quant_embedding""" def test_quant_embedding(self): """paddleslim.quant.quant_embedding(program, place, config=None, scope=None) :return:""" <|body_0|> def test_quant_embedding1(self): """paddleslim.quant.quant_embeddin...
stack_v2_sparse_classes_36k_train_018269
4,417
no_license
[ { "docstring": "paddleslim.quant.quant_embedding(program, place, config=None, scope=None) :return:", "name": "test_quant_embedding", "signature": "def test_quant_embedding(self)" }, { "docstring": "paddleslim.quant.quant_embedding(program, place, config=None, scope=None) :return:", "name": "...
3
null
Implement the Python class `TestQuantEmbedding` described below. Class description: test paddleslim.quant.quant_embedding Method signatures and docstrings: - def test_quant_embedding(self): paddleslim.quant.quant_embedding(program, place, config=None, scope=None) :return: - def test_quant_embedding1(self): paddleslim...
Implement the Python class `TestQuantEmbedding` described below. Class description: test paddleslim.quant.quant_embedding Method signatures and docstrings: - def test_quant_embedding(self): paddleslim.quant.quant_embedding(program, place, config=None, scope=None) :return: - def test_quant_embedding1(self): paddleslim...
bd3790ce72a2a26611b5eda3901651b5a809348f
<|skeleton|> class TestQuantEmbedding: """test paddleslim.quant.quant_embedding""" def test_quant_embedding(self): """paddleslim.quant.quant_embedding(program, place, config=None, scope=None) :return:""" <|body_0|> def test_quant_embedding1(self): """paddleslim.quant.quant_embeddin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestQuantEmbedding: """test paddleslim.quant.quant_embedding""" def test_quant_embedding(self): """paddleslim.quant.quant_embedding(program, place, config=None, scope=None) :return:""" startup_program = paddle.static.Program() train_program = paddle.static.Program() with p...
the_stack_v2_python_sparse
models/PaddleSlim/CI/Slim_CI_all_case/p1_api_case_static/test_api_quant_embedding.py
PaddlePaddle/PaddleTest
train
42
fed57dc3bb8cc0043c1505cca7ff05c86473b362
[ "super().__init__()\nself.inventory = None\nself.supplier_inventory = None\nself.indicators = None\nif inventory is not None and supplier_inventory is not None:\n self.build(inventory, supplier_inventory)", "print(f'Building QUBO')\nself.inventory = inventory\nself.supplier_inventory = supplier_inventory\nself...
<|body_start_0|> super().__init__() self.inventory = None self.supplier_inventory = None self.indicators = None if inventory is not None and supplier_inventory is not None: self.build(inventory, supplier_inventory) <|end_body_0|> <|body_start_1|> print(f'Buil...
SupplierQubo
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SupplierQubo: def __init__(self, inventory: list[int or str] or None, supplier_inventory: list[set[int or str]] or None) -> None: """Initializes the SupplierQubo inventory (list): List of items we want for our inventory supplier_inventory (list of sets): List for each supplier their inve...
stack_v2_sparse_classes_36k_train_018270
4,576
permissive
[ { "docstring": "Initializes the SupplierQubo inventory (list): List of items we want for our inventory supplier_inventory (list of sets): List for each supplier their inventory", "name": "__init__", "signature": "def __init__(self, inventory: list[int or str] or None, supplier_inventory: list[set[int or...
4
stack_v2_sparse_classes_30k_train_002658
Implement the Python class `SupplierQubo` described below. Class description: Implement the SupplierQubo class. Method signatures and docstrings: - def __init__(self, inventory: list[int or str] or None, supplier_inventory: list[set[int or str]] or None) -> None: Initializes the SupplierQubo inventory (list): List of...
Implement the Python class `SupplierQubo` described below. Class description: Implement the SupplierQubo class. Method signatures and docstrings: - def __init__(self, inventory: list[int or str] or None, supplier_inventory: list[set[int or str]] or None) -> None: Initializes the SupplierQubo inventory (list): List of...
de3a36e292683485682f0f7b12aabcf8f548bab7
<|skeleton|> class SupplierQubo: def __init__(self, inventory: list[int or str] or None, supplier_inventory: list[set[int or str]] or None) -> None: """Initializes the SupplierQubo inventory (list): List of items we want for our inventory supplier_inventory (list of sets): List for each supplier their inve...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SupplierQubo: def __init__(self, inventory: list[int or str] or None, supplier_inventory: list[set[int or str]] or None) -> None: """Initializes the SupplierQubo inventory (list): List of items we want for our inventory supplier_inventory (list of sets): List for each supplier their inventory""" ...
the_stack_v2_python_sparse
ZebraKet/models/SupplierQubo.py
olegxtend/Hackathon2021
train
0
b5d588c6f95481853b9d658933d0ec48620f8d7e
[ "super().__init__()\nself.t_last_solution = 0\nself.num_restarts = 0", "super().post_step(step, level_number)\nself.t_last_solution = step.levels[0].time + step.levels[0].dt\nself.num_restarts = step.status.get('restarts_in_a_row', 0)", "super().post_run(step, level_number)\nself._hooks__num_restarts = self.num...
<|body_start_0|> super().__init__() self.t_last_solution = 0 self.num_restarts = 0 <|end_body_0|> <|body_start_1|> super().post_step(step, level_number) self.t_last_solution = step.levels[0].time + step.levels[0].dt self.num_restarts = step.status.get('restarts_in_a_row'...
Compute the global error once after the run is finished. Because of some timing issues, we cannot inherit from the `LogError` class here. The issue is that the convergence controllers can change the step size after the final iteration but before the `post_run` functions of the hooks are called, which results in a misma...
LogGlobalErrorPostRun
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LogGlobalErrorPostRun: """Compute the global error once after the run is finished. Because of some timing issues, we cannot inherit from the `LogError` class here. The issue is that the convergence controllers can change the step size after the final iteration but before the `post_run` functions ...
stack_v2_sparse_classes_36k_train_018271
7,407
permissive
[ { "docstring": "Add an attribute for when the last solution was added.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Store the time at which the solution is stored. This is required because between the `post_step` hook where the solution is stored and the `post_run` ...
3
null
Implement the Python class `LogGlobalErrorPostRun` described below. Class description: Compute the global error once after the run is finished. Because of some timing issues, we cannot inherit from the `LogError` class here. The issue is that the convergence controllers can change the step size after the final iterati...
Implement the Python class `LogGlobalErrorPostRun` described below. Class description: Compute the global error once after the run is finished. Because of some timing issues, we cannot inherit from the `LogError` class here. The issue is that the convergence controllers can change the step size after the final iterati...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class LogGlobalErrorPostRun: """Compute the global error once after the run is finished. Because of some timing issues, we cannot inherit from the `LogError` class here. The issue is that the convergence controllers can change the step size after the final iteration but before the `post_run` functions ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LogGlobalErrorPostRun: """Compute the global error once after the run is finished. Because of some timing issues, we cannot inherit from the `LogError` class here. The issue is that the convergence controllers can change the step size after the final iteration but before the `post_run` functions of the hooks ...
the_stack_v2_python_sparse
pySDC/implementations/hooks/log_errors.py
Parallel-in-Time/pySDC
train
30
105672e66eb8bee3a5cfb49e473e97e855b6ed28
[ "task_qs = Task.objects.select_related('manager').prefetch_related('agent_list').filter(id=pk)\nif len(task_qs) < 1:\n return Response({'detail': 'Task not found!'}, status=400)\ntask = task_qs[0]\nself.check_object_permissions(request, task)\ntask_data = get_task_details(task)\nreturn Response(task_data, status...
<|body_start_0|> task_qs = Task.objects.select_related('manager').prefetch_related('agent_list').filter(id=pk) if len(task_qs) < 1: return Response({'detail': 'Task not found!'}, status=400) task = task_qs[0] self.check_object_permissions(request, task) task_data = ge...
TaskViewSetAgent
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskViewSetAgent: def retrieve(self, request, pk, format=None): """Sample response: --- { 'id': 11, 'title': 'Title', 'point': {'lat': 23.780926, 'lng': 90.422858}, 'status': 0, 'start': datetime, 'deadline': datetime, "images": ['url1..', 'url2..'], 'task_type': 'Doctors visit', 'agent_...
stack_v2_sparse_classes_36k_train_018272
22,163
no_license
[ { "docstring": "Sample response: --- { 'id': 11, 'title': 'Title', 'point': {'lat': 23.780926, 'lng': 90.422858}, 'status': 0, 'start': datetime, 'deadline': datetime, \"images\": ['url1..', 'url2..'], 'task_type': 'Doctors visit', 'agent_list': [50, 51], 'manager': 'name', 'custom_fields': [], 'address': 'addr...
4
null
Implement the Python class `TaskViewSetAgent` described below. Class description: Implement the TaskViewSetAgent class. Method signatures and docstrings: - def retrieve(self, request, pk, format=None): Sample response: --- { 'id': 11, 'title': 'Title', 'point': {'lat': 23.780926, 'lng': 90.422858}, 'status': 0, 'star...
Implement the Python class `TaskViewSetAgent` described below. Class description: Implement the TaskViewSetAgent class. Method signatures and docstrings: - def retrieve(self, request, pk, format=None): Sample response: --- { 'id': 11, 'title': 'Title', 'point': {'lat': 23.780926, 'lng': 90.422858}, 'status': 0, 'star...
11be165f85cda0ffe7a237d011de562d3dc64135
<|skeleton|> class TaskViewSetAgent: def retrieve(self, request, pk, format=None): """Sample response: --- { 'id': 11, 'title': 'Title', 'point': {'lat': 23.780926, 'lng': 90.422858}, 'status': 0, 'start': datetime, 'deadline': datetime, "images": ['url1..', 'url2..'], 'task_type': 'Doctors visit', 'agent_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TaskViewSetAgent: def retrieve(self, request, pk, format=None): """Sample response: --- { 'id': 11, 'title': 'Title', 'point': {'lat': 23.780926, 'lng': 90.422858}, 'status': 0, 'start': datetime, 'deadline': datetime, "images": ['url1..', 'url2..'], 'task_type': 'Doctors visit', 'agent_list': [50, 51...
the_stack_v2_python_sparse
apps/task/views.py
ash018/FFTracker
train
0
1c6315bf1ee497701ab03a0319aa9cf1024b13f0
[ "url = '/dashboard/bulkpricing/'\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.status_code, 302)", "url = '/dashboard/bulkpricing/'\nself.client.login(username=self.adminUN, password='pass')\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(re...
<|body_start_0|> url = '/dashboard/bulkpricing/' response = self.client.get(url, HTTP_HOST='website.domain') self.assertEqual(response.status_code, 302) <|end_body_0|> <|body_start_1|> url = '/dashboard/bulkpricing/' self.client.login(username=self.adminUN, password='pass') ...
DashboardBulkpricingTestCase
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DashboardBulkpricingTestCase: def test_not_logged_in(self): """Test that the dashboard bulkpricing view will redirect whilst not logged in.""" <|body_0|> def test_logged_in_admin(self): """Test that the dashboard bulkpricing view will load whilst logged in as admin."...
stack_v2_sparse_classes_36k_train_018273
26,818
permissive
[ { "docstring": "Test that the dashboard bulkpricing view will redirect whilst not logged in.", "name": "test_not_logged_in", "signature": "def test_not_logged_in(self)" }, { "docstring": "Test that the dashboard bulkpricing view will load whilst logged in as admin.", "name": "test_logged_in_...
3
null
Implement the Python class `DashboardBulkpricingTestCase` described below. Class description: Implement the DashboardBulkpricingTestCase class. Method signatures and docstrings: - def test_not_logged_in(self): Test that the dashboard bulkpricing view will redirect whilst not logged in. - def test_logged_in_admin(self...
Implement the Python class `DashboardBulkpricingTestCase` described below. Class description: Implement the DashboardBulkpricingTestCase class. Method signatures and docstrings: - def test_not_logged_in(self): Test that the dashboard bulkpricing view will redirect whilst not logged in. - def test_logged_in_admin(self...
37d2942efcbdaad072f7a06ac876a40e0f69f702
<|skeleton|> class DashboardBulkpricingTestCase: def test_not_logged_in(self): """Test that the dashboard bulkpricing view will redirect whilst not logged in.""" <|body_0|> def test_logged_in_admin(self): """Test that the dashboard bulkpricing view will load whilst logged in as admin."...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DashboardBulkpricingTestCase: def test_not_logged_in(self): """Test that the dashboard bulkpricing view will redirect whilst not logged in.""" url = '/dashboard/bulkpricing/' response = self.client.get(url, HTTP_HOST='website.domain') self.assertEqual(response.status_code, 302)...
the_stack_v2_python_sparse
mooring/test_views.py
dbca-wa/moorings
train
0
32c1571a62386f6d4fb490056be5dc4bfd9763d7
[ "super(PytorchGraphConverter, self).__init__(framework, base_path)\nprint('{} bmodel converter init'.format(model_name))\nself.model_name = model_name\nself.models_path = models_path\nself.shapes = shapes\nself.dyns = dyns\nself.outdirs = outdirs\nself.nets_name = nets_name\nself.target = target\nassert len(self.mo...
<|body_start_0|> super(PytorchGraphConverter, self).__init__(framework, base_path) print('{} bmodel converter init'.format(model_name)) self.model_name = model_name self.models_path = models_path self.shapes = shapes self.dyns = dyns self.outdirs = outdirs ...
pytorch graph bmodel converter
PytorchGraphConverter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PytorchGraphConverter: """pytorch graph bmodel converter""" def __init__(self, model_name, base_path, models_path, shapes, dyns, outdirs, nets_name, framework, target): """Init pytorch graph bmodel converter""" <|body_0|> def converter(self): """convert pytorch g...
stack_v2_sparse_classes_36k_train_018274
15,723
permissive
[ { "docstring": "Init pytorch graph bmodel converter", "name": "__init__", "signature": "def __init__(self, model_name, base_path, models_path, shapes, dyns, outdirs, nets_name, framework, target)" }, { "docstring": "convert pytorch graph", "name": "converter", "signature": "def converter...
2
stack_v2_sparse_classes_30k_train_013102
Implement the Python class `PytorchGraphConverter` described below. Class description: pytorch graph bmodel converter Method signatures and docstrings: - def __init__(self, model_name, base_path, models_path, shapes, dyns, outdirs, nets_name, framework, target): Init pytorch graph bmodel converter - def converter(sel...
Implement the Python class `PytorchGraphConverter` described below. Class description: pytorch graph bmodel converter Method signatures and docstrings: - def __init__(self, model_name, base_path, models_path, shapes, dyns, outdirs, nets_name, framework, target): Init pytorch graph bmodel converter - def converter(sel...
c9fa07851da663dda4953dba72e1d3937299a4ea
<|skeleton|> class PytorchGraphConverter: """pytorch graph bmodel converter""" def __init__(self, model_name, base_path, models_path, shapes, dyns, outdirs, nets_name, framework, target): """Init pytorch graph bmodel converter""" <|body_0|> def converter(self): """convert pytorch g...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PytorchGraphConverter: """pytorch graph bmodel converter""" def __init__(self, model_name, base_path, models_path, shapes, dyns, outdirs, nets_name, framework, target): """Init pytorch graph bmodel converter""" super(PytorchGraphConverter, self).__init__(framework, base_path) prin...
the_stack_v2_python_sparse
modules/utils/bmodel_converter.py
sophon-ai-algo/sophon-inference
train
32
f7d10d41f7e0b2aae4cdde6a9a1c6e1eb4a94819
[ "res = []\nlayer = [root]\nwhile any(layer):\n next_layer = []\n for node in layer:\n if node:\n next_layer.extend([node.left, node.right])\n res.append(str(node.val))\n else:\n res.append('#')\n layer = next_layer\nreturn ','.join(res)", "if not data:\n ...
<|body_start_0|> res = [] layer = [root] while any(layer): next_layer = [] for node in layer: if node: next_layer.extend([node.left, node.right]) res.append(str(node.val)) else: 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_018275
1,804
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:...
501c347004c140a82a95461e1dbcef6775b3d9da
<|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""" res = [] layer = [root] while any(layer): next_layer = [] for node in layer: if node: next_layer.extend([node....
the_stack_v2_python_sparse
297-serialize_and_deserialize_binary_tree.py
dkrotx/leetcode
train
0
e49f8c0e1fbe2296d393d8acdee0d0edb15c41c1
[ "l, r = (1, num)\nwhile l <= r:\n mid = (l + r) // 2\n square = mid * mid\n if square == num:\n return True\n elif square > num:\n r = mid - 1\n else:\n l = mid + 1\nreturn False", "i = 1\nwhile num > 0:\n num -= i\n i += 2\nreturn num == 0" ]
<|body_start_0|> l, r = (1, num) while l <= r: mid = (l + r) // 2 square = mid * mid if square == num: return True elif square > num: r = mid - 1 else: l = mid + 1 return False <|end_body_...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPerfectSquare(self, num: int) -> bool: """1. 二分查找""" <|body_0|> def isPerfectSquare_2(self, num: int) -> bool: """2. 平方数一定可以写成 等差数列 之和:16=1+3+5+7""" <|body_1|> <|end_skeleton|> <|body_start_0|> l, r = (1, num) while l <= r: ...
stack_v2_sparse_classes_36k_train_018276
1,278
no_license
[ { "docstring": "1. 二分查找", "name": "isPerfectSquare", "signature": "def isPerfectSquare(self, num: int) -> bool" }, { "docstring": "2. 平方数一定可以写成 等差数列 之和:16=1+3+5+7", "name": "isPerfectSquare_2", "signature": "def isPerfectSquare_2(self, num: int) -> bool" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPerfectSquare(self, num: int) -> bool: 1. 二分查找 - def isPerfectSquare_2(self, num: int) -> bool: 2. 平方数一定可以写成 等差数列 之和:16=1+3+5+7
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPerfectSquare(self, num: int) -> bool: 1. 二分查找 - def isPerfectSquare_2(self, num: int) -> bool: 2. 平方数一定可以写成 等差数列 之和:16=1+3+5+7 <|skeleton|> class Solution: def isPer...
4732fb80710a08a715c3e7080c394f5298b8326d
<|skeleton|> class Solution: def isPerfectSquare(self, num: int) -> bool: """1. 二分查找""" <|body_0|> def isPerfectSquare_2(self, num: int) -> bool: """2. 平方数一定可以写成 等差数列 之和:16=1+3+5+7""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPerfectSquare(self, num: int) -> bool: """1. 二分查找""" l, r = (1, num) while l <= r: mid = (l + r) // 2 square = mid * mid if square == num: return True elif square > num: r = mid - 1 ...
the_stack_v2_python_sparse
.leetcode/367.有效的完全平方数.py
xiaoruijiang/algorithm
train
0
eb3cc5ca9a125393a703ed7178e464ac876ea14a
[ "if not root:\n return []\nres = [[root.val]]\nstruc = [[root]]\nlevel = 0\nwhile struc[level]:\n temp_res = []\n temp_struc = []\n for i in struc[level]:\n if i:\n temp_struc.extend([i.left, i.right])\n if i.left:\n temp_res.append(i.left.val)\n if...
<|body_start_0|> if not root: return [] res = [[root.val]] struc = [[root]] level = 0 while struc[level]: temp_res = [] temp_struc = [] for i in struc[level]: if i: temp_struc.extend([i.left, i.ri...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def levelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_0|> def levelOrder2(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root: ...
stack_v2_sparse_classes_36k_train_018277
1,837
no_license
[ { "docstring": ":type root: TreeNode :rtype: List[List[int]]", "name": "levelOrder", "signature": "def levelOrder(self, root)" }, { "docstring": ":type root: TreeNode :rtype: List[List[int]]", "name": "levelOrder2", "signature": "def levelOrder2(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_016575
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]] - def levelOrder2(self, root): :type root: TreeNode :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]] - def levelOrder2(self, root): :type root: TreeNode :rtype: List[List[int]] <|skeleton|> class Solution:...
391328c7c601b5c77ff250ad173600d4d1dd7f57
<|skeleton|> class Solution: def levelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_0|> def levelOrder2(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def levelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" if not root: return [] res = [[root.val]] struc = [[root]] level = 0 while struc[level]: temp_res = [] temp_struc = [] for i ...
the_stack_v2_python_sparse
leetcode/algo/102. Binary Tree Level Order Traversal.py
wduncan21/Challenges
train
0
3a65c2e4a42a6902c9b1e98bfa023e4e0bde7002
[ "allure.dynamic.title('Wolf at the beginning of the queue')\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>')\nlst = ['wolf', 'sheep', 'sheep', 'she...
<|body_start_0|> allure.dynamic.title('Wolf at the beginning of the queue') 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>') ...
Testing warn_the_sheep function
WarnTheSheepTestCase
[ "Unlicense", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WarnTheSheepTestCase: """Testing warn_the_sheep function""" def test_warn_the_sheep_wolf_at_start(self): """If the wolf is the closest animal to you, return "Pls go away and stop eating my sheep". :return:""" <|body_0|> def test_warn_the_sheep_wolf_in_middle(self): ...
stack_v2_sparse_classes_36k_train_018278
4,284
permissive
[ { "docstring": "If the wolf is the closest animal to you, return \"Pls go away and stop eating my sheep\". :return:", "name": "test_warn_the_sheep_wolf_at_start", "signature": "def test_warn_the_sheep_wolf_at_start(self)" }, { "docstring": "If the wolf is the closest animal to you, return \"Pls ...
3
null
Implement the Python class `WarnTheSheepTestCase` described below. Class description: Testing warn_the_sheep function Method signatures and docstrings: - def test_warn_the_sheep_wolf_at_start(self): If the wolf is the closest animal to you, return "Pls go away and stop eating my sheep". :return: - def test_warn_the_s...
Implement the Python class `WarnTheSheepTestCase` described below. Class description: Testing warn_the_sheep function Method signatures and docstrings: - def test_warn_the_sheep_wolf_at_start(self): If the wolf is the closest animal to you, return "Pls go away and stop eating my sheep". :return: - def test_warn_the_s...
ba3ea81125b6082d867f0ae34c6c9be15e153966
<|skeleton|> class WarnTheSheepTestCase: """Testing warn_the_sheep function""" def test_warn_the_sheep_wolf_at_start(self): """If the wolf is the closest animal to you, return "Pls go away and stop eating my sheep". :return:""" <|body_0|> def test_warn_the_sheep_wolf_in_middle(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WarnTheSheepTestCase: """Testing warn_the_sheep function""" def test_warn_the_sheep_wolf_at_start(self): """If the wolf is the closest animal to you, return "Pls go away and stop eating my sheep". :return:""" allure.dynamic.title('Wolf at the beginning of the queue') allure.dynami...
the_stack_v2_python_sparse
kyu_8/wolf_in_sheep_clothing/test_wolf_in_sheep_clothing.py
qamine-test/codewars
train
0
e51a01074b6f21dd3a86493642115b98d1975d7b
[ "if root is None:\n return 0\nmax_count = [1]\n\ndef DFS(node, count, parent_val):\n if parent_val + 1 == node.val:\n count += 1\n max_count[0] = max(max_count[0], count)\n else:\n count = 1\n if node.left:\n DFS(node.left, count, node.val)\n if node.right:\n DFS(no...
<|body_start_0|> if root is None: return 0 max_count = [1] def DFS(node, count, parent_val): if parent_val + 1 == node.val: count += 1 max_count[0] = max(max_count[0], count) else: count = 1 if node....
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestConsecutive(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def longestConsecutive(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if root is None: retu...
stack_v2_sparse_classes_36k_train_018279
2,033
no_license
[ { "docstring": ":type root: TreeNode :rtype: int", "name": "longestConsecutive", "signature": "def longestConsecutive(self, root)" }, { "docstring": ":type root: TreeNode :rtype: int", "name": "longestConsecutive", "signature": "def longestConsecutive(self, root)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestConsecutive(self, root): :type root: TreeNode :rtype: int - def longestConsecutive(self, root): :type root: TreeNode :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestConsecutive(self, root): :type root: TreeNode :rtype: int - def longestConsecutive(self, root): :type root: TreeNode :rtype: int <|skeleton|> class Solution: def...
8bb17099be02d997d554519be360ef4aa1c028e3
<|skeleton|> class Solution: def longestConsecutive(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def longestConsecutive(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestConsecutive(self, root): """:type root: TreeNode :rtype: int""" if root is None: return 0 max_count = [1] def DFS(node, count, parent_val): if parent_val + 1 == node.val: count += 1 max_count[0] = max...
the_stack_v2_python_sparse
Google/2. medium/298. Binary Tree Longest Consecutive Sequence.py
yemao616/summer18
train
0
1fe89e0523c9160939709328d164a6fb22522b9e
[ "counter = 0\nwhile head:\n counter += 1\n head = head.next\nreturn counter", "for i in range(size - 1):\n if not head:\n break\n head = head.next\nif not head:\n return None\nnext_start, head.next = (head.next, None)\nreturn next_start", "curr = dummy_start\nwhile l1 and l2:\n if l1.va...
<|body_start_0|> counter = 0 while head: counter += 1 head = head.next return counter <|end_body_0|> <|body_start_1|> for i in range(size - 1): if not head: break head = head.next if not head: return Non...
Algorithm: Bottom Up Merge Sort 1) Start with splitting the list into sublists of size 1. Each adjacent pair of sublists of size 1 is merged in sorted order. After the first iteration, we get the sorted lists of size 2. A similar process is repeated for a sublist of size 2. In this way, we iteratively split the list in...
Solution2
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution2: """Algorithm: Bottom Up Merge Sort 1) Start with splitting the list into sublists of size 1. Each adjacent pair of sublists of size 1 is merged in sorted order. After the first iteration, we get the sorted lists of size 2. A similar process is repeated for a sublist of size 2. In this ...
stack_v2_sparse_classes_36k_train_018280
4,593
permissive
[ { "docstring": "Count the length of the linked list", "name": "get_size", "signature": "def get_size(self, head: ListNode) -> int" }, { "docstring": "Given the head & size, return the start node of the next chunk", "name": "split", "signature": "def split(self, head: ListNode, size: int)...
4
stack_v2_sparse_classes_30k_train_005021
Implement the Python class `Solution2` described below. Class description: Algorithm: Bottom Up Merge Sort 1) Start with splitting the list into sublists of size 1. Each adjacent pair of sublists of size 1 is merged in sorted order. After the first iteration, we get the sorted lists of size 2. A similar process is rep...
Implement the Python class `Solution2` described below. Class description: Algorithm: Bottom Up Merge Sort 1) Start with splitting the list into sublists of size 1. Each adjacent pair of sublists of size 1 is merged in sorted order. After the first iteration, we get the sorted lists of size 2. A similar process is rep...
9f66d352c805fcdd9930aaa18c93d7546768287c
<|skeleton|> class Solution2: """Algorithm: Bottom Up Merge Sort 1) Start with splitting the list into sublists of size 1. Each adjacent pair of sublists of size 1 is merged in sorted order. After the first iteration, we get the sorted lists of size 2. A similar process is repeated for a sublist of size 2. In this ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution2: """Algorithm: Bottom Up Merge Sort 1) Start with splitting the list into sublists of size 1. Each adjacent pair of sublists of size 1 is merged in sorted order. After the first iteration, we get the sorted lists of size 2. A similar process is repeated for a sublist of size 2. In this way, we itera...
the_stack_v2_python_sparse
medium/148_sort_list.py
niki4/leetcode_py3
train
0
6732325006f21a58628517b3b5fb88d4d2bf10fe
[ "self.dirname = Path(dirname).absolute()\nself.basename = basename\nif not self.dirname.is_dir():\n raise ValueError('dirname must be a directory')", "all_filenames = self.dirname.glob('*')\nd = {}\nfor v in all_filenames:\n split_fn = v.name\n m = glob.re.search('^(\\\\w+)\\\\.%s\\\\.(\\\\d+)$' % typest...
<|body_start_0|> self.dirname = Path(dirname).absolute() self.basename = basename if not self.dirname.is_dir(): raise ValueError('dirname must be a directory') <|end_body_0|> <|body_start_1|> all_filenames = self.dirname.glob('*') d = {} for v in all_filename...
Simple class to interpret user's requests into KlustaKwik filenames
FilenameParser
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FilenameParser: """Simple class to interpret user's requests into KlustaKwik filenames""" def __init__(self, dirname, basename=None): """Initialize a new parser for a directory containing files dirname: directory containing files basename: basename in KlustaKwik format spec If basena...
stack_v2_sparse_classes_36k_train_018281
17,008
permissive
[ { "docstring": "Initialize a new parser for a directory containing files dirname: directory containing files basename: basename in KlustaKwik format spec If basename is left None, then files with any basename in the directory will be used. An error is raised if files with multiple basenames exist in the directo...
2
stack_v2_sparse_classes_30k_train_015215
Implement the Python class `FilenameParser` described below. Class description: Simple class to interpret user's requests into KlustaKwik filenames Method signatures and docstrings: - def __init__(self, dirname, basename=None): Initialize a new parser for a directory containing files dirname: directory containing fil...
Implement the Python class `FilenameParser` described below. Class description: Simple class to interpret user's requests into KlustaKwik filenames Method signatures and docstrings: - def __init__(self, dirname, basename=None): Initialize a new parser for a directory containing files dirname: directory containing fil...
354c8d9d5fbc4daad3547773d2f281f8c163d208
<|skeleton|> class FilenameParser: """Simple class to interpret user's requests into KlustaKwik filenames""" def __init__(self, dirname, basename=None): """Initialize a new parser for a directory containing files dirname: directory containing files basename: basename in KlustaKwik format spec If basena...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FilenameParser: """Simple class to interpret user's requests into KlustaKwik filenames""" def __init__(self, dirname, basename=None): """Initialize a new parser for a directory containing files dirname: directory containing files basename: basename in KlustaKwik format spec If basename is left No...
the_stack_v2_python_sparse
neo/io/klustakwikio.py
NeuralEnsemble/python-neo
train
265
2a4ce08fa1df750db7bae3280b585a4edea41da7
[ "_id = request.form.get('id', request.args.get('id', None))\nif _id is None:\n return ({'success': False, 'message': 'missing parameter: id'}, 400)\njob_spec = mozart_es.get_by_id(index=JOB_SPECS_INDEX, id=_id, ignore=404)\napp.logger.info(job_spec)\nif job_spec['found'] is False:\n app.logger.error('job_spec...
<|body_start_0|> _id = request.form.get('id', request.args.get('id', None)) if _id is None: return ({'success': False, 'message': 'missing parameter: id'}, 400) job_spec = mozart_es.get_by_id(index=JOB_SPECS_INDEX, id=_id, ignore=404) app.logger.info(job_spec) if job_...
Rest APIs for all job_specs (GET, POST, DELETE)
JobSpecs
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JobSpecs: """Rest APIs for all job_specs (GET, POST, DELETE)""" def get(self): """Gets a Job Type specification object for the given ID.""" <|body_0|> def post(self): """Add a Job Type specification JSON object.""" <|body_1|> def delete(self): ...
stack_v2_sparse_classes_36k_train_018282
13,931
permissive
[ { "docstring": "Gets a Job Type specification object for the given ID.", "name": "get", "signature": "def get(self)" }, { "docstring": "Add a Job Type specification JSON object.", "name": "post", "signature": "def post(self)" }, { "docstring": "Remove Job Spec for the given ID", ...
3
stack_v2_sparse_classes_30k_test_000641
Implement the Python class `JobSpecs` described below. Class description: Rest APIs for all job_specs (GET, POST, DELETE) Method signatures and docstrings: - def get(self): Gets a Job Type specification object for the given ID. - def post(self): Add a Job Type specification JSON object. - def delete(self): Remove Job...
Implement the Python class `JobSpecs` described below. Class description: Rest APIs for all job_specs (GET, POST, DELETE) Method signatures and docstrings: - def get(self): Gets a Job Type specification object for the given ID. - def post(self): Add a Job Type specification JSON object. - def delete(self): Remove Job...
c238340fafd96a9b92d92e544d0892a354c1ca32
<|skeleton|> class JobSpecs: """Rest APIs for all job_specs (GET, POST, DELETE)""" def get(self): """Gets a Job Type specification object for the given ID.""" <|body_0|> def post(self): """Add a Job Type specification JSON object.""" <|body_1|> def delete(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JobSpecs: """Rest APIs for all job_specs (GET, POST, DELETE)""" def get(self): """Gets a Job Type specification object for the given ID.""" _id = request.form.get('id', request.args.get('id', None)) if _id is None: return ({'success': False, 'message': 'missing paramet...
the_stack_v2_python_sparse
mozart/services/api_v02/specs.py
hysds/mozart
train
1
a6489cd60d6902b6bbd014ce5508f25107fea124
[ "res = super(AccountInvoiceLine, self).onchange_invoice_product_id(product_id, invoice)\nif isinstance(product_id, int):\n product_id = self.env['product.product'].browse(product_id)\nsuppinfo = False\nfiscal_position = invoice.fiscal_position_id\nif product_id:\n if product_id.purchase_ok and invoice.type in...
<|body_start_0|> res = super(AccountInvoiceLine, self).onchange_invoice_product_id(product_id, invoice) if isinstance(product_id, int): product_id = self.env['product.product'].browse(product_id) suppinfo = False fiscal_position = invoice.fiscal_position_id if product...
AccountInvoiceLine
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountInvoiceLine: def onchange_invoice_product_id(self, product_id, invoice): """Récupération des infos du produit et du supplierinfo""" <|body_0|> def _onchange_sec_uom_qty(self): """Au changement de la qty, changement des autres qty""" <|body_1|> def...
stack_v2_sparse_classes_36k_train_018283
14,763
no_license
[ { "docstring": "Récupération des infos du produit et du supplierinfo", "name": "onchange_invoice_product_id", "signature": "def onchange_invoice_product_id(self, product_id, invoice)" }, { "docstring": "Au changement de la qty, changement des autres qty", "name": "_onchange_sec_uom_qty", ...
3
null
Implement the Python class `AccountInvoiceLine` described below. Class description: Implement the AccountInvoiceLine class. Method signatures and docstrings: - def onchange_invoice_product_id(self, product_id, invoice): Récupération des infos du produit et du supplierinfo - def _onchange_sec_uom_qty(self): Au changem...
Implement the Python class `AccountInvoiceLine` described below. Class description: Implement the AccountInvoiceLine class. Method signatures and docstrings: - def onchange_invoice_product_id(self, product_id, invoice): Récupération des infos du produit et du supplierinfo - def _onchange_sec_uom_qty(self): Au changem...
eb394e1f79ba1995da2dcd81adfdd511c22caff9
<|skeleton|> class AccountInvoiceLine: def onchange_invoice_product_id(self, product_id, invoice): """Récupération des infos du produit et du supplierinfo""" <|body_0|> def _onchange_sec_uom_qty(self): """Au changement de la qty, changement des autres qty""" <|body_1|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccountInvoiceLine: def onchange_invoice_product_id(self, product_id, invoice): """Récupération des infos du produit et du supplierinfo""" res = super(AccountInvoiceLine, self).onchange_invoice_product_id(product_id, invoice) if isinstance(product_id, int): product_id = sel...
the_stack_v2_python_sparse
OpenPROD/openprod-addons/purchase/account_invoice.py
kazacube-mziouadi/ceci
train
0
325fbf053795413e392bdfa484e193cfefd49874
[ "self.prefix_sum_array = []\nprefix_sum = 0\nfor weight in w:\n prefix_sum += weight\n self.prefix_sum_array.append(prefix_sum)\nself.total_sum = prefix_sum", "from bisect import bisect_left\nprefix_sum = self.total_sum * random.random()\nreturn bisect_left(self.prefix_sum_array, prefix_sum)" ]
<|body_start_0|> self.prefix_sum_array = [] prefix_sum = 0 for weight in w: prefix_sum += weight self.prefix_sum_array.append(prefix_sum) self.total_sum = prefix_sum <|end_body_0|> <|body_start_1|> from bisect import bisect_left prefix_sum = self....
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def __init__(self, w): """:type w: List[int]""" <|body_0|> def pickIndex(self): """:rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.prefix_sum_array = [] prefix_sum = 0 for weight in w: prefix_su...
stack_v2_sparse_classes_36k_train_018284
648
permissive
[ { "docstring": ":type w: List[int]", "name": "__init__", "signature": "def __init__(self, w)" }, { "docstring": ":rtype: int", "name": "pickIndex", "signature": "def pickIndex(self)" } ]
2
stack_v2_sparse_classes_30k_train_007327
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def __init__(self, w): :type w: List[int] - def pickIndex(self): :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def __init__(self, w): :type w: List[int] - def pickIndex(self): :rtype: int <|skeleton|> class Solution: def __init__(self, w): """:type w: List[int]""" <|...
bf03743a3676ca9a8c107f92cf3858b6887d0308
<|skeleton|> class Solution: def __init__(self, w): """:type w: List[int]""" <|body_0|> def pickIndex(self): """:rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def __init__(self, w): """:type w: List[int]""" self.prefix_sum_array = [] prefix_sum = 0 for weight in w: prefix_sum += weight self.prefix_sum_array.append(prefix_sum) self.total_sum = prefix_sum def pickIndex(self): """:r...
the_stack_v2_python_sparse
python/528_random_pick_with_weight.py
liaison/LeetCode
train
17
46c1bf38178e10091bce874178c79c8292b3cf46
[ "try:\n volume = int(redis.get('fm:player:volume'))\nexcept ValueError:\n volume = 100\nreturn http.OK({'volume': volume})", "serializer = VolumeSerializer()\ntry:\n data = serializer.marshal(request.json)\nexcept MappingErrors as e:\n return http.UnprocessableEntity(errors=e.message)\nredis.publish(c...
<|body_start_0|> try: volume = int(redis.get('fm:player:volume')) except ValueError: volume = 100 return http.OK({'volume': volume}) <|end_body_0|> <|body_start_1|> serializer = VolumeSerializer() try: data = serializer.marshal(request.json) ...
Contorls Volume on the Physical player.
VolumeView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VolumeView: """Contorls Volume on the Physical player.""" def get(self): """Retrieve the current volume level for the physical player.""" <|body_0|> def post(self): """Change the volume level for the player.""" <|body_1|> <|end_skeleton|> <|body_start_0...
stack_v2_sparse_classes_36k_train_018285
12,943
no_license
[ { "docstring": "Retrieve the current volume level for the physical player.", "name": "get", "signature": "def get(self)" }, { "docstring": "Change the volume level for the player.", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_019462
Implement the Python class `VolumeView` described below. Class description: Contorls Volume on the Physical player. Method signatures and docstrings: - def get(self): Retrieve the current volume level for the physical player. - def post(self): Change the volume level for the player.
Implement the Python class `VolumeView` described below. Class description: Contorls Volume on the Physical player. Method signatures and docstrings: - def get(self): Retrieve the current volume level for the physical player. - def post(self): Change the volume level for the player. <|skeleton|> class VolumeView: ...
817766c6d2e2660291b723274d345ce5eb40ab77
<|skeleton|> class VolumeView: """Contorls Volume on the Physical player.""" def get(self): """Retrieve the current volume level for the physical player.""" <|body_0|> def post(self): """Change the volume level for the player.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VolumeView: """Contorls Volume on the Physical player.""" def get(self): """Retrieve the current volume level for the physical player.""" try: volume = int(redis.get('fm:player:volume')) except ValueError: volume = 100 return http.OK({'volume': volu...
the_stack_v2_python_sparse
fm/views/player.py
thisissoon/FM-API
train
3
6f97c9fe59b491b3f585e4695249f63f1543559a
[ "super().__init__(n_head, n_feat, dropout_rate)\nself.zero_triu = zero_triu\nself.linear_pos = nn.Linear(n_feat, n_feat, bias=False)\nself.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))\nself.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))\ntorch.nn.init.xavier_uniform_(self.pos_bias_u)\ntorch....
<|body_start_0|> super().__init__(n_head, n_feat, dropout_rate) self.zero_triu = zero_triu self.linear_pos = nn.Linear(n_feat, n_feat, bias=False) self.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k)) self.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k)) ...
Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate. zero_triu (bool)...
RelPositionMultiHeadedAttention
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelPositionMultiHeadedAttention: """Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of fea...
stack_v2_sparse_classes_36k_train_018286
11,646
permissive
[ { "docstring": "Construct an RelPositionMultiHeadedAttention object.", "name": "__init__", "signature": "def __init__(self, n_head, n_feat, dropout_rate, zero_triu=False)" }, { "docstring": "Compute relative positional encoding. Args: x (torch.Tensor): Input tensor (batch, head, time1, 2*time1-1...
3
null
Implement the Python class `RelPositionMultiHeadedAttention` described below. Class description: Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of...
Implement the Python class `RelPositionMultiHeadedAttention` described below. Class description: Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class RelPositionMultiHeadedAttention: """Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of fea...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RelPositionMultiHeadedAttention: """Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of features. dropou...
the_stack_v2_python_sparse
espnet/nets/pytorch_backend/transformer/attention.py
espnet/espnet
train
7,242
6c2cc2009c99a7814846642daad27a99073c6cd0
[ "super().save_model(request, obj, form, change)\nfrom celery_tasks.tasks import generate_static_index_html\ngenerate_static_index_html.delay()\ncache.delete('index_page_data')", "super().save_model(request, obj)\nfrom celery_tasks.tasks import generate_static_index_html\ngenerate_static_index_html.delay()\ncache....
<|body_start_0|> super().save_model(request, obj, form, change) from celery_tasks.tasks import generate_static_index_html generate_static_index_html.delay() cache.delete('index_page_data') <|end_body_0|> <|body_start_1|> super().save_model(request, obj) from celery_tasks...
BaseModelAdmin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseModelAdmin: def save_model(self, request, obj, form, change): """后台新增或更新表中的数据时调用这个方法""" <|body_0|> def delete_model(self, request, obj): """删除表中的数据时也使用""" <|body_1|> <|end_skeleton|> <|body_start_0|> super().save_model(request, obj, form, change...
stack_v2_sparse_classes_36k_train_018287
1,872
no_license
[ { "docstring": "后台新增或更新表中的数据时调用这个方法", "name": "save_model", "signature": "def save_model(self, request, obj, form, change)" }, { "docstring": "删除表中的数据时也使用", "name": "delete_model", "signature": "def delete_model(self, request, obj)" } ]
2
stack_v2_sparse_classes_30k_train_003489
Implement the Python class `BaseModelAdmin` described below. Class description: Implement the BaseModelAdmin class. Method signatures and docstrings: - def save_model(self, request, obj, form, change): 后台新增或更新表中的数据时调用这个方法 - def delete_model(self, request, obj): 删除表中的数据时也使用
Implement the Python class `BaseModelAdmin` described below. Class description: Implement the BaseModelAdmin class. Method signatures and docstrings: - def save_model(self, request, obj, form, change): 后台新增或更新表中的数据时调用这个方法 - def delete_model(self, request, obj): 删除表中的数据时也使用 <|skeleton|> class BaseModelAdmin: def...
206909fa8ab76de4b2aa5cabc9d76e9977809d46
<|skeleton|> class BaseModelAdmin: def save_model(self, request, obj, form, change): """后台新增或更新表中的数据时调用这个方法""" <|body_0|> def delete_model(self, request, obj): """删除表中的数据时也使用""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseModelAdmin: def save_model(self, request, obj, form, change): """后台新增或更新表中的数据时调用这个方法""" super().save_model(request, obj, form, change) from celery_tasks.tasks import generate_static_index_html generate_static_index_html.delay() cache.delete('index_page_data') d...
the_stack_v2_python_sparse
E-commerce/dailyfresh/apps/goods/admin.py
zxk1994/Project
train
0
66284f5d00c672fdd26fd53213b47ab1fb673281
[ "if request.user.has_perm(CHANGE_TASK):\n task = Task.objects.get(pk=request.data['id_task'])\n team = Team.objects.get(pk=request.data['id_team'])\n task.teams.add(team)\n return Response(status=status.HTTP_201_CREATED)\nreturn Response(status=status.HTTP_401_UNAUTHORIZED)", "if request.user.has_perm...
<|body_start_0|> if request.user.has_perm(CHANGE_TASK): task = Task.objects.get(pk=request.data['id_task']) team = Team.objects.get(pk=request.data['id_team']) task.teams.add(team) return Response(status=status.HTTP_201_CREATED) return Response(status=stat...
\\n# Assign a team to a task. Parameters : request (HttpRequest) : the request coming from the front-end id (int) : the id of the task Return : response (Response) : the response. POST request : add team to task PUT request : remove team from task If the user doesn't have the permissions, it will send HTTP 401. Both re...
AddTeamToTask
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddTeamToTask: """\\n# Assign a team to a task. Parameters : request (HttpRequest) : the request coming from the front-end id (int) : the id of the task Return : response (Response) : the response. POST request : add team to task PUT request : remove team from task If the user doesn't have the pe...
stack_v2_sparse_classes_36k_train_018288
21,722
permissive
[ { "docstring": "Assign a team to a task.", "name": "post", "signature": "def post(self, request)" }, { "docstring": "Remove a team from a task.", "name": "put", "signature": "def put(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_008442
Implement the Python class `AddTeamToTask` described below. Class description: \\n# Assign a team to a task. Parameters : request (HttpRequest) : the request coming from the front-end id (int) : the id of the task Return : response (Response) : the response. POST request : add team to task PUT request : remove team fr...
Implement the Python class `AddTeamToTask` described below. Class description: \\n# Assign a team to a task. Parameters : request (HttpRequest) : the request coming from the front-end id (int) : the id of the task Return : response (Response) : the response. POST request : add team to task PUT request : remove team fr...
56511ebac83a5dc1fb8768a98bc675e88530a447
<|skeleton|> class AddTeamToTask: """\\n# Assign a team to a task. Parameters : request (HttpRequest) : the request coming from the front-end id (int) : the id of the task Return : response (Response) : the response. POST request : add team to task PUT request : remove team from task If the user doesn't have the pe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AddTeamToTask: """\\n# Assign a team to a task. Parameters : request (HttpRequest) : the request coming from the front-end id (int) : the id of the task Return : response (Response) : the response. POST request : add team to task PUT request : remove team from task If the user doesn't have the permissions, it...
the_stack_v2_python_sparse
maintenancemanagement/views/views_task.py
Open-CMMS/openCMMS_backend
train
4
694c38324e3bf23b4398aefe1d0871af5e873463
[ "if stack:\n node = stack.pop()\n if node.right:\n node = node.right\n stack.append(node)\n while node.left:\n node = node.left\n stack.append(node)\n else:\n while stack and stack[-1].val < node.val:\n stack.pop()\n return stack[-1] if stack ...
<|body_start_0|> if stack: node = stack.pop() if node.right: node = node.right stack.append(node) while node.left: node = node.left stack.append(node) else: while stack and...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _nextGT(self, stack): """find node with smallest value > stack[-1].val.""" <|body_0|> def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode: """Q0272, inorder predecessor and successor.""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_36k_train_018289
921
no_license
[ { "docstring": "find node with smallest value > stack[-1].val.", "name": "_nextGT", "signature": "def _nextGT(self, stack)" }, { "docstring": "Q0272, inorder predecessor and successor.", "name": "inorderSuccessor", "signature": "def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> ...
2
stack_v2_sparse_classes_30k_test_001065
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _nextGT(self, stack): find node with smallest value > stack[-1].val. - def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode: Q0272, inorder predecessor and suc...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _nextGT(self, stack): find node with smallest value > stack[-1].val. - def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode: Q0272, inorder predecessor and suc...
6043134736452a6f4704b62857d0aed2e9571164
<|skeleton|> class Solution: def _nextGT(self, stack): """find node with smallest value > stack[-1].val.""" <|body_0|> def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode: """Q0272, inorder predecessor and successor.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def _nextGT(self, stack): """find node with smallest value > stack[-1].val.""" if stack: node = stack.pop() if node.right: node = node.right stack.append(node) while node.left: node = node.lef...
the_stack_v2_python_sparse
src/0200-0299/0285.inorder.successor.bst.py
gyang274/leetcode
train
1
a7a663ffedc2066df93d438dd8d6bc1ea365e704
[ "if graph.is_directed():\n raise ValueError('the graph is directed')\nself.graph = graph\nself.hamiltonian_cycle = self.graph.__class__(self.graph.v())\nfor node in self.graph.iternodes():\n self.hamiltonian_cycle.add_node(node)\nself._uf = UnionFind()\nself._pq = PriorityQueue()", "for node in self.graph.i...
<|body_start_0|> if graph.is_directed(): raise ValueError('the graph is directed') self.graph = graph self.hamiltonian_cycle = self.graph.__class__(self.graph.v()) for node in self.graph.iternodes(): self.hamiltonian_cycle.add_node(node) self._uf = UnionFi...
The sorted edge algorithm for TSP. Attributes ---------- graph : input weighted complete graph hamiltonian_cycle : cycle graph _uf : disjoint-set data structure, private _pq : priority queue, private
SortedEdgeTSPWithGraph
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SortedEdgeTSPWithGraph: """The sorted edge algorithm for TSP. Attributes ---------- graph : input weighted complete graph hamiltonian_cycle : cycle graph _uf : disjoint-set data structure, private _pq : priority queue, private""" def __init__(self, graph): """The algorithm initializa...
stack_v2_sparse_classes_36k_train_018290
5,106
permissive
[ { "docstring": "The algorithm initialization.", "name": "__init__", "signature": "def __init__(self, graph)" }, { "docstring": "Executable pseudocode.", "name": "run", "signature": "def run(self, source=None)" } ]
2
stack_v2_sparse_classes_30k_train_001680
Implement the Python class `SortedEdgeTSPWithGraph` described below. Class description: The sorted edge algorithm for TSP. Attributes ---------- graph : input weighted complete graph hamiltonian_cycle : cycle graph _uf : disjoint-set data structure, private _pq : priority queue, private Method signatures and docstrin...
Implement the Python class `SortedEdgeTSPWithGraph` described below. Class description: The sorted edge algorithm for TSP. Attributes ---------- graph : input weighted complete graph hamiltonian_cycle : cycle graph _uf : disjoint-set data structure, private _pq : priority queue, private Method signatures and docstrin...
0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60
<|skeleton|> class SortedEdgeTSPWithGraph: """The sorted edge algorithm for TSP. Attributes ---------- graph : input weighted complete graph hamiltonian_cycle : cycle graph _uf : disjoint-set data structure, private _pq : priority queue, private""" def __init__(self, graph): """The algorithm initializa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SortedEdgeTSPWithGraph: """The sorted edge algorithm for TSP. Attributes ---------- graph : input weighted complete graph hamiltonian_cycle : cycle graph _uf : disjoint-set data structure, private _pq : priority queue, private""" def __init__(self, graph): """The algorithm initialization.""" ...
the_stack_v2_python_sparse
graphtheory/hamiltonian/tspse.py
kgashok/graphs-dict
train
0
7e36bd0a93c1562ad212bf7e819cba0634f51dbe
[ "self.root = root\nself.image = image\nself.filename = self.imagery[image]\nself.transforms = transforms\nif download:\n self.__download(api_key)\nself.files = self._load_files(os.path.join(root, self.dataset_id))", "if os.path.exists(os.path.join(self.root, self.dataset_id, self.collections[0], 'collection.js...
<|body_start_0|> self.root = root self.image = image self.filename = self.imagery[image] self.transforms = transforms if download: self.__download(api_key) self.files = self._load_files(os.path.join(root, self.dataset_id)) <|end_body_0|> <|body_start_1|> ...
SpaceNet 6: Multi-Sensor All-Weather Mapping. `SpaceNet 6 <https://spacenet.ai/sn6-challenge/>`_ is a dataset of optical and SAR imagery over the city of Rotterdam. Collection features: +------------+---------------------+------------+-----------------------------+ | AOI | Area (km\\ :sup:`2`\\)| # Images | # Building ...
SpaceNet6
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpaceNet6: """SpaceNet 6: Multi-Sensor All-Weather Mapping. `SpaceNet 6 <https://spacenet.ai/sn6-challenge/>`_ is a dataset of optical and SAR imagery over the city of Rotterdam. Collection features: +------------+---------------------+------------+-----------------------------+ | AOI | Area (km\...
stack_v2_sparse_classes_36k_train_018291
45,367
permissive
[ { "docstring": "Initialize a new SpaceNet 6 Dataset instance. Args: root: root directory where dataset can be found image: image selection which must be in [\"PAN\", \"RGBNIR\", \"PS-RGB\", \"PS-RGBNIR\", \"SAR-Intensity\"] transforms: a function/transform that takes input sample and its target as entry and ret...
2
null
Implement the Python class `SpaceNet6` described below. Class description: SpaceNet 6: Multi-Sensor All-Weather Mapping. `SpaceNet 6 <https://spacenet.ai/sn6-challenge/>`_ is a dataset of optical and SAR imagery over the city of Rotterdam. Collection features: +------------+---------------------+------------+---------...
Implement the Python class `SpaceNet6` described below. Class description: SpaceNet 6: Multi-Sensor All-Weather Mapping. `SpaceNet 6 <https://spacenet.ai/sn6-challenge/>`_ is a dataset of optical and SAR imagery over the city of Rotterdam. Collection features: +------------+---------------------+------------+---------...
29985861614b3b93f9ef5389469ebb98570de7dd
<|skeleton|> class SpaceNet6: """SpaceNet 6: Multi-Sensor All-Weather Mapping. `SpaceNet 6 <https://spacenet.ai/sn6-challenge/>`_ is a dataset of optical and SAR imagery over the city of Rotterdam. Collection features: +------------+---------------------+------------+-----------------------------+ | AOI | Area (km\...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpaceNet6: """SpaceNet 6: Multi-Sensor All-Weather Mapping. `SpaceNet 6 <https://spacenet.ai/sn6-challenge/>`_ is a dataset of optical and SAR imagery over the city of Rotterdam. Collection features: +------------+---------------------+------------+-----------------------------+ | AOI | Area (km\\ :sup:`2`\\)...
the_stack_v2_python_sparse
torchgeo/datasets/spacenet.py
microsoft/torchgeo
train
1,724
1f756a73bc382f0648c514246878dbf34c35700b
[ "queryset = Like.objects.filter(sender=user, receiver_content_type=6).order_by('-timestamp')\ntotal = len(queryset)\nreturn {'title': '喜欢', 'data': [], 'total': total, 'nextpage': 0, 'category': 'liking'}", "queryset = Video.objects.filter(user=user).order_by('-upload_time')\ncount = len(queryset)\nlist = queryse...
<|body_start_0|> queryset = Like.objects.filter(sender=user, receiver_content_type=6).order_by('-timestamp') total = len(queryset) return {'title': '喜欢', 'data': [], 'total': total, 'nextpage': 0, 'category': 'liking'} <|end_body_0|> <|body_start_1|> queryset = Video.objects.filter(user...
UserHomeSerializer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserHomeSerializer: def get_liking(self, user): """请求用户喜欢的视频, 这里不返回视频数据,只返回视频数量 :param user: :return:""" <|body_0|> def get_videos(self, user): """请求用户发布的视频, 最多返回前20条 :param user: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> queryset = L...
stack_v2_sparse_classes_36k_train_018292
2,802
permissive
[ { "docstring": "请求用户喜欢的视频, 这里不返回视频数据,只返回视频数量 :param user: :return:", "name": "get_liking", "signature": "def get_liking(self, user)" }, { "docstring": "请求用户发布的视频, 最多返回前20条 :param user: :return:", "name": "get_videos", "signature": "def get_videos(self, user)" } ]
2
stack_v2_sparse_classes_30k_train_016347
Implement the Python class `UserHomeSerializer` described below. Class description: Implement the UserHomeSerializer class. Method signatures and docstrings: - def get_liking(self, user): 请求用户喜欢的视频, 这里不返回视频数据,只返回视频数量 :param user: :return: - def get_videos(self, user): 请求用户发布的视频, 最多返回前20条 :param user: :return:
Implement the Python class `UserHomeSerializer` described below. Class description: Implement the UserHomeSerializer class. Method signatures and docstrings: - def get_liking(self, user): 请求用户喜欢的视频, 这里不返回视频数据,只返回视频数量 :param user: :return: - def get_videos(self, user): 请求用户发布的视频, 最多返回前20条 :param user: :return: <|skel...
fb64440ec7f84f08cf9cd706bec374fa357d7936
<|skeleton|> class UserHomeSerializer: def get_liking(self, user): """请求用户喜欢的视频, 这里不返回视频数据,只返回视频数量 :param user: :return:""" <|body_0|> def get_videos(self, user): """请求用户发布的视频, 最多返回前20条 :param user: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserHomeSerializer: def get_liking(self, user): """请求用户喜欢的视频, 这里不返回视频数据,只返回视频数量 :param user: :return:""" queryset = Like.objects.filter(sender=user, receiver_content_type=6).order_by('-timestamp') total = len(queryset) return {'title': '喜欢', 'data': [], 'total': total, 'nextpag...
the_stack_v2_python_sparse
apps/user_operation/serializers.py
tuxi/video-hub
train
18
13193787a4c772bd897f3c182ed349a5a7d8818a
[ "try:\n self._dao.execute('DELETE FROM Hobby WHERE id = %s AND scheme_id = %s;', (hobby_id, scheme_id))\n succ = self._dao.rowcount()\n self._dao.commit()\n return succ\nexcept Exception as e:\n self._log.exception('Could not delete the hobby')\n raise e", "try:\n self._dao.execute('INSERT IN...
<|body_start_0|> try: self._dao.execute('DELETE FROM Hobby WHERE id = %s AND scheme_id = %s;', (hobby_id, scheme_id)) succ = self._dao.rowcount() self._dao.commit() return succ except Exception as e: self._log.exception('Could not delete the ho...
HobbyModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HobbyModel: def delete_hobby(self, scheme_id, hobby_id): """Given the hobby_id will delete the hobby""" <|body_0|> def insert_hobby(self, scheme_id, hobby): """Will insert an entry for a hobby into the database""" <|body_1|> def select_hobby(self, scheme...
stack_v2_sparse_classes_36k_train_018293
1,612
no_license
[ { "docstring": "Given the hobby_id will delete the hobby", "name": "delete_hobby", "signature": "def delete_hobby(self, scheme_id, hobby_id)" }, { "docstring": "Will insert an entry for a hobby into the database", "name": "insert_hobby", "signature": "def insert_hobby(self, scheme_id, ho...
4
stack_v2_sparse_classes_30k_val_000147
Implement the Python class `HobbyModel` described below. Class description: Implement the HobbyModel class. Method signatures and docstrings: - def delete_hobby(self, scheme_id, hobby_id): Given the hobby_id will delete the hobby - def insert_hobby(self, scheme_id, hobby): Will insert an entry for a hobby into the da...
Implement the Python class `HobbyModel` described below. Class description: Implement the HobbyModel class. Method signatures and docstrings: - def delete_hobby(self, scheme_id, hobby_id): Given the hobby_id will delete the hobby - def insert_hobby(self, scheme_id, hobby): Will insert an entry for a hobby into the da...
649a3c1cdcc90443f9561dfa1262ae3b0e970729
<|skeleton|> class HobbyModel: def delete_hobby(self, scheme_id, hobby_id): """Given the hobby_id will delete the hobby""" <|body_0|> def insert_hobby(self, scheme_id, hobby): """Will insert an entry for a hobby into the database""" <|body_1|> def select_hobby(self, scheme...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HobbyModel: def delete_hobby(self, scheme_id, hobby_id): """Given the hobby_id will delete the hobby""" try: self._dao.execute('DELETE FROM Hobby WHERE id = %s AND scheme_id = %s;', (hobby_id, scheme_id)) succ = self._dao.rowcount() self._dao.commit() ...
the_stack_v2_python_sparse
flaskr/models/hobbymdl.py
nickpezzotti1/BuddySchemeWebApp
train
2
fa6949e1b87fd23c469e0ab92f31e23fc0f6bf43
[ "layer_db = LayerDatabase(model)\nuse_cuda = False\npruner = SpatialSvdPruner()\ncost_calculator = SpatialSvdCostCalculator()\ncomp_ratio_rounding_algo = RankRounder(params.multiplicity, cost_calculator)\nif params.mode == SpatialSvdParameters.Mode.auto:\n greedy_params = params.mode_params.greedy_params\n co...
<|body_start_0|> layer_db = LayerDatabase(model) use_cuda = False pruner = SpatialSvdPruner() cost_calculator = SpatialSvdCostCalculator() comp_ratio_rounding_algo = RankRounder(params.multiplicity, cost_calculator) if params.mode == SpatialSvdParameters.Mode.auto: ...
Factory to construct various aimet model compression classes based on a scheme
CompressionFactory
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompressionFactory: """Factory to construct various aimet model compression classes based on a scheme""" def create_spatial_svd_algo(cls, model: tf.keras.Model, eval_callback: EvalFunction, eval_iterations: int, cost_metric: CostMetric, params: SpatialSvdParameters, bokeh_session: BokehServe...
stack_v2_sparse_classes_36k_train_018294
7,032
permissive
[ { "docstring": "Factory method to construct SpatialSvdCompressionAlgo :param model: Keras model to compress :param eval_callback: Evaluation callback for the model :param eval_iterations: Evaluation iterations :param cost_metric: Cost metric (mac or memory) :param params: Spatial SVD compression parameters :par...
2
stack_v2_sparse_classes_30k_train_016673
Implement the Python class `CompressionFactory` described below. Class description: Factory to construct various aimet model compression classes based on a scheme Method signatures and docstrings: - def create_spatial_svd_algo(cls, model: tf.keras.Model, eval_callback: EvalFunction, eval_iterations: int, cost_metric:...
Implement the Python class `CompressionFactory` described below. Class description: Factory to construct various aimet model compression classes based on a scheme Method signatures and docstrings: - def create_spatial_svd_algo(cls, model: tf.keras.Model, eval_callback: EvalFunction, eval_iterations: int, cost_metric:...
5a406e657082b6a4f6e4bf48f0e46e085cb1e351
<|skeleton|> class CompressionFactory: """Factory to construct various aimet model compression classes based on a scheme""" def create_spatial_svd_algo(cls, model: tf.keras.Model, eval_callback: EvalFunction, eval_iterations: int, cost_metric: CostMetric, params: SpatialSvdParameters, bokeh_session: BokehServe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CompressionFactory: """Factory to construct various aimet model compression classes based on a scheme""" def create_spatial_svd_algo(cls, model: tf.keras.Model, eval_callback: EvalFunction, eval_iterations: int, cost_metric: CostMetric, params: SpatialSvdParameters, bokeh_session: BokehServerSession=None...
the_stack_v2_python_sparse
TrainingExtensions/tensorflow/src/python/aimet_tensorflow/keras/compression_factory.py
quic/aimet
train
1,676
17148629a1a715097c551f0e78b2141c82ffdcd1
[ "query = DuesPayment.query.filter_by(user_id=user.id)\nif not include_void:\n query = query.filter_by(void=False)\ndues_payments = query.all()\nif not include_exceptional:\n dues_payments = filter(lambda p: p.exception is None, dues_payments)\nif not include_invisible:\n dues_payments = filter(lambda p: p....
<|body_start_0|> query = DuesPayment.query.filter_by(user_id=user.id) if not include_void: query = query.filter_by(void=False) dues_payments = query.all() if not include_exceptional: dues_payments = filter(lambda p: p.exception is None, dues_payments) if n...
Provides high-level methods for managing member dues.
DuesService
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DuesService: """Provides high-level methods for managing member dues.""" def get_dues_payments(self, user, include_void=False, include_exceptional=False, include_invisible=False): """Get all dues payments made by a user. :param user: the user to search for dues payments from :param i...
stack_v2_sparse_classes_36k_train_018295
3,876
no_license
[ { "docstring": "Get all dues payments made by a user. :param user: the user to search for dues payments from :param include_void: if True payments marked as void will be included in the results, if False they will not :param include_exceptional: if True payments with a non-None exceptional property will be incl...
2
stack_v2_sparse_classes_30k_train_010752
Implement the Python class `DuesService` described below. Class description: Provides high-level methods for managing member dues. Method signatures and docstrings: - def get_dues_payments(self, user, include_void=False, include_exceptional=False, include_invisible=False): Get all dues payments made by a user. :param...
Implement the Python class `DuesService` described below. Class description: Provides high-level methods for managing member dues. Method signatures and docstrings: - def get_dues_payments(self, user, include_void=False, include_exceptional=False, include_invisible=False): Get all dues payments made by a user. :param...
28cf2be6986045d68f12a647808b6c7a3446a50e
<|skeleton|> class DuesService: """Provides high-level methods for managing member dues.""" def get_dues_payments(self, user, include_void=False, include_exceptional=False, include_invisible=False): """Get all dues payments made by a user. :param user: the user to search for dues payments from :param i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DuesService: """Provides high-level methods for managing member dues.""" def get_dues_payments(self, user, include_void=False, include_exceptional=False, include_invisible=False): """Get all dues payments made by a user. :param user: the user to search for dues payments from :param include_void: ...
the_stack_v2_python_sparse
dismember/dues.py
splatspace/dismember
train
2
79d49aea9d87b6460e6df937a2e497fe637e2e91
[ "if request.user.has_perm(CHANGE_TEAM):\n user = UserProfile.objects.get(pk=request.data['id_user'])\n team = Team.objects.get(pk=request.data['id_team'])\n team.user_set.add(user)\n logger.info('{user} ADDED {member} to {team}'.format(user=request.user, member=repr(user), team=repr(team)))\n return ...
<|body_start_0|> if request.user.has_perm(CHANGE_TEAM): user = UserProfile.objects.get(pk=request.data['id_user']) team = Team.objects.get(pk=request.data['id_team']) team.user_set.add(user) logger.info('{user} ADDED {member} to {team}'.format(user=request.user, m...
# Add and remove users from team. Parameters : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. POST request : add a user to a team and send HTTP 201, must contain id_user (the id of the user to add, int) and id_team (the id of the team where the user will be ad...
AddUserToTeam
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddUserToTeam: """# Add and remove users from team. Parameters : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. POST request : add a user to a team and send HTTP 201, must contain id_user (the id of the user to add, int) and id_team (the...
stack_v2_sparse_classes_36k_train_018296
10,635
permissive
[ { "docstring": "Implement the POST method. ``` Parameters : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. POST request : add a user to a team and send HTTP 201, must contain id_user (the id of the user to add, int) and id_team (the id of the team wher...
2
stack_v2_sparse_classes_30k_train_008919
Implement the Python class `AddUserToTeam` described below. Class description: # Add and remove users from team. Parameters : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. POST request : add a user to a team and send HTTP 201, must contain id_user (the id of...
Implement the Python class `AddUserToTeam` described below. Class description: # Add and remove users from team. Parameters : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. POST request : add a user to a team and send HTTP 201, must contain id_user (the id of...
56511ebac83a5dc1fb8768a98bc675e88530a447
<|skeleton|> class AddUserToTeam: """# Add and remove users from team. Parameters : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. POST request : add a user to a team and send HTTP 201, must contain id_user (the id of the user to add, int) and id_team (the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AddUserToTeam: """# Add and remove users from team. Parameters : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. POST request : add a user to a team and send HTTP 201, must contain id_user (the id of the user to add, int) and id_team (the id of the te...
the_stack_v2_python_sparse
usersmanagement/views/views_team.py
Open-CMMS/openCMMS_backend
train
4
a9c58b23c11564becd9e282401af5923ff01a27b
[ "l = 0\nnode = head\nwhile node:\n node = node.next\n l += 1\n\ndef reverse(node):\n pre = None\n while node:\n pre, node.next, node = (node, pre, node.next)\n return pre\ni = l // 2\nnode = head\nwhile i > 0:\n node = node.next\n i -= 1\nnode = reverse(node)\nwhile node:\n if node.va...
<|body_start_0|> l = 0 node = head while node: node = node.next l += 1 def reverse(node): pre = None while node: pre, node.next, node = (node, pre, node.next) return pre i = l // 2 node = head ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindrome(self, head: Optional[ListNode]) -> bool: """2022-08-23 Runtime: 947 ms, faster than 78.82% Memory Usage: 39 MB, less than 76.71% The number of nodes in the list is in the range [1, 10^5]. 0 <= Node.val <= 9""" <|body_0|> def isPalindrome2(self, hea...
stack_v2_sparse_classes_36k_train_018297
3,203
permissive
[ { "docstring": "2022-08-23 Runtime: 947 ms, faster than 78.82% Memory Usage: 39 MB, less than 76.71% The number of nodes in the list is in the range [1, 10^5]. 0 <= Node.val <= 9", "name": "isPalindrome", "signature": "def isPalindrome(self, head: Optional[ListNode]) -> bool" }, { "docstring": "...
2
stack_v2_sparse_classes_30k_train_015839
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, head: Optional[ListNode]) -> bool: 2022-08-23 Runtime: 947 ms, faster than 78.82% Memory Usage: 39 MB, less than 76.71% The number of nodes in the list is ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, head: Optional[ListNode]) -> bool: 2022-08-23 Runtime: 947 ms, faster than 78.82% Memory Usage: 39 MB, less than 76.71% The number of nodes in the list is ...
4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5
<|skeleton|> class Solution: def isPalindrome(self, head: Optional[ListNode]) -> bool: """2022-08-23 Runtime: 947 ms, faster than 78.82% Memory Usage: 39 MB, less than 76.71% The number of nodes in the list is in the range [1, 10^5]. 0 <= Node.val <= 9""" <|body_0|> def isPalindrome2(self, hea...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPalindrome(self, head: Optional[ListNode]) -> bool: """2022-08-23 Runtime: 947 ms, faster than 78.82% Memory Usage: 39 MB, less than 76.71% The number of nodes in the list is in the range [1, 10^5]. 0 <= Node.val <= 9""" l = 0 node = head while node: ...
the_stack_v2_python_sparse
src/234-PalindromeLinkedList.py
Jiezhi/myleetcode
train
1
8bfeeabea7242fe99e897eb2f6d09239aacf8dd6
[ "args = self.validate_input(args)\nvargs = vars(args)\nIS = vargs.pop('IS')\nGF = vargs.pop('gene_file')\nlogging.debug('Loading genes')\nscaff_2_gene_database, scaff2gene2sequence = parse_genes(GF, **vargs)\nGdbP = pd.concat([x for x in scaff_2_gene_database.values()])\nname2result = calculate_gene_metrics(IS, Gdb...
<|body_start_0|> args = self.validate_input(args) vargs = vars(args) IS = vargs.pop('IS') GF = vargs.pop('gene_file') logging.debug('Loading genes') scaff_2_gene_database, scaff2gene2sequence = parse_genes(GF, **vargs) GdbP = pd.concat([x for x in scaff_2_gene_dat...
The command line access point to the program
Controller
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Controller: """The command line access point to the program""" def main(self, args): """The main method when run on the command line""" <|body_0|> def validate_input(self, args): """Validate and mess with the arguments a bit""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k_train_018298
31,954
permissive
[ { "docstring": "The main method when run on the command line", "name": "main", "signature": "def main(self, args)" }, { "docstring": "Validate and mess with the arguments a bit", "name": "validate_input", "signature": "def validate_input(self, args)" } ]
2
stack_v2_sparse_classes_30k_train_014217
Implement the Python class `Controller` described below. Class description: The command line access point to the program Method signatures and docstrings: - def main(self, args): The main method when run on the command line - def validate_input(self, args): Validate and mess with the arguments a bit
Implement the Python class `Controller` described below. Class description: The command line access point to the program Method signatures and docstrings: - def main(self, args): The main method when run on the command line - def validate_input(self, args): Validate and mess with the arguments a bit <|skeleton|> cla...
748ef37f1e3449e290f4b5eb574f6d0a3404daba
<|skeleton|> class Controller: """The command line access point to the program""" def main(self, args): """The main method when run on the command line""" <|body_0|> def validate_input(self, args): """Validate and mess with the arguments a bit""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Controller: """The command line access point to the program""" def main(self, args): """The main method when run on the command line""" args = self.validate_input(args) vargs = vars(args) IS = vargs.pop('IS') GF = vargs.pop('gene_file') logging.debug('Loadi...
the_stack_v2_python_sparse
inStrain/GeneProfile.py
MrOlm/inStrain
train
103
b36de3369a3742eea67c70d68adb72794fc78a7f
[ "self._device = device\nself._attr_unique_id = device.serial_number\nself._attr_device_info = DeviceInfo(identifiers={(KALEIDESCAPE_DOMAIN, self._device.serial_number)}, name=f'{KALEIDESCAPE_NAME} {device.system.friendly_name}', model=self._device.system.type, manufacturer=KALEIDESCAPE_NAME, sw_version=f'{self._dev...
<|body_start_0|> self._device = device self._attr_unique_id = device.serial_number self._attr_device_info = DeviceInfo(identifiers={(KALEIDESCAPE_DOMAIN, self._device.serial_number)}, name=f'{KALEIDESCAPE_NAME} {device.system.friendly_name}', model=self._device.system.type, manufacturer=KALEIDES...
Defines a base Kaleidescape entity.
KaleidescapeEntity
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KaleidescapeEntity: """Defines a base Kaleidescape entity.""" def __init__(self, device: KaleidescapeDevice) -> None: """Initialize entity.""" <|body_0|> async def async_added_to_hass(self) -> None: """Register update listener.""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_36k_train_018299
1,702
permissive
[ { "docstring": "Initialize entity.", "name": "__init__", "signature": "def __init__(self, device: KaleidescapeDevice) -> None" }, { "docstring": "Register update listener.", "name": "async_added_to_hass", "signature": "async def async_added_to_hass(self) -> None" } ]
2
null
Implement the Python class `KaleidescapeEntity` described below. Class description: Defines a base Kaleidescape entity. Method signatures and docstrings: - def __init__(self, device: KaleidescapeDevice) -> None: Initialize entity. - async def async_added_to_hass(self) -> None: Register update listener.
Implement the Python class `KaleidescapeEntity` described below. Class description: Defines a base Kaleidescape entity. Method signatures and docstrings: - def __init__(self, device: KaleidescapeDevice) -> None: Initialize entity. - async def async_added_to_hass(self) -> None: Register update listener. <|skeleton|> ...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class KaleidescapeEntity: """Defines a base Kaleidescape entity.""" def __init__(self, device: KaleidescapeDevice) -> None: """Initialize entity.""" <|body_0|> async def async_added_to_hass(self) -> None: """Register update listener.""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KaleidescapeEntity: """Defines a base Kaleidescape entity.""" def __init__(self, device: KaleidescapeDevice) -> None: """Initialize entity.""" self._device = device self._attr_unique_id = device.serial_number self._attr_device_info = DeviceInfo(identifiers={(KALEIDESCAPE_D...
the_stack_v2_python_sparse
homeassistant/components/kaleidescape/entity.py
home-assistant/core
train
35,501