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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ccf3af20cd23a4c8f9191343ebbd66f232e64e2c | [
"exit_num = len(cls._list_of_item_types) + 1\nvalid_choice_list = [exit_num]\ncls._print_menu(valid_choice_list)\nprint(f'{exit_num}. Return')\nint_input = cls._get_valid_user_input(valid_choice_list)\nif int_input != exit_num:\n item_type = cls._list_of_item_types[int_input - 1]\n print('item type: ' + item_... | <|body_start_0|>
exit_num = len(cls._list_of_item_types) + 1
valid_choice_list = [exit_num]
cls._print_menu(valid_choice_list)
print(f'{exit_num}. Return')
int_input = cls._get_valid_user_input(valid_choice_list)
if int_input != exit_num:
item_type = cls._list... | LibraryItemGenerator prompts user with an UI to select the type of library they want, and then add that item. Used as a static class by Catalogue. It contains Classes of Book, DVD, and Journals, but not instances of them. It also generates dummy data for the Library. | LibraryItemGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryItemGenerator:
"""LibraryItemGenerator prompts user with an UI to select the type of library they want, and then add that item. Used as a static class by Catalogue. It contains Classes of Book, DVD, and Journals, but not instances of them. It also generates dummy data for the Library."""
... | stack_v2_sparse_classes_36k_train_028700 | 3,887 | no_license | [
{
"docstring": "Add a LibraryItem based on user's choice. Uses the types in cls._list_of_item_types. :param call_num: a string :precondition call_number: a unique identifier :return: a type of LibraryItem",
"name": "add_item",
"signature": "def add_item(cls, call_num)"
},
{
"docstring": "Helper ... | 4 | stack_v2_sparse_classes_30k_train_006496 | Implement the Python class `LibraryItemGenerator` described below.
Class description:
LibraryItemGenerator prompts user with an UI to select the type of library they want, and then add that item. Used as a static class by Catalogue. It contains Classes of Book, DVD, and Journals, but not instances of them. It also gen... | Implement the Python class `LibraryItemGenerator` described below.
Class description:
LibraryItemGenerator prompts user with an UI to select the type of library they want, and then add that item. Used as a static class by Catalogue. It contains Classes of Book, DVD, and Journals, but not instances of them. It also gen... | 5fbc92a7ddd9103076a7095124b5ae108b002f03 | <|skeleton|>
class LibraryItemGenerator:
"""LibraryItemGenerator prompts user with an UI to select the type of library they want, and then add that item. Used as a static class by Catalogue. It contains Classes of Book, DVD, and Journals, but not instances of them. It also generates dummy data for the Library."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LibraryItemGenerator:
"""LibraryItemGenerator prompts user with an UI to select the type of library they want, and then add that item. Used as a static class by Catalogue. It contains Classes of Book, DVD, and Journals, but not instances of them. It also generates dummy data for the Library."""
def add_i... | the_stack_v2_python_sparse | Labs/Lab3/library_item_generator.py | pyopoly/3522_A00699267 | train | 0 |
f52957f572073650cf122021c25752587457ff7c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn FilterOperatorSchema()",
"from .attribute_type import AttributeType\nfrom .entity import Entity\nfrom .scope_operator_multi_valued_comparison_type import ScopeOperatorMultiValuedComparisonType\nfrom .scope_operator_type import ScopeOpe... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return FilterOperatorSchema()
<|end_body_0|>
<|body_start_1|>
from .attribute_type import AttributeType
from .entity import Entity
from .scope_operator_multi_valued_comparison_type impo... | FilterOperatorSchema | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterOperatorSchema:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema:
"""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_sparse_classes_36k_train_028701 | 3,425 | 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: FilterOperatorSchema",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | stack_v2_sparse_classes_30k_train_015152 | Implement the Python class `FilterOperatorSchema` described below.
Class description:
Implement the FilterOperatorSchema class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema: Creates a new instance of the appropriate class based o... | Implement the Python class `FilterOperatorSchema` described below.
Class description:
Implement the FilterOperatorSchema class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class FilterOperatorSchema:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema:
"""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_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterOperatorSchema:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/filter_operator_schema.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
78fdb9b5f521848b26e4def5942ee7f6c11d229e | [
"self.epsilon = epsilon\nself.n_iteration = n_iteration\nself.window = window\nself.tau = tau\nself.np_asset_prices = None\nsuper().__init__()",
"super()._initialize(asset_prices, weights, resample_by)\nif self.epsilon < 1:\n raise ValueError('Epsilon values must be greater than 1.')\nif not isinstance(self.n_... | <|body_start_0|>
self.epsilon = epsilon
self.n_iteration = n_iteration
self.window = window
self.tau = tau
self.np_asset_prices = None
super().__init__()
<|end_body_0|>
<|body_start_1|>
super()._initialize(asset_prices, weights, resample_by)
if self.epsil... | This class implements the Confidence Weighted Mean Reversion strategy. It is reproduced with modification from the following paper: `D. Huang, J. Zhou, B. Li, S. C. H. Hoi and S. Zhou, "Robust Median Reversion Strategy for Online Portfolio Selection," in IEEE Transactions on Knowledge and Data Engineering, vol. 28, no.... | RMR | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RMR:
"""This class implements the Confidence Weighted Mean Reversion strategy. It is reproduced with modification from the following paper: `D. Huang, J. Zhou, B. Li, S. C. H. Hoi and S. Zhou, "Robust Median Reversion Strategy for Online Portfolio Selection," in IEEE Transactions on Knowledge and... | stack_v2_sparse_classes_36k_train_028702 | 8,049 | permissive | [
{
"docstring": "Initializes Robust Median Reversion with the given epsilon, n_iteration, window, and tau values. :param epsilon: (float) Reversion threshold with range [1, inf). Values of [15, 25] had the highest returns for the original dataset provided by the authors. :param n_iteration: (int) Maximum number ... | 5 | stack_v2_sparse_classes_30k_train_002915 | Implement the Python class `RMR` described below.
Class description:
This class implements the Confidence Weighted Mean Reversion strategy. It is reproduced with modification from the following paper: `D. Huang, J. Zhou, B. Li, S. C. H. Hoi and S. Zhou, "Robust Median Reversion Strategy for Online Portfolio Selection,... | Implement the Python class `RMR` described below.
Class description:
This class implements the Confidence Weighted Mean Reversion strategy. It is reproduced with modification from the following paper: `D. Huang, J. Zhou, B. Li, S. C. H. Hoi and S. Zhou, "Robust Median Reversion Strategy for Online Portfolio Selection,... | 046c47d995da08b1003bba3f9c07d5bfb73d9c1f | <|skeleton|>
class RMR:
"""This class implements the Confidence Weighted Mean Reversion strategy. It is reproduced with modification from the following paper: `D. Huang, J. Zhou, B. Li, S. C. H. Hoi and S. Zhou, "Robust Median Reversion Strategy for Online Portfolio Selection," in IEEE Transactions on Knowledge and... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RMR:
"""This class implements the Confidence Weighted Mean Reversion strategy. It is reproduced with modification from the following paper: `D. Huang, J. Zhou, B. Li, S. C. H. Hoi and S. Zhou, "Robust Median Reversion Strategy for Online Portfolio Selection," in IEEE Transactions on Knowledge and Data Enginee... | the_stack_v2_python_sparse | src/collection/portfoliolab/online_portfolio_selection/rmr.py | Ta-nu-ki/dissertacao | train | 0 |
3ae8f4497a46691adefeaf6f67a5cbd1d1491ace | [
"x = input_dict[node.inputs[0]]\nind = input_dict[node.inputs[1]]\nif len(node.inputs) > 2:\n output_shape = input_dict.get(node.inputs[2], None)\nelse:\n output_shape = None\nkernel_shape = node.attrs['kernel_shape']\nspatial_size = len(kernel_shape)\nx_rank = spatial_size + 2\nstorage_format, _ = get_data_f... | <|body_start_0|>
x = input_dict[node.inputs[0]]
ind = input_dict[node.inputs[1]]
if len(node.inputs) > 2:
output_shape = input_dict.get(node.inputs[2], None)
else:
output_shape = None
kernel_shape = node.attrs['kernel_shape']
spatial_size = len(ker... | UnpoolMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnpoolMixin:
def max_unpool(cls, node, input_dict):
"""MaxUnpooling operation"""
<|body_0|>
def _get_default_shape(cls, input_shape, kernel_shape, strides):
"""Calculates default shape from kernel_shape and strides Args: input_shape: shape of the input to unpool op k... | stack_v2_sparse_classes_36k_train_028703 | 5,295 | permissive | [
{
"docstring": "MaxUnpooling operation",
"name": "max_unpool",
"signature": "def max_unpool(cls, node, input_dict)"
},
{
"docstring": "Calculates default shape from kernel_shape and strides Args: input_shape: shape of the input to unpool op kernel_shape: the size of the kernel along each axis ou... | 5 | stack_v2_sparse_classes_30k_train_007494 | Implement the Python class `UnpoolMixin` described below.
Class description:
Implement the UnpoolMixin class.
Method signatures and docstrings:
- def max_unpool(cls, node, input_dict): MaxUnpooling operation
- def _get_default_shape(cls, input_shape, kernel_shape, strides): Calculates default shape from kernel_shape ... | Implement the Python class `UnpoolMixin` described below.
Class description:
Implement the UnpoolMixin class.
Method signatures and docstrings:
- def max_unpool(cls, node, input_dict): MaxUnpooling operation
- def _get_default_shape(cls, input_shape, kernel_shape, strides): Calculates default shape from kernel_shape ... | 44c09275a803e04eeeb4e0d24c372adf1f9ff1f5 | <|skeleton|>
class UnpoolMixin:
def max_unpool(cls, node, input_dict):
"""MaxUnpooling operation"""
<|body_0|>
def _get_default_shape(cls, input_shape, kernel_shape, strides):
"""Calculates default shape from kernel_shape and strides Args: input_shape: shape of the input to unpool op k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnpoolMixin:
def max_unpool(cls, node, input_dict):
"""MaxUnpooling operation"""
x = input_dict[node.inputs[0]]
ind = input_dict[node.inputs[1]]
if len(node.inputs) > 2:
output_shape = input_dict.get(node.inputs[2], None)
else:
output_shape = Non... | the_stack_v2_python_sparse | onnx_tf/handlers/backend/unpool_mixin.py | sdmonov/onnx-tensorflow | train | 3 | |
a8a3ac9f37c0e38c8014e2c9316a7b3033b47357 | [
"n, res = (len(nums1), 1)\ndp = [1, 1]\nfor i in range(1, n):\n ndp = [1, 1]\n for pre in range(2):\n preNums = nums1 if pre == 0 else nums2\n for cur in range(2):\n curNums = nums1 if cur == 0 else nums2\n if preNums[i - 1] <= curNums[i]:\n ndp[cur] = max(nd... | <|body_start_0|>
n, res = (len(nums1), 1)
dp = [1, 1]
for i in range(1, n):
ndp = [1, 1]
for pre in range(2):
preNums = nums1 if pre == 0 else nums2
for cur in range(2):
curNums = nums1 if cur == 0 else nums2
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:
"""两个数组选数,使得最长非递减`子数组`最长."""
<|body_0|>
def maxNonDecreasingLength2(self, nums1: List[int], nums2: List[int]) -> int:
"""两个数组选数,使得最长非递减`子序列`最长->LIS."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_028704 | 1,361 | no_license | [
{
"docstring": "两个数组选数,使得最长非递减`子数组`最长.",
"name": "maxNonDecreasingLength",
"signature": "def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int"
},
{
"docstring": "两个数组选数,使得最长非递减`子序列`最长->LIS.",
"name": "maxNonDecreasingLength2",
"signature": "def maxNonDecreasingLeng... | 2 | stack_v2_sparse_classes_30k_train_020533 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int: 两个数组选数,使得最长非递减`子数组`最长.
- def maxNonDecreasingLength2(self, nums1: List[int], nums2: List[int]) -> int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int: 两个数组选数,使得最长非递减`子数组`最长.
- def maxNonDecreasingLength2(self, nums1: List[int], nums2: List[int]) -> int... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:
"""两个数组选数,使得最长非递减`子数组`最长."""
<|body_0|>
def maxNonDecreasingLength2(self, nums1: List[int], nums2: List[int]) -> int:
"""两个数组选数,使得最长非递减`子序列`最长->LIS."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:
"""两个数组选数,使得最长非递减`子数组`最长."""
n, res = (len(nums1), 1)
dp = [1, 1]
for i in range(1, n):
ndp = [1, 1]
for pre in range(2):
preNums = nums1 if pre == 0 e... | the_stack_v2_python_sparse | 11_动态规划/lis最长上升子序列问题/6912. 构造最长非递减子数组.py | 981377660LMT/algorithm-study | train | 225 | |
db069a7b4cf094dcac0b953a89514df4803722bd | [
"a = [x for x in sys_stdin]\na = [self.cast(x.strip()) for x in a[0].strip('[]\\n').split(',')]\no = TreeNode().convert(a)\nreturn o",
"if x.lower() == 'null':\n return None\nelse:\n return int(x)"
] | <|body_start_0|>
a = [x for x in sys_stdin]
a = [self.cast(x.strip()) for x in a[0].strip('[]\n').split(',')]
o = TreeNode().convert(a)
return o
<|end_body_0|>
<|body_start_1|>
if x.lower() == 'null':
return None
else:
return int(x)
<|end_body_1|>... | Input | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head node of binary tree :rtype: TreeNode"""
<|body_0|>
def cast(self, x):
"""Converts string values to integer or None values. :param str x: str... | stack_v2_sparse_classes_36k_train_028705 | 2,141 | permissive | [
{
"docstring": "Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head node of binary tree :rtype: TreeNode",
"name": "stdin",
"signature": "def stdin(self, sys_stdin)"
},
{
"docstring": "Converts string values to integer or None values. :param str x: string inp... | 2 | stack_v2_sparse_classes_30k_train_020054 | Implement the Python class `Input` described below.
Class description:
Implement the Input class.
Method signatures and docstrings:
- def stdin(self, sys_stdin): Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head node of binary tree :rtype: TreeNode
- def cast(self, x): Converts ... | Implement the Python class `Input` described below.
Class description:
Implement the Input class.
Method signatures and docstrings:
- def stdin(self, sys_stdin): Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head node of binary tree :rtype: TreeNode
- def cast(self, x): Converts ... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head node of binary tree :rtype: TreeNode"""
<|body_0|>
def cast(self, x):
"""Converts string values to integer or None values. :param str x: str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head node of binary tree :rtype: TreeNode"""
a = [x for x in sys_stdin]
a = [self.cast(x.strip()) for x in a[0].strip('[]\n').split(',')]
o = TreeNode().con... | the_stack_v2_python_sparse | 0144_binary_tree_preorder_traversal/python_source.py | arthurdysart/LeetCode | train | 0 | |
1e16de79c2224c0c8fdae883716abac4af74005d | [
"self.cassandra_additional_info = cassandra_additional_info\nself.finalise_restore_task_id = finalise_restore_task_id\nself.graph_handling_enabled = graph_handling_enabled\nself.is_finalise_phase = is_finalise_phase\nself.log_recover_params = log_recover_params\nself.log_restore_directory = log_restore_directory\ns... | <|body_start_0|>
self.cassandra_additional_info = cassandra_additional_info
self.finalise_restore_task_id = finalise_restore_task_id
self.graph_handling_enabled = graph_handling_enabled
self.is_finalise_phase = is_finalise_phase
self.log_recover_params = log_recover_params
... | Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters required for Cassandra recovery. TODO (faizan.khan) : Remove this. finalise_restore_task_id... | CassandraRecoverJobParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CassandraRecoverJobParams:
"""Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters required for Cassandra recovery. TODO ... | stack_v2_sparse_classes_36k_train_028706 | 6,191 | permissive | [
{
"docstring": "Constructor for the CassandraRecoverJobParams class",
"name": "__init__",
"signature": "def __init__(self, cassandra_additional_info=None, finalise_restore_task_id=None, graph_handling_enabled=None, is_finalise_phase=None, log_recover_params=None, log_restore_directory=None, restart_allo... | 2 | stack_v2_sparse_classes_30k_train_021204 | Implement the Python class `CassandraRecoverJobParams` described below.
Class description:
Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters... | Implement the Python class `CassandraRecoverJobParams` described below.
Class description:
Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CassandraRecoverJobParams:
"""Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters required for Cassandra recovery. TODO ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CassandraRecoverJobParams:
"""Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters required for Cassandra recovery. TODO (faizan.khan)... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cassandra_recover_job_params.py | cohesity/management-sdk-python | train | 24 |
bb7ad01f63b2f8f23c7c17604d95e1e2f8433b64 | [
"k = k % len(nums)\nfor _ in range(k):\n nums.insert(0, nums.pop())",
"k = k % len(nums)\nfor _ in range(k):\n l = nums[-1]\n for i in range(len(nums) - 1, 0, -1):\n nums[i], nums[i - 1] = (nums[i - 1], nums[i])\n nums[0] = l",
"k = k % len(nums)\nif not k:\n return\nns = (nums * 2)[len(nu... | <|body_start_0|>
k = k % len(nums)
for _ in range(k):
nums.insert(0, nums.pop())
<|end_body_0|>
<|body_start_1|>
k = k % len(nums)
for _ in range(k):
l = nums[-1]
for i in range(len(nums) - 1, 0, -1):
nums[i], nums[i - 1] = (nums[i - 1... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def __rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: None Do not return anything, modify... | stack_v2_sparse_classes_36k_train_028707 | 2,129 | permissive | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead.",
"name": "_rotate",
"signature": "def _rotate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place ins... | 3 | stack_v2_sparse_classes_30k_train_018301 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead.
- def __rotate(self, nums, k): :type nums: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead.
- def __rotate(self, nums, k): :type nums: List[... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def __rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: None Do not return anything, modify... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead."""
k = k % len(nums)
for _ in range(k):
nums.insert(0, nums.pop())
def __rotate(self, nums, k):
""":type nums: List[in... | the_stack_v2_python_sparse | 189.rotate-array.py | windard/leeeeee | train | 0 | |
43ce7d964ac347d59432be676d5564ecc5d2b8ff | [
"tags = set()\nxmp = file_to_dict(file_path)\nif 'http://www.digikam.org/ns/1.0/' in xmp:\n for tag_section in xmp['http://www.digikam.org/ns/1.0/']:\n if len(tag_section) == 0:\n continue\n tag = tag_section[1]\n if tag != '':\n tags.add(tag)\nreturn tags",
"if os.pa... | <|body_start_0|>
tags = set()
xmp = file_to_dict(file_path)
if 'http://www.digikam.org/ns/1.0/' in xmp:
for tag_section in xmp['http://www.digikam.org/ns/1.0/']:
if len(tag_section) == 0:
continue
tag = tag_section[1]
... | XmpUtils | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XmpUtils:
def read_tags(file_path: str) -> Set[str]:
"""Reads tags from an XMP file (only Digikam tags) :param file_path: File where to read the tags from :return: Set of tags"""
<|body_0|>
def generate_xmp(output_file: str, tags: Set[str]) -> None:
"""Generates a ne... | stack_v2_sparse_classes_36k_train_028708 | 2,522 | permissive | [
{
"docstring": "Reads tags from an XMP file (only Digikam tags) :param file_path: File where to read the tags from :return: Set of tags",
"name": "read_tags",
"signature": "def read_tags(file_path: str) -> Set[str]"
},
{
"docstring": "Generates a new XMP file with the set of tags. Only for Digik... | 2 | null | Implement the Python class `XmpUtils` described below.
Class description:
Implement the XmpUtils class.
Method signatures and docstrings:
- def read_tags(file_path: str) -> Set[str]: Reads tags from an XMP file (only Digikam tags) :param file_path: File where to read the tags from :return: Set of tags
- def generate_... | Implement the Python class `XmpUtils` described below.
Class description:
Implement the XmpUtils class.
Method signatures and docstrings:
- def read_tags(file_path: str) -> Set[str]: Reads tags from an XMP file (only Digikam tags) :param file_path: File where to read the tags from :return: Set of tags
- def generate_... | 49798f5301c0facc6315b4a3e9613a51ada07583 | <|skeleton|>
class XmpUtils:
def read_tags(file_path: str) -> Set[str]:
"""Reads tags from an XMP file (only Digikam tags) :param file_path: File where to read the tags from :return: Set of tags"""
<|body_0|>
def generate_xmp(output_file: str, tags: Set[str]) -> None:
"""Generates a ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XmpUtils:
def read_tags(file_path: str) -> Set[str]:
"""Reads tags from an XMP file (only Digikam tags) :param file_path: File where to read the tags from :return: Set of tags"""
tags = set()
xmp = file_to_dict(file_path)
if 'http://www.digikam.org/ns/1.0/' in xmp:
... | the_stack_v2_python_sparse | SpiMediaGallery/main/xmp_utils.py | Swiss-Polar-Institute/spi-media-gallery | train | 6 | |
154e3101a35c09a58a2ecb29d044737f9b8eb980 | [
"super().__init__()\nif isinstance(video_path, Path):\n video_path = str(video_path.resolve())\nif not os.path.exists(video_path):\n raise ValueError(\"The specified video file doesn't exist.\")\nself.capture_device = cv2.VideoCapture(video_path)\nself.fps = self.capture_device.get(cv2.CAP_PROP_FPS)\nself.fra... | <|body_start_0|>
super().__init__()
if isinstance(video_path, Path):
video_path = str(video_path.resolve())
if not os.path.exists(video_path):
raise ValueError("The specified video file doesn't exist.")
self.capture_device = cv2.VideoCapture(video_path)
se... | Frame source for loading video files. | VideoFrameSource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoFrameSource:
"""Frame source for loading video files."""
def __init__(self, video_path: Union[str, Path]):
"""Parameters ---------- video_path : str or Path Path to the target video"""
<|body_0|>
def run(self) -> None:
"""Reads frames from `self.capture_devi... | stack_v2_sparse_classes_36k_train_028709 | 3,890 | permissive | [
{
"docstring": "Parameters ---------- video_path : str or Path Path to the target video",
"name": "__init__",
"signature": "def __init__(self, video_path: Union[str, Path])"
},
{
"docstring": "Reads frames from `self.capture_device` until thread join is requested. After reading each frame, waits... | 2 | stack_v2_sparse_classes_30k_train_000679 | Implement the Python class `VideoFrameSource` described below.
Class description:
Frame source for loading video files.
Method signatures and docstrings:
- def __init__(self, video_path: Union[str, Path]): Parameters ---------- video_path : str or Path Path to the target video
- def run(self) -> None: Reads frames fr... | Implement the Python class `VideoFrameSource` described below.
Class description:
Frame source for loading video files.
Method signatures and docstrings:
- def __init__(self, video_path: Union[str, Path]): Parameters ---------- video_path : str or Path Path to the target video
- def run(self) -> None: Reads frames fr... | a1c17fa53845648de31bf191f4c516ed13e654c9 | <|skeleton|>
class VideoFrameSource:
"""Frame source for loading video files."""
def __init__(self, video_path: Union[str, Path]):
"""Parameters ---------- video_path : str or Path Path to the target video"""
<|body_0|>
def run(self) -> None:
"""Reads frames from `self.capture_devi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VideoFrameSource:
"""Frame source for loading video files."""
def __init__(self, video_path: Union[str, Path]):
"""Parameters ---------- video_path : str or Path Path to the target video"""
super().__init__()
if isinstance(video_path, Path):
video_path = str(video_path... | the_stack_v2_python_sparse | src/frame_source.py | WiktorPieklik/Llama | train | 0 |
403ffb5ab3253633b53379f50780ec39dd120a40 | [
"self.parent = parent\nself.custom_channel_name = _qstring(parent.rhd)\nself.native_channel_name = _qstring(parent.rhd)\nself.native_order = np.int16(struct.unpack('h', parent.rhd.read(2)))[0]\nself.custom_order = np.int16(struct.unpack('h', parent.rhd.read(2)))[0]\nself.signal_type = np.int16(struct.unpack('h', pa... | <|body_start_0|>
self.parent = parent
self.custom_channel_name = _qstring(parent.rhd)
self.native_channel_name = _qstring(parent.rhd)
self.native_order = np.int16(struct.unpack('h', parent.rhd.read(2)))[0]
self.custom_order = np.int16(struct.unpack('h', parent.rhd.read(2)))[0]
... | Represents a single "Channel" and stores all revelent data | Channel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Channel:
"""Represents a single "Channel" and stores all revelent data"""
def __init__(self, parent):
"""Reads in and parses the next chunk of channel group data from the parent RHD instance creates a dict of chanel objects for the given signal group"""
<|body_0|>
def ge... | stack_v2_sparse_classes_36k_train_028710 | 12,179 | permissive | [
{
"docstring": "Reads in and parses the next chunk of channel group data from the parent RHD instance creates a dict of chanel objects for the given signal group",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "returns the raw trace of all data samples from this... | 2 | stack_v2_sparse_classes_30k_train_007355 | Implement the Python class `Channel` described below.
Class description:
Represents a single "Channel" and stores all revelent data
Method signatures and docstrings:
- def __init__(self, parent): Reads in and parses the next chunk of channel group data from the parent RHD instance creates a dict of chanel objects for... | Implement the Python class `Channel` described below.
Class description:
Represents a single "Channel" and stores all revelent data
Method signatures and docstrings:
- def __init__(self, parent): Reads in and parses the next chunk of channel group data from the parent RHD instance creates a dict of chanel objects for... | 0fdbe834442550117dc9d9c8f611989bb600db62 | <|skeleton|>
class Channel:
"""Represents a single "Channel" and stores all revelent data"""
def __init__(self, parent):
"""Reads in and parses the next chunk of channel group data from the parent RHD instance creates a dict of chanel objects for the given signal group"""
<|body_0|>
def ge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Channel:
"""Represents a single "Channel" and stores all revelent data"""
def __init__(self, parent):
"""Reads in and parses the next chunk of channel group data from the parent RHD instance creates a dict of chanel objects for the given signal group"""
self.parent = parent
self.c... | the_stack_v2_python_sparse | pyhfo/io/RHD.py | britodasilva/pyhfo | train | 4 |
fb6a4803b435aa60f879840400060d107c129cf5 | [
"self.storage.append(longUrl)\nn = len(self.storage)\nn <<= 1\ns = ''\nwhile n:\n n, i = divmod(n, len(self.allowed_chars))\n s += self.allowed_chars[i]\nreturn self.prefix + s",
"shortUrl = shortUrl[len(self.prefix):]\nn = 0\nbase = 1\nfor c in shortUrl:\n i = self.allowed_chars.index(c)\n n += base ... | <|body_start_0|>
self.storage.append(longUrl)
n = len(self.storage)
n <<= 1
s = ''
while n:
n, i = divmod(n, len(self.allowed_chars))
s += self.allowed_chars[i]
return self.prefix + s
<|end_body_0|>
<|body_start_1|>
shortUrl = shortUrl[len... | 06/02/2020 23:01 | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""06/02/2020 23:01"""
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
<|body_0|>
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_028711 | 3,269 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL.",
"name": "encode",
"signature": "def encode(self, longUrl: str) -> str"
},
{
"docstring": "Decodes a shortened URL to its original URL.",
"name": "decode",
"signature": "def decode(self, shortUrl: str) -> str"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
06/02/2020 23:01
Method signatures and docstrings:
- def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL.
- def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL. | Implement the Python class `Codec` described below.
Class description:
06/02/2020 23:01
Method signatures and docstrings:
- def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL.
- def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL.
<|skeleton|>
class Codec:
"""... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Codec:
"""06/02/2020 23:01"""
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
<|body_0|>
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
"""06/02/2020 23:01"""
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
self.storage.append(longUrl)
n = len(self.storage)
n <<= 1
s = ''
while n:
n, i = divmod(n, len(self.allowed_chars))
s += se... | the_stack_v2_python_sparse | leetcode/solved/535_Encode_and_Decode_TinyURL/solution.py | sungminoh/algorithms | train | 0 |
a85090cd2866ef3fa6587a6fa7a38b0074dd534e | [
"self.data_to_sign = data_to_sign\nself.data_format = data_format\nself.external_reference = external_reference\nself.xslt = xslt\nself.signing_format = signing_format\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\ndata_to_sign = dictionary.get('dataToSign')\ndata_... | <|body_start_0|>
self.data_to_sign = data_to_sign
self.data_format = data_format
self.external_reference = external_reference
self.xslt = xslt
self.signing_format = signing_format
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
... | Implementation of the 'SignRequest' model. TODO: type model description here. Attributes: data_to_sign (string): Base 64 encoded data data_format (DataFormat): Format of data (i.e xml) external_reference (string): The service reference for the signing. Will be used for auditlog, and invoicing xslt (string): Base 64 enc... | SignRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignRequest:
"""Implementation of the 'SignRequest' model. TODO: type model description here. Attributes: data_to_sign (string): Base 64 encoded data data_format (DataFormat): Format of data (i.e xml) external_reference (string): The service reference for the signing. Will be used for auditlog, a... | stack_v2_sparse_classes_36k_train_028712 | 3,017 | permissive | [
{
"docstring": "Constructor for the SignRequest class",
"name": "__init__",
"signature": "def __init__(self, data_to_sign=None, data_format=None, external_reference=None, xslt=None, signing_format=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictio... | 2 | null | Implement the Python class `SignRequest` described below.
Class description:
Implementation of the 'SignRequest' model. TODO: type model description here. Attributes: data_to_sign (string): Base 64 encoded data data_format (DataFormat): Format of data (i.e xml) external_reference (string): The service reference for th... | Implement the Python class `SignRequest` described below.
Class description:
Implementation of the 'SignRequest' model. TODO: type model description here. Attributes: data_to_sign (string): Base 64 encoded data data_format (DataFormat): Format of data (i.e xml) external_reference (string): The service reference for th... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class SignRequest:
"""Implementation of the 'SignRequest' model. TODO: type model description here. Attributes: data_to_sign (string): Base 64 encoded data data_format (DataFormat): Format of data (i.e xml) external_reference (string): The service reference for the signing. Will be used for auditlog, a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignRequest:
"""Implementation of the 'SignRequest' model. TODO: type model description here. Attributes: data_to_sign (string): Base 64 encoded data data_format (DataFormat): Format of data (i.e xml) external_reference (string): The service reference for the signing. Will be used for auditlog, and invoicing ... | the_stack_v2_python_sparse | idfy_rest_client/models/sign_request.py | dealflowteam/Idfy | train | 0 |
9ca3bf578a7a52863846567c300f54cfc8ed5c8c | [
"ciphertext = []\nk = 0\nn = len(key)\nfor i in range(len(self)):\n p = self[i]\n if p.isalpha():\n ciphertext.append(chr((ord(p) + ord((key[k % n].upper(), key[k % n].lower())[int(p.islower())]) - 2 * ord('Aa'[int(p.islower())])) % 26 + ord('Aa'[int(p.islower())])))\n k += 1\n else:\n ... | <|body_start_0|>
ciphertext = []
k = 0
n = len(key)
for i in range(len(self)):
p = self[i]
if p.isalpha():
ciphertext.append(chr((ord(p) + ord((key[k % n].upper(), key[k % n].lower())[int(p.islower())]) - 2 * ord('Aa'[int(p.islower())])) % 26 + ord... | An implementation of the Vigenere cipher. | Vigenere | [
"CC-BY-SA-4.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vigenere:
"""An implementation of the Vigenere cipher."""
def encipher(self, key):
"""Encipher input (plaintext) using the Vigenere cipher and return it (ciphertext)."""
<|body_0|>
def decipher(self, key):
"""Decipher input (ciphertext) using the Vigenere cipher ... | stack_v2_sparse_classes_36k_train_028713 | 19,578 | permissive | [
{
"docstring": "Encipher input (plaintext) using the Vigenere cipher and return it (ciphertext).",
"name": "encipher",
"signature": "def encipher(self, key)"
},
{
"docstring": "Decipher input (ciphertext) using the Vigenere cipher and return it (plaintext).",
"name": "decipher",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_012364 | Implement the Python class `Vigenere` described below.
Class description:
An implementation of the Vigenere cipher.
Method signatures and docstrings:
- def encipher(self, key): Encipher input (plaintext) using the Vigenere cipher and return it (ciphertext).
- def decipher(self, key): Decipher input (ciphertext) using... | Implement the Python class `Vigenere` described below.
Class description:
An implementation of the Vigenere cipher.
Method signatures and docstrings:
- def encipher(self, key): Encipher input (plaintext) using the Vigenere cipher and return it (ciphertext).
- def decipher(self, key): Decipher input (ciphertext) using... | e5532a9be30e998ed49888ae5526a1c3b5a2e1b3 | <|skeleton|>
class Vigenere:
"""An implementation of the Vigenere cipher."""
def encipher(self, key):
"""Encipher input (plaintext) using the Vigenere cipher and return it (ciphertext)."""
<|body_0|>
def decipher(self, key):
"""Decipher input (ciphertext) using the Vigenere cipher ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vigenere:
"""An implementation of the Vigenere cipher."""
def encipher(self, key):
"""Encipher input (plaintext) using the Vigenere cipher and return it (ciphertext)."""
ciphertext = []
k = 0
n = len(key)
for i in range(len(self)):
p = self[i]
... | the_stack_v2_python_sparse | Cryptography/Rotation-Ciphers/pygenere.py | nclv/My-Gray-Hacker-Resources | train | 2 |
915938c309c035944502500677609cd50e279caa | [
"projects = Project.objects.filter(owner=request.user)\nserializer = self.serializer_class(projects, many=True)\nresponse_data = serializer.data\nfor d in response_data:\n p = Project.objects.get(id=d['id'])\n m = Metadata(p, None)\n meta = m.get_metadata('ProjectMetadata')\n d['metadata'] = meta\nretur... | <|body_start_0|>
projects = Project.objects.filter(owner=request.user)
serializer = self.serializer_class(projects, many=True)
response_data = serializer.data
for d in response_data:
p = Project.objects.get(id=d['id'])
m = Metadata(p, None)
meta = m.ge... | The Project API endpoint viewset for managing user projects in the database. | ProjectView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectView:
"""The Project API endpoint viewset for managing user projects in the database."""
def list(self, request, pk=None):
"""GET request that lists all the projects :param request: GET request :return: List of projects"""
<|body_0|>
def create(self, request):
... | stack_v2_sparse_classes_36k_train_028714 | 4,532 | no_license | [
{
"docstring": "GET request that lists all the projects :param request: GET request :return: List of projects",
"name": "list",
"signature": "def list(self, request, pk=None)"
},
{
"docstring": "POST request that creates a new project. :param request: POST request :return: New project object",
... | 4 | stack_v2_sparse_classes_30k_train_012894 | Implement the Python class `ProjectView` described below.
Class description:
The Project API endpoint viewset for managing user projects in the database.
Method signatures and docstrings:
- def list(self, request, pk=None): GET request that lists all the projects :param request: GET request :return: List of projects
... | Implement the Python class `ProjectView` described below.
Class description:
The Project API endpoint viewset for managing user projects in the database.
Method signatures and docstrings:
- def list(self, request, pk=None): GET request that lists all the projects :param request: GET request :return: List of projects
... | f694ef259c54cd89321eaa3650212241be033d99 | <|skeleton|>
class ProjectView:
"""The Project API endpoint viewset for managing user projects in the database."""
def list(self, request, pk=None):
"""GET request that lists all the projects :param request: GET request :return: List of projects"""
<|body_0|>
def create(self, request):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectView:
"""The Project API endpoint viewset for managing user projects in the database."""
def list(self, request, pk=None):
"""GET request that lists all the projects :param request: GET request :return: List of projects"""
projects = Project.objects.filter(owner=request.user)
... | the_stack_v2_python_sparse | vb_django/views/project_views.py | brandonmain/vb_django | train | 0 |
0841afd1c38e0a802938bf18fc0017cd1df4403c | [
"for i in range(1, 32):\n bit = DiscreteBit.Field(bitIndex=i, bitName='testBit', meaningWhenSet='happy', meaningWhenNotSet='unhappy')\n bit.setData(True)\n self.assertEqual(bit.pack(), 1 << i - 1, 'Label Not Packed Properly')",
"for i in range(1, 32):\n bit = DiscreteBit.Field(bitIndex=i, bitName='tes... | <|body_start_0|>
for i in range(1, 32):
bit = DiscreteBit.Field(bitIndex=i, bitName='testBit', meaningWhenSet='happy', meaningWhenNotSet='unhappy')
bit.setData(True)
self.assertEqual(bit.pack(), 1 << i - 1, 'Label Not Packed Properly')
<|end_body_0|>
<|body_start_1|>
... | Verify that bits are packed and unpacked properly | testBitPackandUnpack | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class testBitPackandUnpack:
"""Verify that bits are packed and unpacked properly"""
def testBitPackingSet(self):
"""Move a bit from 1 to 32, check only this bit is set"""
<|body_0|>
def testBitPackingUnset(self):
"""Move a bit from 1 to 32, check only this bit is not s... | stack_v2_sparse_classes_36k_train_028715 | 7,060 | permissive | [
{
"docstring": "Move a bit from 1 to 32, check only this bit is set",
"name": "testBitPackingSet",
"signature": "def testBitPackingSet(self)"
},
{
"docstring": "Move a bit from 1 to 32, check only this bit is not set",
"name": "testBitPackingUnset",
"signature": "def testBitPackingUnset(... | 3 | stack_v2_sparse_classes_30k_train_005960 | Implement the Python class `testBitPackandUnpack` described below.
Class description:
Verify that bits are packed and unpacked properly
Method signatures and docstrings:
- def testBitPackingSet(self): Move a bit from 1 to 32, check only this bit is set
- def testBitPackingUnset(self): Move a bit from 1 to 32, check o... | Implement the Python class `testBitPackandUnpack` described below.
Class description:
Verify that bits are packed and unpacked properly
Method signatures and docstrings:
- def testBitPackingSet(self): Move a bit from 1 to 32, check only this bit is set
- def testBitPackingUnset(self): Move a bit from 1 to 32, check o... | 077c979c7eb2aae206f6052c2a67e68ecc5b35a8 | <|skeleton|>
class testBitPackandUnpack:
"""Verify that bits are packed and unpacked properly"""
def testBitPackingSet(self):
"""Move a bit from 1 to 32, check only this bit is set"""
<|body_0|>
def testBitPackingUnset(self):
"""Move a bit from 1 to 32, check only this bit is not s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class testBitPackandUnpack:
"""Verify that bits are packed and unpacked properly"""
def testBitPackingSet(self):
"""Move a bit from 1 to 32, check only this bit is set"""
for i in range(1, 32):
bit = DiscreteBit.Field(bitIndex=i, bitName='testBit', meaningWhenSet='happy', meaningWhe... | the_stack_v2_python_sparse | ARINC429/UnitTests/DiscreteBitTest.py | superliujian/Py429 | train | 1 |
f17bc693587f8cf15c9c808117c8599155ca5f19 | [
"self.stdev = stdev\nself.use_keys = use_keys\nself.ignore_keys = ignore_keys",
"valid_keys = _get_valid_keys(inputs.keys(), self.use_keys, self.ignore_keys)\nfor k in valid_keys:\n v = inputs[k]\n std = random.uniform(0.0, self.stdev)\n inputs[k] = (v + std * torch.randn(*v.shape, dtype=v.dtype, device=... | <|body_start_0|>
self.stdev = stdev
self.use_keys = use_keys
self.ignore_keys = ignore_keys
<|end_body_0|>
<|body_start_1|>
valid_keys = _get_valid_keys(inputs.keys(), self.use_keys, self.ignore_keys)
for k in valid_keys:
v = inputs[k]
std = random.unifor... | Applies random gaussian noise on the images. | GaussianNoise | [
"Apache-2.0",
"CC-BY-NC-SA-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianNoise:
"""Applies random gaussian noise on the images."""
def __init__(self, stdev: float=0.0, use_keys: Optional[Union[KeysView, Sequence[str]]]=('images',), ignore_keys: Optional[Union[KeysView, Sequence[str]]]=None) -> None:
"""Initialize GaussianNoise. Parameters --------... | stack_v2_sparse_classes_36k_train_028716 | 42,078 | permissive | [
{
"docstring": "Initialize GaussianNoise. Parameters ---------- stdev : float, default 0.0 The maximum standard deviation of the gaussian noise. use_keys : Optional[Union[KeysView, Sequence[str]]], optional If it is not None, then only elements with these keys will be transformed. Otherwise, all elements are tr... | 2 | stack_v2_sparse_classes_30k_train_012045 | Implement the Python class `GaussianNoise` described below.
Class description:
Applies random gaussian noise on the images.
Method signatures and docstrings:
- def __init__(self, stdev: float=0.0, use_keys: Optional[Union[KeysView, Sequence[str]]]=('images',), ignore_keys: Optional[Union[KeysView, Sequence[str]]]=Non... | Implement the Python class `GaussianNoise` described below.
Class description:
Applies random gaussian noise on the images.
Method signatures and docstrings:
- def __init__(self, stdev: float=0.0, use_keys: Optional[Union[KeysView, Sequence[str]]]=('images',), ignore_keys: Optional[Union[KeysView, Sequence[str]]]=Non... | d6582a0fd386517fdefbe2c347cef53150b5b1da | <|skeleton|>
class GaussianNoise:
"""Applies random gaussian noise on the images."""
def __init__(self, stdev: float=0.0, use_keys: Optional[Union[KeysView, Sequence[str]]]=('images',), ignore_keys: Optional[Union[KeysView, Sequence[str]]]=None) -> None:
"""Initialize GaussianNoise. Parameters --------... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianNoise:
"""Applies random gaussian noise on the images."""
def __init__(self, stdev: float=0.0, use_keys: Optional[Union[KeysView, Sequence[str]]]=('images',), ignore_keys: Optional[Union[KeysView, Sequence[str]]]=None) -> None:
"""Initialize GaussianNoise. Parameters ---------- stdev : fl... | the_stack_v2_python_sparse | ptlflow/data/flow_transforms.py | hmorimitsu/ptlflow | train | 140 |
5eb81b456c2b531c621483890d7c1ba28b577be5 | [
"res = []\n\ndef get_preorder(root):\n if not root:\n res.append('#')\n return\n res.append(str(root.val))\n get_preorder(root.left)\n get_preorder(root.right)\nget_preorder(root)\nreturn ','.join(res)",
"vals = iter(data.split(','))\n\ndef helper():\n val = next(vals)\n if val == ... | <|body_start_0|>
res = []
def get_preorder(root):
if not root:
res.append('#')
return
res.append(str(root.val))
get_preorder(root.left)
get_preorder(root.right)
get_preorder(root)
return ','.join(res)
<|end_... | 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_028717 | 1,489 | 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:... | 238995bd23c8a6c40c6035890e94baa2473d4bbc | <|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 = []
def get_preorder(root):
if not root:
res.append('#')
return
res.append(str(root.val))
get_preorder(r... | the_stack_v2_python_sparse | problems/N297_Serialize_And_Deserialize_Binary_Tree.py | wan-catherine/Leetcode | train | 5 | |
d1cc847d37a6080cf1f829499efefdd85be49854 | [
"maxVal = nums[0]\nfor i in range(1, len(nums)):\n nums[i] = max(nums[i], nums[i] + nums[i - 1])\n if nums[i] > maxVal:\n maxVal = nums[i]\nreturn maxVal",
"temp = nums[0]\nmaxVal = nums[0]\nfor i in nums[1:]:\n temp = max(0, temp)\n temp += i\n maxVal = max(i, temp, maxVal)\nreturn maxVal"
... | <|body_start_0|>
maxVal = nums[0]
for i in range(1, len(nums)):
nums[i] = max(nums[i], nums[i] + nums[i - 1])
if nums[i] > maxVal:
maxVal = nums[i]
return maxVal
<|end_body_0|>
<|body_start_1|>
temp = nums[0]
maxVal = nums[0]
for i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def ms(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
maxVal = nums[0]
for i in range(1, len(nums)):... | stack_v2_sparse_classes_36k_train_028718 | 762 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "ms",
"signature": "def ms(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int
- def ms(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 maxSubArray(self, nums): :type nums: List[int] :rtype: int
- def ms(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxSubArray(self, nu... | 11c8fc663888b48b5417256aab1bf872190267ba | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def ms(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 maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
maxVal = nums[0]
for i in range(1, len(nums)):
nums[i] = max(nums[i], nums[i] + nums[i - 1])
if nums[i] > maxVal:
maxVal = nums[i]
return maxVal
def ms(se... | the_stack_v2_python_sparse | Maximum Subarray.py | lfdyf20/Leetcode | train | 1 | |
036f876c635b42a7abcec5ca77c2380bcbf72877 | [
"length = len(nums)\nfor i in range(1, length):\n for j in range(0, i):\n if nums[i] == nums[j]:\n return nums[i]",
"length = len(nums)\nnums_count = [0] * (length - 1)\nfor i in range(length):\n if nums_count[nums[i] - 1] == 1:\n return nums[i]\n else:\n nums_count[nums[i... | <|body_start_0|>
length = len(nums)
for i in range(1, length):
for j in range(0, i):
if nums[i] == nums[j]:
return nums[i]
<|end_body_0|>
<|body_start_1|>
length = len(nums)
nums_count = [0] * (length - 1)
for i in range(length):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate1(self, nums):
"""Time Limit Exceeded :type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate(self, nums):
"""Time Limit Exceeded :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_028719 | 750 | no_license | [
{
"docstring": "Time Limit Exceeded :type nums: List[int] :rtype: int",
"name": "findDuplicate1",
"signature": "def findDuplicate1(self, nums)"
},
{
"docstring": "Time Limit Exceeded :type nums: List[int] :rtype: int",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums)"... | 2 | stack_v2_sparse_classes_30k_train_006509 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate1(self, nums): Time Limit Exceeded :type nums: List[int] :rtype: int
- def findDuplicate(self, nums): Time Limit Exceeded :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate1(self, nums): Time Limit Exceeded :type nums: List[int] :rtype: int
- def findDuplicate(self, nums): Time Limit Exceeded :type nums: List[int] :rtype: int
<|sk... | 8cde0af5a9de3f01e71093e5cdbe58908db16c69 | <|skeleton|>
class Solution:
def findDuplicate1(self, nums):
"""Time Limit Exceeded :type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate(self, nums):
"""Time Limit Exceeded :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate1(self, nums):
"""Time Limit Exceeded :type nums: List[int] :rtype: int"""
length = len(nums)
for i in range(1, length):
for j in range(0, i):
if nums[i] == nums[j]:
return nums[i]
def findDuplicate(self, n... | the_stack_v2_python_sparse | test_287.py | huangbenyu/leetcode | train | 0 | |
d9a3bc826b4b0d2dc17465bf06427d4f6ad785e2 | [
"super().__init__(initial_class_observations, parent_node, random_state)\nself.fMAE_M = 0.0\nself.fMAE_P = 0.0\nself.fMAE_SP = 0.0",
"normalized_sample = rht.normalize_sample(X)\nnormalized_base_pred = self._predict_base(normalized_sample)\n_, n_features = get_dimensions(X)\n_, n_targets = get_dimensions(y)\nnorm... | <|body_start_0|>
super().__init__(initial_class_observations, parent_node, random_state)
self.fMAE_M = 0.0
self.fMAE_P = 0.0
self.fMAE_SP = 0.0
<|end_body_0|>
<|body_start_1|>
normalized_sample = rht.normalize_sample(X)
normalized_base_pred = self._predict_base(normalize... | Inactive Multi-target regression learning node for SST-HT that keeps track of mean, perceptron, and stacked perceptrons predictors for each target. Parameters ---------- initial_class_observations: dict A dictionary containing the set of sufficient statistics to be stored by the leaf node. It contains the following ele... | SSTInactiveLearningNodeAdaptive | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSTInactiveLearningNodeAdaptive:
"""Inactive Multi-target regression learning node for SST-HT that keeps track of mean, perceptron, and stacked perceptrons predictors for each target. Parameters ---------- initial_class_observations: dict A dictionary containing the set of sufficient statistics t... | stack_v2_sparse_classes_36k_train_028720 | 3,710 | permissive | [
{
"docstring": "SSTInactiveLearningNodeAdaptive class constructor.",
"name": "__init__",
"signature": "def __init__(self, initial_class_observations, parent_node=None, random_state=None)"
},
{
"docstring": "Update the perceptron weights Parameters ---------- X: numpy.ndarray of length equal to t... | 2 | stack_v2_sparse_classes_30k_train_009233 | Implement the Python class `SSTInactiveLearningNodeAdaptive` described below.
Class description:
Inactive Multi-target regression learning node for SST-HT that keeps track of mean, perceptron, and stacked perceptrons predictors for each target. Parameters ---------- initial_class_observations: dict A dictionary contai... | Implement the Python class `SSTInactiveLearningNodeAdaptive` described below.
Class description:
Inactive Multi-target regression learning node for SST-HT that keeps track of mean, perceptron, and stacked perceptrons predictors for each target. Parameters ---------- initial_class_observations: dict A dictionary contai... | bfe504b4ca24b77e211fd55dc42844fc494671d7 | <|skeleton|>
class SSTInactiveLearningNodeAdaptive:
"""Inactive Multi-target regression learning node for SST-HT that keeps track of mean, perceptron, and stacked perceptrons predictors for each target. Parameters ---------- initial_class_observations: dict A dictionary containing the set of sufficient statistics t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSTInactiveLearningNodeAdaptive:
"""Inactive Multi-target regression learning node for SST-HT that keeps track of mean, perceptron, and stacked perceptrons predictors for each target. Parameters ---------- initial_class_observations: dict A dictionary containing the set of sufficient statistics to be stored b... | the_stack_v2_python_sparse | src/skmultiflow/trees/nodes/sst_inactive_learning_node_adaptive.py | jacobmontiel/scikit-multiflow | train | 1 |
22d188ff4b348248d539cb5766141e17af2bc17f | [
"super().__init__(**kwargs)\nself.plot_axis_type = plot_axis_type\nself.label = label",
"if self.label is not None:\n label = self.label\nif plot_axis_type == 'linear' or plot_axis_type == 'symlog':\n plt.plot(x, y, label=label, **self.config_dict)\nelif plot_axis_type == 'semilogy':\n plt.semilogy(x, y,... | <|body_start_0|>
super().__init__(**kwargs)
self.plot_axis_type = plot_axis_type
self.label = label
<|end_body_0|>
<|body_start_1|>
if self.label is not None:
label = self.label
if plot_axis_type == 'linear' or plot_axis_type == 'symlog':
plt.plot(x, y, l... | YXPlot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YXPlot:
def __init__(self, plot_axis_type=None, label=None, **kwargs):
"""Plots 1D data structures as a y vs x figure. This object wraps the following Matplotlib methods: - plt.plot: https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.plot.html"""
<|body_0|>
def plot_... | stack_v2_sparse_classes_36k_train_028721 | 2,802 | permissive | [
{
"docstring": "Plots 1D data structures as a y vs x figure. This object wraps the following Matplotlib methods: - plt.plot: https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.plot.html",
"name": "__init__",
"signature": "def __init__(self, plot_axis_type=None, label=None, **kwargs)"
},
{
... | 2 | null | Implement the Python class `YXPlot` described below.
Class description:
Implement the YXPlot class.
Method signatures and docstrings:
- def __init__(self, plot_axis_type=None, label=None, **kwargs): Plots 1D data structures as a y vs x figure. This object wraps the following Matplotlib methods: - plt.plot: https://ma... | Implement the Python class `YXPlot` described below.
Class description:
Implement the YXPlot class.
Method signatures and docstrings:
- def __init__(self, plot_axis_type=None, label=None, **kwargs): Plots 1D data structures as a y vs x figure. This object wraps the following Matplotlib methods: - plt.plot: https://ma... | 6639dd86d21ea28e942155753ec556752735b4e4 | <|skeleton|>
class YXPlot:
def __init__(self, plot_axis_type=None, label=None, **kwargs):
"""Plots 1D data structures as a y vs x figure. This object wraps the following Matplotlib methods: - plt.plot: https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.plot.html"""
<|body_0|>
def plot_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YXPlot:
def __init__(self, plot_axis_type=None, label=None, **kwargs):
"""Plots 1D data structures as a y vs x figure. This object wraps the following Matplotlib methods: - plt.plot: https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.plot.html"""
super().__init__(**kwargs)
self... | the_stack_v2_python_sparse | autoarray/plot/wrap/one_d/yx_plot.py | Jammy2211/PyAutoArray | train | 6 | |
289ff93490bc1ab6b257a3b874a32827886fa064 | [
"hashed = hashlib.sha256(string.encode())\nhex_of_hashed = hashed.hexdigest()\nreturn hex_of_hashed",
"hashed = hashlib.sha256(string.encode())\nhex_of_string = hashed.hexdigest()\nhashed = hashlib.sha256(candidate.encode())\nhex_of_candidate = hashed.hexdigest()\nreturn hex_of_string == hex_of_string"
] | <|body_start_0|>
hashed = hashlib.sha256(string.encode())
hex_of_hashed = hashed.hexdigest()
return hex_of_hashed
<|end_body_0|>
<|body_start_1|>
hashed = hashlib.sha256(string.encode())
hex_of_string = hashed.hexdigest()
hashed = hashlib.sha256(candidate.encode())
... | Hasher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hasher:
def makeHash(string):
"""returns the hash value of string input"""
<|body_0|>
def checkHash(string, candidate):
"""string : hash value candidate : the input to check with hash value returns True if equal else False"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_028722 | 1,325 | no_license | [
{
"docstring": "returns the hash value of string input",
"name": "makeHash",
"signature": "def makeHash(string)"
},
{
"docstring": "string : hash value candidate : the input to check with hash value returns True if equal else False",
"name": "checkHash",
"signature": "def checkHash(strin... | 2 | stack_v2_sparse_classes_30k_train_010734 | Implement the Python class `Hasher` described below.
Class description:
Implement the Hasher class.
Method signatures and docstrings:
- def makeHash(string): returns the hash value of string input
- def checkHash(string, candidate): string : hash value candidate : the input to check with hash value returns True if eq... | Implement the Python class `Hasher` described below.
Class description:
Implement the Hasher class.
Method signatures and docstrings:
- def makeHash(string): returns the hash value of string input
- def checkHash(string, candidate): string : hash value candidate : the input to check with hash value returns True if eq... | a3500acd8efb41aeefbadbff966f956a9f1e7766 | <|skeleton|>
class Hasher:
def makeHash(string):
"""returns the hash value of string input"""
<|body_0|>
def checkHash(string, candidate):
"""string : hash value candidate : the input to check with hash value returns True if equal else False"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Hasher:
def makeHash(string):
"""returns the hash value of string input"""
hashed = hashlib.sha256(string.encode())
hex_of_hashed = hashed.hexdigest()
return hex_of_hashed
def checkHash(string, candidate):
"""string : hash value candidate : the input to check with ... | the_stack_v2_python_sparse | Tourino/helpers.py | zerobits01/Tourino | train | 0 | |
305bb73d639297ce46a08da0e2f6a2d7be0985d7 | [
"if len(set(nums1)) <= len(set(nums2)):\n return [each for each in set(nums1) if each in set(nums2)]\nreturn [each for each in set(nums2) if each in set(nums1)]",
"res = []\nfrom collections import Counter\nn1 = Counter(nums1)\nfor each in nums2:\n if each in n1.keys() and each not in res:\n res.appe... | <|body_start_0|>
if len(set(nums1)) <= len(set(nums2)):
return [each for each in set(nums1) if each in set(nums2)]
return [each for each in set(nums2) if each in set(nums1)]
<|end_body_0|>
<|body_start_1|>
res = []
from collections import Counter
n1 = Counter(nums1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersection(self, nums1, nums2):
"""Time: O(n + m) Space: O(n + m) :type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersection1(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]""... | stack_v2_sparse_classes_36k_train_028723 | 1,445 | no_license | [
{
"docstring": "Time: O(n + m) Space: O(n + m) :type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersection",
"signature": "def intersection(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersection(self, nums1, nums2): Time: O(n + m) Space: O(n + m) :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersection1(self, nums1, nums2): :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersection(self, nums1, nums2): Time: O(n + m) Space: O(n + m) :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersection1(self, nums1, nums2): :typ... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def intersection(self, nums1, nums2):
"""Time: O(n + m) Space: O(n + m) :type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersection1(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def intersection(self, nums1, nums2):
"""Time: O(n + m) Space: O(n + m) :type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
if len(set(nums1)) <= len(set(nums2)):
return [each for each in set(nums1) if each in set(nums2)]
return [each for each in se... | the_stack_v2_python_sparse | LeetCode/BinarySearch/349_intersection_of_two_arrays.py | XyK0907/for_work | train | 0 | |
8717f01badab675c2a12bd8f0bf2677e60c36334 | [
"l = len(prices)\nif l == 0:\n return 0\nstart = prices[0]\nprofit = 0\nfor i in range(1, l):\n gain = prices[i] - start\n start = prices[i]\n if gain > 0:\n profit += gain\nreturn profit",
"start = None\nprofit = 0\nfor p in prices:\n if start is None:\n start = p\n continue\n... | <|body_start_0|>
l = len(prices)
if l == 0:
return 0
start = prices[0]
profit = 0
for i in range(1, l):
gain = prices[i] - start
start = prices[i]
if gain > 0:
profit += gain
return profit
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = len(prices)
if l == 0:
... | stack_v2_sparse_classes_36k_train_028724 | 1,245 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "_maxProfit",
"signature": "def _maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019432 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def _maxPr... | aa86773659bfb6af8b9f0f1562913739a1110a0f | <|skeleton|>
class Solution:
def _maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
l = len(prices)
if l == 0:
return 0
start = prices[0]
profit = 0
for i in range(1, l):
gain = prices[i] - start
start = prices[i]
if... | the_stack_v2_python_sparse | leetcode/SellAndBuyStocks.py | naren-m/programming_practice | train | 0 | |
6cecbce301a792eb28d87a5e8ac57cac14f9b3ec | [
"if not root:\n return 0\nreturn 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))",
"def top_down(root, depth):\n if not root:\n return depth\n return max(top_down(root.left, depth + 1), top_down(root.right, depth + 1))\nreturn top_down(root, 0)",
"if not root:\n return 0\nwhite, ... | <|body_start_0|>
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
<|end_body_0|>
<|body_start_1|>
def top_down(root, depth):
if not root:
return depth
return max(top_down(root.left, depth + 1), top_down... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root: TreeNode) -> int:
"""递归法(自底向上) 分别计算出左子树的深度,右子树的深度,再计算其最大值 最后+1,是加上根节点这一层"""
<|body_0|>
def maxDepth_1(self, root: TreeNode) -> int:
"""递归法(自顶向下)"""
<|body_1|>
def maxDepth_2(self, root: TreeNode) -> int:
"""层次遍历... | stack_v2_sparse_classes_36k_train_028725 | 1,701 | no_license | [
{
"docstring": "递归法(自底向上) 分别计算出左子树的深度,右子树的深度,再计算其最大值 最后+1,是加上根节点这一层",
"name": "maxDepth",
"signature": "def maxDepth(self, root: TreeNode) -> int"
},
{
"docstring": "递归法(自顶向下)",
"name": "maxDepth_1",
"signature": "def maxDepth_1(self, root: TreeNode) -> int"
},
{
"docstring": "层次... | 3 | stack_v2_sparse_classes_30k_val_000837 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root: TreeNode) -> int: 递归法(自底向上) 分别计算出左子树的深度,右子树的深度,再计算其最大值 最后+1,是加上根节点这一层
- def maxDepth_1(self, root: TreeNode) -> int: 递归法(自顶向下)
- def maxDepth_2(self, roo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root: TreeNode) -> int: 递归法(自底向上) 分别计算出左子树的深度,右子树的深度,再计算其最大值 最后+1,是加上根节点这一层
- def maxDepth_1(self, root: TreeNode) -> int: 递归法(自顶向下)
- def maxDepth_2(self, roo... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def maxDepth(self, root: TreeNode) -> int:
"""递归法(自底向上) 分别计算出左子树的深度,右子树的深度,再计算其最大值 最后+1,是加上根节点这一层"""
<|body_0|>
def maxDepth_1(self, root: TreeNode) -> int:
"""递归法(自顶向下)"""
<|body_1|>
def maxDepth_2(self, root: TreeNode) -> int:
"""层次遍历... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth(self, root: TreeNode) -> int:
"""递归法(自底向上) 分别计算出左子树的深度,右子树的深度,再计算其最大值 最后+1,是加上根节点这一层"""
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
def maxDepth_1(self, root: TreeNode) -> int:
"""递归法(自顶向下)"""... | the_stack_v2_python_sparse | algorithm/leetcode/tree/07-二叉树的最大深度.py | lxconfig/UbuntuCode_bak | train | 0 | |
8cab00b44fce5db2942bd4725c6d7cbc79e6023f | [
"self.id = plant_id\nself.mod = mod\nself.growth_bonus = 0.025\nself.growth_chance = 0.9\nself.light_range = Range(10, 16)\nself.soils = ['farmland_soil']\nself.crop_yield = None\nself.name = None\nself.parent_a = None\nself.parent_b = None\nself.path = None\nself.qualified_id = None\nself.seed_item_id = None\nself... | <|body_start_0|>
self.id = plant_id
self.mod = mod
self.growth_bonus = 0.025
self.growth_chance = 0.9
self.light_range = Range(10, 16)
self.soils = ['farmland_soil']
self.crop_yield = None
self.name = None
self.parent_a = None
self.parent_b... | Plant is a specific plant which can be grown in a Agricraft crop. | Plant | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plant:
"""Plant is a specific plant which can be grown in a Agricraft crop."""
def __init__(self, mod: Mod, plant_id: str):
"""Create a new plant."""
<|body_0|>
def tier(self) -> int:
"""Get how many mutations are required before you find a plant which is native ... | stack_v2_sparse_classes_36k_train_028726 | 1,487 | no_license | [
{
"docstring": "Create a new plant.",
"name": "__init__",
"signature": "def __init__(self, mod: Mod, plant_id: str)"
},
{
"docstring": "Get how many mutations are required before you find a plant which is native to the world.",
"name": "tier",
"signature": "def tier(self) -> int"
}
] | 2 | null | Implement the Python class `Plant` described below.
Class description:
Plant is a specific plant which can be grown in a Agricraft crop.
Method signatures and docstrings:
- def __init__(self, mod: Mod, plant_id: str): Create a new plant.
- def tier(self) -> int: Get how many mutations are required before you find a p... | Implement the Python class `Plant` described below.
Class description:
Plant is a specific plant which can be grown in a Agricraft crop.
Method signatures and docstrings:
- def __init__(self, mod: Mod, plant_id: str): Create a new plant.
- def tier(self) -> int: Get how many mutations are required before you find a p... | 9bd6e74cb3817eec76119978ea31cf5b04e0ed51 | <|skeleton|>
class Plant:
"""Plant is a specific plant which can be grown in a Agricraft crop."""
def __init__(self, mod: Mod, plant_id: str):
"""Create a new plant."""
<|body_0|>
def tier(self) -> int:
"""Get how many mutations are required before you find a plant which is native ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Plant:
"""Plant is a specific plant which can be grown in a Agricraft crop."""
def __init__(self, mod: Mod, plant_id: str):
"""Create a new plant."""
self.id = plant_id
self.mod = mod
self.growth_bonus = 0.025
self.growth_chance = 0.9
self.light_range = Ran... | the_stack_v2_python_sparse | src/packconfig/agricraft/plant.py | tungstonminer/packconfig | train | 0 |
c03dc0fd02681f8cd581a54d185d164356bf75d5 | [
"size = len(height)\nif size < 2:\n return 0\nleft_arr, right_arr = ([0] * size, [0] * size)\nleft_arr[0] = height[0]\nfor i in range(1, size):\n left_arr[i] = max(left_arr[i - 1], height[i])\nright_arr[size - 1] = height[size - 1]\nfor i in range(size - 2, -1, -1):\n right_arr[i] = max(right_arr[i + 1], h... | <|body_start_0|>
size = len(height)
if size < 2:
return 0
left_arr, right_arr = ([0] * size, [0] * size)
left_arr[0] = height[0]
for i in range(1, size):
left_arr[i] = max(left_arr[i - 1], height[i])
right_arr[size - 1] = height[size - 1]
f... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def trap_fast(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
size = len(height)
if size < 2:
... | stack_v2_sparse_classes_36k_train_028727 | 4,728 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trap",
"signature": "def trap(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trap_fast",
"signature": "def trap_fast(self, height)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): :type height: List[int] :rtype: int
- def trap_fast(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): :type height: List[int] :rtype: int
- def trap_fast(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def trap(self, h... | 8731e2ccfbda9323ea5c8629599806cd1c37c3bf | <|skeleton|>
class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def trap_fast(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
size = len(height)
if size < 2:
return 0
left_arr, right_arr = ([0] * size, [0] * size)
left_arr[0] = height[0]
for i in range(1, size):
left_arr[i] = max(left_ar... | the_stack_v2_python_sparse | problems/two_pointer_sliding_window/RainWaterTrappingAndContainerWithMostWater.py | jonu4u/DataStructuresInPython | train | 0 | |
79642d78bdfc4b8895089edb0cd6edcda84ff165 | [
"key = '2b7e151628aed2a6abf7158809cf4f3c'\niv = '000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f'\npt = '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51\\n 30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710'\nkey, iv, pt = (a2b_p(key), a2b_p(iv), a2b_p... | <|body_start_0|>
key = '2b7e151628aed2a6abf7158809cf4f3c'
iv = '000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f'
pt = '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51\n 30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710'
key... | CBC test with Rijndael | CBC_Rijndael_Test | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CBC_Rijndael_Test:
"""CBC test with Rijndael"""
def testCBC_Rijndael_256(self):
"""Rijndael CBC 256"""
<|body_0|>
def testCBC_Rijndael_variable_data(self):
"""Rijndael CBC 256"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
key = '2b7e151628aed2... | stack_v2_sparse_classes_36k_train_028728 | 5,430 | permissive | [
{
"docstring": "Rijndael CBC 256",
"name": "testCBC_Rijndael_256",
"signature": "def testCBC_Rijndael_256(self)"
},
{
"docstring": "Rijndael CBC 256",
"name": "testCBC_Rijndael_variable_data",
"signature": "def testCBC_Rijndael_variable_data(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004374 | Implement the Python class `CBC_Rijndael_Test` described below.
Class description:
CBC test with Rijndael
Method signatures and docstrings:
- def testCBC_Rijndael_256(self): Rijndael CBC 256
- def testCBC_Rijndael_variable_data(self): Rijndael CBC 256 | Implement the Python class `CBC_Rijndael_Test` described below.
Class description:
CBC test with Rijndael
Method signatures and docstrings:
- def testCBC_Rijndael_256(self): Rijndael CBC 256
- def testCBC_Rijndael_variable_data(self): Rijndael CBC 256
<|skeleton|>
class CBC_Rijndael_Test:
"""CBC test with Rijnda... | ed4d80d1e6f09634c12c0c3096e39667c6642b95 | <|skeleton|>
class CBC_Rijndael_Test:
"""CBC test with Rijndael"""
def testCBC_Rijndael_256(self):
"""Rijndael CBC 256"""
<|body_0|>
def testCBC_Rijndael_variable_data(self):
"""Rijndael CBC 256"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CBC_Rijndael_Test:
"""CBC test with Rijndael"""
def testCBC_Rijndael_256(self):
"""Rijndael CBC 256"""
key = '2b7e151628aed2a6abf7158809cf4f3c'
iv = '000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f'
pt = '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb... | the_stack_v2_python_sparse | script.module.cryptolib/lib/cryptopy/cipher/cbc_test.py | gacj22/WizardGacj22 | train | 4 |
ea2382ce55bd21c048d6a53e6b3c490007344cc4 | [
"width = int(width)\nheight = int(height)\ncairo_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\nreturn (cairo_surface, width, height)",
"if self.output is not None:\n self.cairo.write_to_png(self.output)\nreturn super().finish()"
] | <|body_start_0|>
width = int(width)
height = int(height)
cairo_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
return (cairo_surface, width, height)
<|end_body_0|>
<|body_start_1|>
if self.output is not None:
self.cairo.write_to_png(self.output)
... | A surface that writes in PNG format. | PNGSurface | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PNGSurface:
"""A surface that writes in PNG format."""
def _create_surface(self, width, height):
"""Create and return ``(cairo_surface, width, height)``."""
<|body_0|>
def finish(self):
"""Read the PNG surface content."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_028729 | 20,834 | permissive | [
{
"docstring": "Create and return ``(cairo_surface, width, height)``.",
"name": "_create_surface",
"signature": "def _create_surface(self, width, height)"
},
{
"docstring": "Read the PNG surface content.",
"name": "finish",
"signature": "def finish(self)"
}
] | 2 | null | Implement the Python class `PNGSurface` described below.
Class description:
A surface that writes in PNG format.
Method signatures and docstrings:
- def _create_surface(self, width, height): Create and return ``(cairo_surface, width, height)``.
- def finish(self): Read the PNG surface content. | Implement the Python class `PNGSurface` described below.
Class description:
A surface that writes in PNG format.
Method signatures and docstrings:
- def _create_surface(self, width, height): Create and return ``(cairo_surface, width, height)``.
- def finish(self): Read the PNG surface content.
<|skeleton|>
class PNG... | e9e8db0b2a96c003d9555cc04c64e82c34233c46 | <|skeleton|>
class PNGSurface:
"""A surface that writes in PNG format."""
def _create_surface(self, width, height):
"""Create and return ``(cairo_surface, width, height)``."""
<|body_0|>
def finish(self):
"""Read the PNG surface content."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PNGSurface:
"""A surface that writes in PNG format."""
def _create_surface(self, width, height):
"""Create and return ``(cairo_surface, width, height)``."""
width = int(width)
height = int(height)
cairo_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
... | the_stack_v2_python_sparse | exostriker/lib/cairosvg_ES/surface.py | 3fon3fonov/exostriker | train | 92 |
545b23f62518fc5bc4ce459f43d1c278c5ddeb46 | [
"if config and 'connection' not in config:\n raise KeyManagerException('connection information is not provided.')\nif config and 'authority' not in config:\n raise KeyManagerException('authority information is not provided.')\nconnection_cls_ref = get_class_by_name(config['connection']['path'], config['connec... | <|body_start_0|>
if config and 'connection' not in config:
raise KeyManagerException('connection information is not provided.')
if config and 'authority' not in config:
raise KeyManagerException('authority information is not provided.')
connection_cls_ref = get_class_by_n... | AuthorityKeyManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthorityKeyManager:
def __init__(self, config):
"""Initialize a authority key manager that can request the key from an online authority key server"""
<|body_0|>
def initialize_keys(self, config):
"""Initialize needed keys for the crypto system according its roles.""... | stack_v2_sparse_classes_36k_train_028730 | 3,516 | permissive | [
{
"docstring": "Initialize a authority key manager that can request the key from an online authority key server",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Initialize needed keys for the crypto system according its roles.",
"name": "initialize_keys",
... | 3 | null | Implement the Python class `AuthorityKeyManager` described below.
Class description:
Implement the AuthorityKeyManager class.
Method signatures and docstrings:
- def __init__(self, config): Initialize a authority key manager that can request the key from an online authority key server
- def initialize_keys(self, conf... | Implement the Python class `AuthorityKeyManager` described below.
Class description:
Implement the AuthorityKeyManager class.
Method signatures and docstrings:
- def __init__(self, config): Initialize a authority key manager that can request the key from an online authority key server
- def initialize_keys(self, conf... | 64ffa2ee2e906b1bd6b3dd6aabcf6fc3de862608 | <|skeleton|>
class AuthorityKeyManager:
def __init__(self, config):
"""Initialize a authority key manager that can request the key from an online authority key server"""
<|body_0|>
def initialize_keys(self, config):
"""Initialize needed keys for the crypto system according its roles.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthorityKeyManager:
def __init__(self, config):
"""Initialize a authority key manager that can request the key from an online authority key server"""
if config and 'connection' not in config:
raise KeyManagerException('connection information is not provided.')
if config an... | the_stack_v2_python_sparse | debugging-constructs/ibmfl/crypto/keys_mng/crypto_key_mng_auth.py | SEED-VT/FedDebug | train | 8 | |
5be01831a9154025192a9f9733c96b568501898d | [
"super().__init__()\nself._handle_show_login_view = handle_show_login_view\nself.left = 10\nself.top = 10\nself.width = 1500\nself.height = 1000\nself._username_line = QLineEdit()\nself._password_line = QLineEdit()\nself._initialise()",
"msg = QMessageBox()\nuser = kks.create_user(self._username_line.text(), self... | <|body_start_0|>
super().__init__()
self._handle_show_login_view = handle_show_login_view
self.left = 10
self.top = 10
self.width = 1500
self.height = 1000
self._username_line = QLineEdit()
self._password_line = QLineEdit()
self._initialise()
<|end... | Class responsible for create user ui. Attributes: handle_show_login_view: A method to open a -login- ui. | CreateUserView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateUserView:
"""Class responsible for create user ui. Attributes: handle_show_login_view: A method to open a -login- ui."""
def __init__(self, handle_show_login_view=None):
"""Class constructor. Creates a new create user ui. Args: handle_show_login_view: A method to open a -login-... | stack_v2_sparse_classes_36k_train_028731 | 3,135 | no_license | [
{
"docstring": "Class constructor. Creates a new create user ui. Args: handle_show_login_view: A method to open a -login- ui. left, top, width, height: Page geometry values. username_line: QLineEdit widget for entering the username password_line: QLineEdit widget for entering the password",
"name": "__init_... | 3 | stack_v2_sparse_classes_30k_train_015675 | Implement the Python class `CreateUserView` described below.
Class description:
Class responsible for create user ui. Attributes: handle_show_login_view: A method to open a -login- ui.
Method signatures and docstrings:
- def __init__(self, handle_show_login_view=None): Class constructor. Creates a new create user ui.... | Implement the Python class `CreateUserView` described below.
Class description:
Class responsible for create user ui. Attributes: handle_show_login_view: A method to open a -login- ui.
Method signatures and docstrings:
- def __init__(self, handle_show_login_view=None): Class constructor. Creates a new create user ui.... | 37e859857570f398b5c237dacd283e7b00bb1b26 | <|skeleton|>
class CreateUserView:
"""Class responsible for create user ui. Attributes: handle_show_login_view: A method to open a -login- ui."""
def __init__(self, handle_show_login_view=None):
"""Class constructor. Creates a new create user ui. Args: handle_show_login_view: A method to open a -login-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateUserView:
"""Class responsible for create user ui. Attributes: handle_show_login_view: A method to open a -login- ui."""
def __init__(self, handle_show_login_view=None):
"""Class constructor. Creates a new create user ui. Args: handle_show_login_view: A method to open a -login- ui. left, to... | the_stack_v2_python_sparse | src/ui/create_user_view.py | Noissi/ot_harjoitustyo | train | 0 |
ae44af1ebfa1c9d12a6332a4bcfb71246165c8f0 | [
"f = cStringIO.StringIO()\npickler = self.pickler(f, protocol=-1)\nsession_data, callbacks, tasklets = self._dumps(pickler, data, clean_callbacks)\nset_persistent_id(pickler, lambda o: None)\npickler.dump(callbacks)\nfor t in tasklets:\n t.kill()\nreturn (session_data, f.getvalue())",
"p = self.unpickler(cStri... | <|body_start_0|>
f = cStringIO.StringIO()
pickler = self.pickler(f, protocol=-1)
session_data, callbacks, tasklets = self._dumps(pickler, data, clean_callbacks)
set_persistent_id(pickler, lambda o: None)
pickler.dump(callbacks)
for t in tasklets:
t.kill()
... | Pickle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pickle:
def dumps(self, data, clean_callbacks):
"""Serialize an objects graph In: - ``data`` -- the objects graph - ``clean_callbacks`` -- do we have to forget the old callbacks? Out: - data kept into the session - data kept into the state"""
<|body_0|>
def loads(self, sessi... | stack_v2_sparse_classes_36k_train_028732 | 4,755 | permissive | [
{
"docstring": "Serialize an objects graph In: - ``data`` -- the objects graph - ``clean_callbacks`` -- do we have to forget the old callbacks? Out: - data kept into the session - data kept into the state",
"name": "dumps",
"signature": "def dumps(self, data, clean_callbacks)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_014794 | Implement the Python class `Pickle` described below.
Class description:
Implement the Pickle class.
Method signatures and docstrings:
- def dumps(self, data, clean_callbacks): Serialize an objects graph In: - ``data`` -- the objects graph - ``clean_callbacks`` -- do we have to forget the old callbacks? Out: - data ke... | Implement the Python class `Pickle` described below.
Class description:
Implement the Pickle class.
Method signatures and docstrings:
- def dumps(self, data, clean_callbacks): Serialize an objects graph In: - ``data`` -- the objects graph - ``clean_callbacks`` -- do we have to forget the old callbacks? Out: - data ke... | 9e251f053c4edeb46b59b46d22049b29d1498727 | <|skeleton|>
class Pickle:
def dumps(self, data, clean_callbacks):
"""Serialize an objects graph In: - ``data`` -- the objects graph - ``clean_callbacks`` -- do we have to forget the old callbacks? Out: - data kept into the session - data kept into the state"""
<|body_0|>
def loads(self, sessi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pickle:
def dumps(self, data, clean_callbacks):
"""Serialize an objects graph In: - ``data`` -- the objects graph - ``clean_callbacks`` -- do we have to forget the old callbacks? Out: - data kept into the session - data kept into the state"""
f = cStringIO.StringIO()
pickler = self.pic... | the_stack_v2_python_sparse | cifrado/web/codigo/Python/virtualenv-15.1.0/NAGARE_HOME/Lib/site-packages/nagare-0.5.1-py2.7.egg/nagare/sessions/serializer.py | SanchezRuizCarlosEduardo/disor | train | 0 | |
9632bd3eb41ac33d43e35e5e9c91a8f52d15d5ff | [
"self.paths_images = paths_images\nself.labels = labels\nself.args = args",
"self.train_x, self.val_x, self.train_y, self.val_y = train_test_split(self.paths_images, self.labels, test_size=0.1, random_state=42)\npreprocess = DataPreprocessing(self.val_x, self.val_y, self.args)\nself.val_x, self.val_y, label_cl = ... | <|body_start_0|>
self.paths_images = paths_images
self.labels = labels
self.args = args
<|end_body_0|>
<|body_start_1|>
self.train_x, self.val_x, self.train_y, self.val_y = train_test_split(self.paths_images, self.labels, test_size=0.1, random_state=42)
preprocess = DataPreproce... | Operate training with a validation dataset Methods ------- launching_steps | StepsRun | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StepsRun:
"""Operate training with a validation dataset Methods ------- launching_steps"""
def __init__(self, paths_images: list, labels: list, args):
"""Class initialisation Parameters ---------- paths_images : list list of paths to selected images labels : list list of labels (str)... | stack_v2_sparse_classes_36k_train_028733 | 4,620 | no_license | [
{
"docstring": "Class initialisation Parameters ---------- paths_images : list list of paths to selected images labels : list list of labels (str) corresponding to the images paths args : arguments parser list of user arguments",
"name": "__init__",
"signature": "def __init__(self, paths_images: list, l... | 2 | null | Implement the Python class `StepsRun` described below.
Class description:
Operate training with a validation dataset Methods ------- launching_steps
Method signatures and docstrings:
- def __init__(self, paths_images: list, labels: list, args): Class initialisation Parameters ---------- paths_images : list list of pa... | Implement the Python class `StepsRun` described below.
Class description:
Operate training with a validation dataset Methods ------- launching_steps
Method signatures and docstrings:
- def __init__(self, paths_images: list, labels: list, args): Class initialisation Parameters ---------- paths_images : list list of pa... | 227641cc02f5c3aef04f3c27cbfc316382041ae0 | <|skeleton|>
class StepsRun:
"""Operate training with a validation dataset Methods ------- launching_steps"""
def __init__(self, paths_images: list, labels: list, args):
"""Class initialisation Parameters ---------- paths_images : list list of paths to selected images labels : list list of labels (str)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StepsRun:
"""Operate training with a validation dataset Methods ------- launching_steps"""
def __init__(self, paths_images: list, labels: list, args):
"""Class initialisation Parameters ---------- paths_images : list list of paths to selected images labels : list list of labels (str) correspondin... | the_stack_v2_python_sparse | yotta_p2/bj-computer-vision/masked_face/domain/run_selection.py | j-bd/various_exs | train | 0 |
f95f5be057373c177010bf10de34c69f77d9bbc1 | [
"self.volume = self.blockstorage_behavior.create_available_volume(size=self.volume_size, volume_type=self.volume_type, timeout=self.volume_create_timeout)\nself.resources.add(self.volume.id_, self.blockstorage_client.delete_volume)\nself.device = '/dev/xvdm'\nself.mount_directory = '/mnt/test'\nself.filesystem_type... | <|body_start_0|>
self.volume = self.blockstorage_behavior.create_available_volume(size=self.volume_size, volume_type=self.volume_type, timeout=self.volume_create_timeout)
self.resources.add(self.volume.id_, self.blockstorage_client.delete_volume)
self.device = '/dev/xvdm'
self.mount_dire... | CreateVolumeServerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateVolumeServerTest:
def test_attach_volume_to_server_from_volume(self):
"""Verify volume attachment works for "boot from volume" servers. Will create an available volume to be used in attaching the volume to a server and then waiting for the volume status to become "in-use" or timeou... | stack_v2_sparse_classes_36k_train_028734 | 5,450 | permissive | [
{
"docstring": "Verify volume attachment works for \"boot from volume\" servers. Will create an available volume to be used in attaching the volume to a server and then waiting for the volume status to become \"in-use\" or timeout.",
"name": "test_attach_volume_to_server_from_volume",
"signature": "def ... | 2 | null | Implement the Python class `CreateVolumeServerTest` described below.
Class description:
Implement the CreateVolumeServerTest class.
Method signatures and docstrings:
- def test_attach_volume_to_server_from_volume(self): Verify volume attachment works for "boot from volume" servers. Will create an available volume to ... | Implement the Python class `CreateVolumeServerTest` described below.
Class description:
Implement the CreateVolumeServerTest class.
Method signatures and docstrings:
- def test_attach_volume_to_server_from_volume(self): Verify volume attachment works for "boot from volume" servers. Will create an available volume to ... | 30f0e64672676c3f90b4a582fe90fac6621475b3 | <|skeleton|>
class CreateVolumeServerTest:
def test_attach_volume_to_server_from_volume(self):
"""Verify volume attachment works for "boot from volume" servers. Will create an available volume to be used in attaching the volume to a server and then waiting for the volume status to become "in-use" or timeou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateVolumeServerTest:
def test_attach_volume_to_server_from_volume(self):
"""Verify volume attachment works for "boot from volume" servers. Will create an available volume to be used in attaching the volume to a server and then waiting for the volume status to become "in-use" or timeout."""
... | the_stack_v2_python_sparse | cloudroast/compute/integration/volumes/boot_from_volume/v2/test_create_volume_server.py | RULCSoft/cloudroast | train | 1 | |
3e984d9a2a2ec4e27a0aea2c192b203cfd6d757b | [
"self.head = None\nself.tail = None\nself._counter = 0\nif hasattr(iterable, '__iter__') or isinstance(iterable, str):\n for item in iterable:\n self.insert(item)",
"new_node = Node(val)\nif self.tail is None:\n self.head = new_node\n self.tail = new_node\nelse:\n self.tail.next = new_node\n ... | <|body_start_0|>
self.head = None
self.tail = None
self._counter = 0
if hasattr(iterable, '__iter__') or isinstance(iterable, str):
for item in iterable:
self.insert(item)
<|end_body_0|>
<|body_start_1|>
new_node = Node(val)
if self.tail is No... | A Line of Nodes. | PQ | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PQ:
"""A Line of Nodes."""
def __init__(self, iterable=()):
"""Create an empty queue."""
<|body_0|>
def insert(self, val):
"""Add a node to the tail of the queue."""
<|body_1|>
def return_list(self):
"""To match the kata request."""
<... | stack_v2_sparse_classes_36k_train_028735 | 2,352 | permissive | [
{
"docstring": "Create an empty queue.",
"name": "__init__",
"signature": "def __init__(self, iterable=())"
},
{
"docstring": "Add a node to the tail of the queue.",
"name": "insert",
"signature": "def insert(self, val)"
},
{
"docstring": "To match the kata request.",
"name":... | 3 | stack_v2_sparse_classes_30k_train_013445 | Implement the Python class `PQ` described below.
Class description:
A Line of Nodes.
Method signatures and docstrings:
- def __init__(self, iterable=()): Create an empty queue.
- def insert(self, val): Add a node to the tail of the queue.
- def return_list(self): To match the kata request. | Implement the Python class `PQ` described below.
Class description:
A Line of Nodes.
Method signatures and docstrings:
- def __init__(self, iterable=()): Create an empty queue.
- def insert(self, val): Add a node to the tail of the queue.
- def return_list(self): To match the kata request.
<|skeleton|>
class PQ:
... | 3bdce2b5d12df612e7c8f2e2b8b5ebe16a653712 | <|skeleton|>
class PQ:
"""A Line of Nodes."""
def __init__(self, iterable=()):
"""Create an empty queue."""
<|body_0|>
def insert(self, val):
"""Add a node to the tail of the queue."""
<|body_1|>
def return_list(self):
"""To match the kata request."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PQ:
"""A Line of Nodes."""
def __init__(self, iterable=()):
"""Create an empty queue."""
self.head = None
self.tail = None
self._counter = 0
if hasattr(iterable, '__iter__') or isinstance(iterable, str):
for item in iterable:
self.insert... | the_stack_v2_python_sparse | sort_cards/sort_cards.py | philipwerner/code-katas | train | 0 |
38ea641fe30961546917334e3e72df665dc2ba99 | [
"nums1_copy = nums1[:]\ni, j = (0, 0)\nwhile i < m and j < n:\n if nums1_copy[i] < nums2[j]:\n nums1[i + j] = nums1_copy[i]\n i += 1\n else:\n nums1[i + j] = nums2[j]\n j += 1\nif i == m:\n nums1[i + j:] = nums2[j:]\nif j == n:\n nums1[i + j:] = nums1_copy[i:m]",
"i = m - 1... | <|body_start_0|>
nums1_copy = nums1[:]
i, j = (0, 0)
while i < m and j < n:
if nums1_copy[i] < nums2[j]:
nums1[i + j] = nums1_copy[i]
i += 1
else:
nums1[i + j] = nums2[j]
j += 1
if i == m:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge_1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""1. 双指针,从左向右,需要额外的辅助数组"""
<|body_0|>
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""2. 双指针:从右向左填充,不需要额外空间"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_028736 | 2,186 | no_license | [
{
"docstring": "1. 双指针,从左向右,需要额外的辅助数组",
"name": "merge_1",
"signature": "def merge_1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None"
},
{
"docstring": "2. 双指针:从右向左填充,不需要额外空间",
"name": "merge",
"signature": "def merge(self, nums1: List[int], m: int, nums2: List[int], n:... | 2 | stack_v2_sparse_classes_30k_val_000781 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge_1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 1. 双指针,从左向右,需要额外的辅助数组
- def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge_1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 1. 双指针,从左向右,需要额外的辅助数组
- def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def merge_1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""1. 双指针,从左向右,需要额外的辅助数组"""
<|body_0|>
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""2. 双指针:从右向左填充,不需要额外空间"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def merge_1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""1. 双指针,从左向右,需要额外的辅助数组"""
nums1_copy = nums1[:]
i, j = (0, 0)
while i < m and j < n:
if nums1_copy[i] < nums2[j]:
nums1[i + j] = nums1_copy[i]
... | the_stack_v2_python_sparse | 01-array/88.合并两个有序数组.py | xiaoruijiang/algorithm | train | 0 | |
ba008f71ec629db5107a315f0747981d2faac79c | [
"self.ID = trial_nr\nself.bar_pass_direction_at_TR = bar_pass_direction_at_TR\nself.bar_midpoint_at_TR = bar_midpoint_at_TR\nself.session = session\nself.phase_durations = phase_durations\nself.phase_names = phase_names\nsuper().__init__(session, trial_nr, phase_durations, phase_names, *args, verbose=False, **kwarg... | <|body_start_0|>
self.ID = trial_nr
self.bar_pass_direction_at_TR = bar_pass_direction_at_TR
self.bar_midpoint_at_TR = bar_midpoint_at_TR
self.session = session
self.phase_durations = phase_durations
self.phase_names = phase_names
super().__init__(session, trial_n... | PRFTrial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PRFTrial:
def __init__(self, session, trial_nr, bar_pass_direction_at_TR, bar_midpoint_at_TR, phase_durations, phase_names, timing='seconds', *args, **kwargs):
"""Initializes a PRFTrial object. Parameters ---------- session : exptools Session object A Session object (needed for metadata)... | stack_v2_sparse_classes_36k_train_028737 | 20,707 | no_license | [
{
"docstring": "Initializes a PRFTrial object. Parameters ---------- session : exptools Session object A Session object (needed for metadata) trial_nr: int Trial nr of trial phase_durations : array-like List/tuple/array with phase durations phase_names : array-like List/tuple/array with names for phases (only f... | 3 | stack_v2_sparse_classes_30k_train_019464 | Implement the Python class `PRFTrial` described below.
Class description:
Implement the PRFTrial class.
Method signatures and docstrings:
- def __init__(self, session, trial_nr, bar_pass_direction_at_TR, bar_midpoint_at_TR, phase_durations, phase_names, timing='seconds', *args, **kwargs): Initializes a PRFTrial objec... | Implement the Python class `PRFTrial` described below.
Class description:
Implement the PRFTrial class.
Method signatures and docstrings:
- def __init__(self, session, trial_nr, bar_pass_direction_at_TR, bar_midpoint_at_TR, phase_durations, phase_names, timing='seconds', *args, **kwargs): Initializes a PRFTrial objec... | 41fd68e93607570c2f71c33cf1d8bce609b229bf | <|skeleton|>
class PRFTrial:
def __init__(self, session, trial_nr, bar_pass_direction_at_TR, bar_midpoint_at_TR, phase_durations, phase_names, timing='seconds', *args, **kwargs):
"""Initializes a PRFTrial object. Parameters ---------- session : exptools Session object A Session object (needed for metadata)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PRFTrial:
def __init__(self, session, trial_nr, bar_pass_direction_at_TR, bar_midpoint_at_TR, phase_durations, phase_names, timing='seconds', *args, **kwargs):
"""Initializes a PRFTrial object. Parameters ---------- session : exptools Session object A Session object (needed for metadata) trial_nr: int... | the_stack_v2_python_sparse | experiment/trial.py | iverissimo/feature_attention_mapping | train | 0 | |
4c8961898681dc5d670d51e8930a25389efd7540 | [
"super(NetworkTester, self).__init__()\nself.testers = testers\nself._output = output\nreturn",
"if self._output is None:\n self._output = sys.stdout\nreturn self._output",
"failures = []\nfor tester in self.testers:\n datum = tester.run()\n if datum is not None:\n self.output.write(ADD_NEWLINE.... | <|body_start_0|>
super(NetworkTester, self).__init__()
self.testers = testers
self._output = output
return
<|end_body_0|>
<|body_start_1|>
if self._output is None:
self._output = sys.stdout
return self._output
<|end_body_1|>
<|body_start_2|>
failures... | A network tester runs a series of network tests. | NetworkTester | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkTester:
"""A network tester runs a series of network tests."""
def __init__(self, testers, output=None):
""":param: - `testers`: An iterable set of testers to run - `output`: An output to write data to."""
<|body_0|>
def output(self):
""":return: The outpu... | stack_v2_sparse_classes_36k_train_028738 | 1,462 | permissive | [
{
"docstring": ":param: - `testers`: An iterable set of testers to run - `output`: An output to write data to.",
"name": "__init__",
"signature": "def __init__(self, testers, output=None)"
},
{
"docstring": ":return: The output to write data to.",
"name": "output",
"signature": "def outp... | 3 | null | Implement the Python class `NetworkTester` described below.
Class description:
A network tester runs a series of network tests.
Method signatures and docstrings:
- def __init__(self, testers, output=None): :param: - `testers`: An iterable set of testers to run - `output`: An output to write data to.
- def output(self... | Implement the Python class `NetworkTester` described below.
Class description:
A network tester runs a series of network tests.
Method signatures and docstrings:
- def __init__(self, testers, output=None): :param: - `testers`: An iterable set of testers to run - `output`: An output to write data to.
- def output(self... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class NetworkTester:
"""A network tester runs a series of network tests."""
def __init__(self, testers, output=None):
""":param: - `testers`: An iterable set of testers to run - `output`: An output to write data to."""
<|body_0|>
def output(self):
""":return: The outpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetworkTester:
"""A network tester runs a series of network tests."""
def __init__(self, testers, output=None):
""":param: - `testers`: An iterable set of testers to run - `output`: An output to write data to."""
super(NetworkTester, self).__init__()
self.testers = testers
... | the_stack_v2_python_sparse | apetools/tools/networktester.py | russell-n/oldape | train | 0 |
8c1f868bada032c028300842fb31d6fe9b86214d | [
"super(self.__class__, self).__init__(callback, **kwargs)\nself.storage_type = 1\nself.follow_stock_list = []\ncf = ConfigParser.ConfigParser()\ncf.read(self.__conf_path)\nhost = cf.get('redis_info', 'host')\nport = cf.get('redis_info', 'port')\ndb = cf.get('redis_info', 'db')\npassword = cf.get('redis_info', 'pass... | <|body_start_0|>
super(self.__class__, self).__init__(callback, **kwargs)
self.storage_type = 1
self.follow_stock_list = []
cf = ConfigParser.ConfigParser()
cf.read(self.__conf_path)
host = cf.get('redis_info', 'host')
port = cf.get('redis_info', 'port')
d... | class docs | ThsOptionalUnitAnalysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThsOptionalUnitAnalysis:
"""class docs"""
def __init__(self, callback=None, **kwargs):
"""Constructor"""
<|body_0|>
def __analysis(self):
"""ananlysis"""
<|body_1|>
def __make_storage_info(self):
"""make storage info"""
<|body_2|>
<|... | stack_v2_sparse_classes_36k_train_028739 | 3,364 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, callback=None, **kwargs)"
},
{
"docstring": "ananlysis",
"name": "__analysis",
"signature": "def __analysis(self)"
},
{
"docstring": "make storage info",
"name": "__make_storage_info",
"sig... | 3 | null | Implement the Python class `ThsOptionalUnitAnalysis` described below.
Class description:
class docs
Method signatures and docstrings:
- def __init__(self, callback=None, **kwargs): Constructor
- def __analysis(self): ananlysis
- def __make_storage_info(self): make storage info | Implement the Python class `ThsOptionalUnitAnalysis` described below.
Class description:
class docs
Method signatures and docstrings:
- def __init__(self, callback=None, **kwargs): Constructor
- def __analysis(self): ananlysis
- def __make_storage_info(self): make storage info
<|skeleton|>
class ThsOptionalUnitAnaly... | fd5dff2607164f4d8a3fa1c328f72ac540c844ca | <|skeleton|>
class ThsOptionalUnitAnalysis:
"""class docs"""
def __init__(self, callback=None, **kwargs):
"""Constructor"""
<|body_0|>
def __analysis(self):
"""ananlysis"""
<|body_1|>
def __make_storage_info(self):
"""make storage info"""
<|body_2|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThsOptionalUnitAnalysis:
"""class docs"""
def __init__(self, callback=None, **kwargs):
"""Constructor"""
super(self.__class__, self).__init__(callback, **kwargs)
self.storage_type = 1
self.follow_stock_list = []
cf = ConfigParser.ConfigParser()
cf.read(self... | the_stack_v2_python_sparse | client/analysis/scheduler/analysis_models/ths_models/ths_optional_unit_analysis_model.py | flaght/mcrawler | train | 0 |
1a46db908b47d7c6395d88b40c228d52ec521b2d | [
"kw = super(StoryEventView, self).get_form_kwargs()\nkw.update({'organization': self.request.user.organization})\nreturn kw",
"context = super(StoryEventView, self).get_context_data(**kwargs)\nstory = get_object_or_404(Story, id=self.kwargs['pk'])\nevents = story.event_set.all()\nreporting_ct = story.event_set.fi... | <|body_start_0|>
kw = super(StoryEventView, self).get_form_kwargs()
kw.update({'organization': self.request.user.organization})
return kw
<|end_body_0|>
<|body_start_1|>
context = super(StoryEventView, self).get_context_data(**kwargs)
story = get_object_or_404(Story, id=self.kwa... | Display all the events associated with a story. | StoryEventView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoryEventView:
"""Display all the events associated with a story."""
def get_form_kwargs(self):
"""Pass organization to form."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Return events belonging to the project."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_028740 | 12,378 | permissive | [
{
"docstring": "Pass organization to form.",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self)"
},
{
"docstring": "Return events belonging to the project.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | null | Implement the Python class `StoryEventView` described below.
Class description:
Display all the events associated with a story.
Method signatures and docstrings:
- def get_form_kwargs(self): Pass organization to form.
- def get_context_data(self, **kwargs): Return events belonging to the project. | Implement the Python class `StoryEventView` described below.
Class description:
Display all the events associated with a story.
Method signatures and docstrings:
- def get_form_kwargs(self): Pass organization to form.
- def get_context_data(self, **kwargs): Return events belonging to the project.
<|skeleton|>
class ... | dc6bc79d450f7e2bdf59cfbcd306d05a736e4db9 | <|skeleton|>
class StoryEventView:
"""Display all the events associated with a story."""
def get_form_kwargs(self):
"""Pass organization to form."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Return events belonging to the project."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StoryEventView:
"""Display all the events associated with a story."""
def get_form_kwargs(self):
"""Pass organization to form."""
kw = super(StoryEventView, self).get_form_kwargs()
kw.update({'organization': self.request.user.organization})
return kw
def get_context_d... | the_stack_v2_python_sparse | project/editorial/views/events.py | ProjectFacet/facet | train | 25 |
9028c3217ed381dda9cc56cc3c77dd2a85c8b02c | [
"self.ip_register = Registry.test_register(ip_register)\nServer.__init__(self, service, auto_register=True, protocol_config=PROTOCOL_CONFIG, registrar=UDPRegistryClient(ip=self.ip_register, port=REGISTRY_PORT))\nself.workers = 0\nself.max_threads = max_threads\nself.lock = threading.Lock()",
"t = threading.Thread... | <|body_start_0|>
self.ip_register = Registry.test_register(ip_register)
Server.__init__(self, service, auto_register=True, protocol_config=PROTOCOL_CONFIG, registrar=UDPRegistryClient(ip=self.ip_register, port=REGISTRY_PORT))
self.workers = 0
self.max_threads = max_threads
self.l... | ServiceServer class is a rpyc server implementation to control the number of threads the server will run in parallel and to get errors during simulation | ServiceServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceServer:
"""ServiceServer class is a rpyc server implementation to control the number of threads the server will run in parallel and to get errors during simulation"""
def __init__(self, service, max_threads, ip_register):
"""Class initialization :param service: Service to serv... | stack_v2_sparse_classes_36k_train_028741 | 3,859 | no_license | [
{
"docstring": "Class initialization :param service: Service to serve on client connection :param max_threads: Integer for the maximum number of thread that the server can run in parallel",
"name": "__init__",
"signature": "def __init__(self, service, max_threads, ip_register)"
},
{
"docstring":... | 5 | stack_v2_sparse_classes_30k_train_021272 | Implement the Python class `ServiceServer` described below.
Class description:
ServiceServer class is a rpyc server implementation to control the number of threads the server will run in parallel and to get errors during simulation
Method signatures and docstrings:
- def __init__(self, service, max_threads, ip_regist... | Implement the Python class `ServiceServer` described below.
Class description:
ServiceServer class is a rpyc server implementation to control the number of threads the server will run in parallel and to get errors during simulation
Method signatures and docstrings:
- def __init__(self, service, max_threads, ip_regist... | f4f212a7533a63d1148068bacf1cc13d3f64db49 | <|skeleton|>
class ServiceServer:
"""ServiceServer class is a rpyc server implementation to control the number of threads the server will run in parallel and to get errors during simulation"""
def __init__(self, service, max_threads, ip_register):
"""Class initialization :param service: Service to serv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServiceServer:
"""ServiceServer class is a rpyc server implementation to control the number of threads the server will run in parallel and to get errors during simulation"""
def __init__(self, service, max_threads, ip_register):
"""Class initialization :param service: Service to serve on client c... | the_stack_v2_python_sparse | src/simulations/servers/serviceServer.py | mahedjaved/mouse_locomotion | train | 0 |
e61f3bf58c7816b9f347806696b8ae06278cdac5 | [
"scheduler = opt.GammaBetaDecreasingStep()\nwith self.assertRaisesRegexp(Exception, err_msg):\n scheduler(1)",
"beta = _ops.convert_to_tensor_v2(2, dtype=tf.float32)\ngamma = _ops.convert_to_tensor_v2(1, dtype=tf.float32)\nscheduler = opt.GammaBetaDecreasingStep()\nscheduler.initialize(beta, gamma)\nstep = _op... | <|body_start_0|>
scheduler = opt.GammaBetaDecreasingStep()
with self.assertRaisesRegexp(Exception, err_msg):
scheduler(1)
<|end_body_0|>
<|body_start_1|>
beta = _ops.convert_to_tensor_v2(2, dtype=tf.float32)
gamma = _ops.convert_to_tensor_v2(1, dtype=tf.float32)
sche... | GammaBeta Scheduler tests. | SchedulerTest | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedulerTest:
"""GammaBeta Scheduler tests."""
def test_bad_call(self, err_msg):
"""Test attribute of internal opt correctly rerouted to the internal opt. Args: err_msg: The expected error message from the scheduler bad call."""
<|body_0|>
def test_call(self, step, res)... | stack_v2_sparse_classes_36k_train_028742 | 18,768 | permissive | [
{
"docstring": "Test attribute of internal opt correctly rerouted to the internal opt. Args: err_msg: The expected error message from the scheduler bad call.",
"name": "test_bad_call",
"signature": "def test_bad_call(self, err_msg)"
},
{
"docstring": "Test call. Test that attribute of internal o... | 2 | null | Implement the Python class `SchedulerTest` described below.
Class description:
GammaBeta Scheduler tests.
Method signatures and docstrings:
- def test_bad_call(self, err_msg): Test attribute of internal opt correctly rerouted to the internal opt. Args: err_msg: The expected error message from the scheduler bad call.
... | Implement the Python class `SchedulerTest` described below.
Class description:
GammaBeta Scheduler tests.
Method signatures and docstrings:
- def test_bad_call(self, err_msg): Test attribute of internal opt correctly rerouted to the internal opt. Args: err_msg: The expected error message from the scheduler bad call.
... | c92610e37aa340932ed2d963813e0890035a22bc | <|skeleton|>
class SchedulerTest:
"""GammaBeta Scheduler tests."""
def test_bad_call(self, err_msg):
"""Test attribute of internal opt correctly rerouted to the internal opt. Args: err_msg: The expected error message from the scheduler bad call."""
<|body_0|>
def test_call(self, step, res)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchedulerTest:
"""GammaBeta Scheduler tests."""
def test_bad_call(self, err_msg):
"""Test attribute of internal opt correctly rerouted to the internal opt. Args: err_msg: The expected error message from the scheduler bad call."""
scheduler = opt.GammaBetaDecreasingStep()
with self... | the_stack_v2_python_sparse | tensorflow_privacy/privacy/bolt_on/optimizers_test.py | tensorflow/privacy | train | 1,881 |
495d0eb7d6e05af8f4a0ddcde6d4b35531990740 | [
"self.cap = capacity\nself.keyList = []\nself.dataDict = {}",
"if key in self.dataDict:\n for i in range(len(self.keyList)):\n if self.keyList[i] == key:\n self.keyList[i], self.keyList[-1] = (self.keyList[-1], self.keyList[i])\n break\n return self.dataDict[key]\nreturn -1",
... | <|body_start_0|>
self.cap = capacity
self.keyList = []
self.dataDict = {}
<|end_body_0|>
<|body_start_1|>
if key in self.dataDict:
for i in range(len(self.keyList)):
if self.keyList[i] == key:
self.keyList[i], self.keyList[-1] = (self.keyL... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_028743 | 1,379 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 48b43999fb7e2ed82d922e1f64ac76f8fabe4baa | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cap = capacity
self.keyList = []
self.dataDict = {}
def get(self, key):
""":type key: int :rtype: int"""
if key in self.dataDict:
for i in range(len(self.keyList)):
... | the_stack_v2_python_sparse | 146.py | saleed/LeetCode | train | 2 | |
a3a9e5c5d9af5d4f2f05f80e5f493a9c56cbe5ff | [
"super(multiheadattention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.w_q = nn.Linear(d_model, d_model, bias=False)\nself.w_k = nn.Linear(d_model, d_model, bias=False)\nself.w_v = nn.Linear(d_model, d_model, bias=False)\nself.fc = nn.Linear(d_model, d_model, bias=False)\nse... | <|body_start_0|>
super(multiheadattention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.w_q = nn.Linear(d_model, d_model, bias=False)
self.w_k = nn.Linear(d_model, d_model, bias=False)
self.w_v = nn.Linear(d_model, d_model, bias... | multiheadattention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class multiheadattention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(m... | stack_v2_sparse_classes_36k_train_028744 | 18,909 | no_license | [
{
"docstring": "Take in model size and number of heads.",
"name": "__init__",
"signature": "def __init__(self, h, d_model, dropout=0.1)"
},
{
"docstring": "Implements Figure 2",
"name": "forward",
"signature": "def forward(self, query, key, value, mask=None)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000488 | Implement the Python class `multiheadattention` described below.
Class description:
Implement the multiheadattention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure 2 | Implement the Python class `multiheadattention` described below.
Class description:
Implement the multiheadattention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure 2
<... | c43e2bb39be9f73475760fa82f389d797591b36e | <|skeleton|>
class multiheadattention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class multiheadattention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
super(multiheadattention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.w_q = nn.Linear(d_model, d_model, bias=False... | the_stack_v2_python_sparse | train/modules.py | biomed-AI/CATCaller | train | 7 | |
decf2794a0f4e882d1fcb019fa0e321897d4a7c4 | [
"LinearValueFunctionPredictor.__init__(self, **kwargs)\nOffPolicyValueFunctionPredictor.__init__(self, **kwargs)\nLambdaValueFunctionPredictor.__init__(self, **kwargs)\nself.init_vals['C'] = np.eye(len(self.init_vals['theta'])) * eps\nself.reset()",
"f0 = self.phi(s0)\nf1 = self.phi(s1)\nself._tic()\nif theta is ... | <|body_start_0|>
LinearValueFunctionPredictor.__init__(self, **kwargs)
OffPolicyValueFunctionPredictor.__init__(self, **kwargs)
LambdaValueFunctionPredictor.__init__(self, **kwargs)
self.init_vals['C'] = np.eye(len(self.init_vals['theta'])) * eps
self.reset()
<|end_body_0|>
<|bo... | recursive Implementation of Least Squared Temporal Difference Learning LSTD(\\lambda) with linear function approximation, also works in the off-policy case and uses eligibility traces for details see Scherrer, B., & Geist, M. (EWRL 2011). : Recursive Least-Squares Learning with Eligibility Traces. Algorithm 1 | LSTDLambda | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTDLambda:
"""recursive Implementation of Least Squared Temporal Difference Learning LSTD(\\lambda) with linear function approximation, also works in the off-policy case and uses eligibility traces for details see Scherrer, B., & Geist, M. (EWRL 2011). : Recursive Least-Squares Learning with Eli... | stack_v2_sparse_classes_36k_train_028745 | 16,053 | no_license | [
{
"docstring": "lam: lambda in [0, 1] specifying the tradeoff between bootstrapping and MC sampling gamma: discount factor",
"name": "__init__",
"signature": "def __init__(self, eps=1, **kwargs)"
},
{
"docstring": "rho: weight for this sample in case of off-policy learning",
"name": "update_... | 2 | stack_v2_sparse_classes_30k_train_016920 | Implement the Python class `LSTDLambda` described below.
Class description:
recursive Implementation of Least Squared Temporal Difference Learning LSTD(\\lambda) with linear function approximation, also works in the off-policy case and uses eligibility traces for details see Scherrer, B., & Geist, M. (EWRL 2011). : Re... | Implement the Python class `LSTDLambda` described below.
Class description:
recursive Implementation of Least Squared Temporal Difference Learning LSTD(\\lambda) with linear function approximation, also works in the off-policy case and uses eligibility traces for details see Scherrer, B., & Geist, M. (EWRL 2011). : Re... | f6c61e18af0c02f4c03ca1e599ae1844970bee25 | <|skeleton|>
class LSTDLambda:
"""recursive Implementation of Least Squared Temporal Difference Learning LSTD(\\lambda) with linear function approximation, also works in the off-policy case and uses eligibility traces for details see Scherrer, B., & Geist, M. (EWRL 2011). : Recursive Least-Squares Learning with Eli... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSTDLambda:
"""recursive Implementation of Least Squared Temporal Difference Learning LSTD(\\lambda) with linear function approximation, also works in the off-policy case and uses eligibility traces for details see Scherrer, B., & Geist, M. (EWRL 2011). : Recursive Least-Squares Learning with Eligibility Trac... | the_stack_v2_python_sparse | td.py | meyerd/tdlearn | train | 1 |
dc16e769196f79512709d210cb1f5274f9cf53da | [
"result = []\ni, j, carry = (len(num1) - 1, len(num2) - 1, 0)\nwhile i >= 0 or j >= 0 or carry:\n if i >= 0:\n carry += ord(num1[i]) - ord('0')\n i -= 1\n if j >= 0:\n carry += ord(num2[j]) - ord('0')\n j -= 1\n result.append(str(carry % 10))\n carry /= 10\nresult.reverse()\n... | <|body_start_0|>
result = []
i, j, carry = (len(num1) - 1, len(num2) - 1, 0)
while i >= 0 or j >= 0 or carry:
if i >= 0:
carry += ord(num1[i]) - ord('0')
i -= 1
if j >= 0:
carry += ord(num2[j]) - ord('0')
j -... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addStrings(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_0|>
def addStrings2(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
... | stack_v2_sparse_classes_36k_train_028746 | 2,315 | permissive | [
{
"docstring": ":type num1: str :type num2: str :rtype: str",
"name": "addStrings",
"signature": "def addStrings(self, num1, num2)"
},
{
"docstring": ":type num1: str :type num2: str :rtype: str",
"name": "addStrings2",
"signature": "def addStrings2(self, num1, num2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008179 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addStrings(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def addStrings2(self, num1, num2): :type num1: str :type num2: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addStrings(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def addStrings2(self, num1, num2): :type num1: str :type num2: str :rtype: str
<|skeleton|>
class... | 0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c | <|skeleton|>
class Solution:
def addStrings(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_0|>
def addStrings2(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addStrings(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
result = []
i, j, carry = (len(num1) - 1, len(num2) - 1, 0)
while i >= 0 or j >= 0 or carry:
if i >= 0:
carry += ord(num1[i]) - ord('0')
i -... | the_stack_v2_python_sparse | cs15211/AddStrings.py | JulyKikuAkita/PythonPrac | train | 1 | |
ce74b113a86905b244a95cc0841316fd2ad1264a | [
"def decorated_view(request: HttpRequest, course_id: int, *args, **kwargs):\n course = Course.objects.get(id=course_id)\n user = request.user\n is_instructor = user in course.instructors.all()\n is_student = user in course.students.all()\n if is_instructor or is_student:\n return view(request,... | <|body_start_0|>
def decorated_view(request: HttpRequest, course_id: int, *args, **kwargs):
course = Course.objects.get(id=course_id)
user = request.user
is_instructor = user in course.instructors.all()
is_student = user in course.students.all()
if is_... | SearchView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchView:
def permissioned(view):
"""View decorator that checks if a user has permission to access/edit the post specified in the url."""
<|body_0|>
def post(self, request: HttpRequest, course_id: int) -> HttpResponse:
"""Post function for searching in courses"""
... | stack_v2_sparse_classes_36k_train_028747 | 2,222 | permissive | [
{
"docstring": "View decorator that checks if a user has permission to access/edit the post specified in the url.",
"name": "permissioned",
"signature": "def permissioned(view)"
},
{
"docstring": "Post function for searching in courses",
"name": "post",
"signature": "def post(self, reque... | 2 | stack_v2_sparse_classes_30k_train_005171 | Implement the Python class `SearchView` described below.
Class description:
Implement the SearchView class.
Method signatures and docstrings:
- def permissioned(view): View decorator that checks if a user has permission to access/edit the post specified in the url.
- def post(self, request: HttpRequest, course_id: in... | Implement the Python class `SearchView` described below.
Class description:
Implement the SearchView class.
Method signatures and docstrings:
- def permissioned(view): View decorator that checks if a user has permission to access/edit the post specified in the url.
- def post(self, request: HttpRequest, course_id: in... | 6b688c28c79e56df5cc667d704db72ba30141f7a | <|skeleton|>
class SearchView:
def permissioned(view):
"""View decorator that checks if a user has permission to access/edit the post specified in the url."""
<|body_0|>
def post(self, request: HttpRequest, course_id: int) -> HttpResponse:
"""Post function for searching in courses"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchView:
def permissioned(view):
"""View decorator that checks if a user has permission to access/edit the post specified in the url."""
def decorated_view(request: HttpRequest, course_id: int, *args, **kwargs):
course = Course.objects.get(id=course_id)
user = reques... | the_stack_v2_python_sparse | backend/api/views/SearchView.py | CaoRuiming/CS1320-Final-Project | train | 0 | |
758e45e6b43d7eaf659da57bc76b20160280fef5 | [
"meta = {}\nfor k, v in self.__dict__.items():\n if isinstance(v, np.ndarray):\n meta[k] = v.tolist()\n else:\n meta[k] = v\nreturn meta",
"meta = {}\nfor k, v in doc.items():\n if k == 'classes_':\n self.classes_ = np.array(v)\n continue\n meta[k] = v\nself.__dict__.update... | <|body_start_0|>
meta = {}
for k, v in self.__dict__.items():
if isinstance(v, np.ndarray):
meta[k] = v.tolist()
else:
meta[k] = v
return meta
<|end_body_0|>
<|body_start_1|>
meta = {}
for k, v in doc.items():
i... | Label encoder with JSON serialization methods. | XGBoostLabelEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XGBoostLabelEncoder:
"""Label encoder with JSON serialization methods."""
def to_json(self) -> Dict:
"""Returns a JSON compatible dictionary"""
<|body_0|>
def from_json(self, doc: Dict) -> None:
"""Load the encoder back from a JSON compatible dict."""
<|b... | stack_v2_sparse_classes_36k_train_028748 | 6,886 | permissive | [
{
"docstring": "Returns a JSON compatible dictionary",
"name": "to_json",
"signature": "def to_json(self) -> Dict"
},
{
"docstring": "Load the encoder back from a JSON compatible dict.",
"name": "from_json",
"signature": "def from_json(self, doc: Dict) -> None"
}
] | 2 | null | Implement the Python class `XGBoostLabelEncoder` described below.
Class description:
Label encoder with JSON serialization methods.
Method signatures and docstrings:
- def to_json(self) -> Dict: Returns a JSON compatible dictionary
- def from_json(self, doc: Dict) -> None: Load the encoder back from a JSON compatible... | Implement the Python class `XGBoostLabelEncoder` described below.
Class description:
Label encoder with JSON serialization methods.
Method signatures and docstrings:
- def to_json(self) -> Dict: Returns a JSON compatible dictionary
- def from_json(self, doc: Dict) -> None: Load the encoder back from a JSON compatible... | f5bf7ad4b5b06449e93500d98f41f0c9793db065 | <|skeleton|>
class XGBoostLabelEncoder:
"""Label encoder with JSON serialization methods."""
def to_json(self) -> Dict:
"""Returns a JSON compatible dictionary"""
<|body_0|>
def from_json(self, doc: Dict) -> None:
"""Load the encoder back from a JSON compatible dict."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XGBoostLabelEncoder:
"""Label encoder with JSON serialization methods."""
def to_json(self) -> Dict:
"""Returns a JSON compatible dictionary"""
meta = {}
for k, v in self.__dict__.items():
if isinstance(v, np.ndarray):
meta[k] = v.tolist()
e... | the_stack_v2_python_sparse | python-package/xgboost/compat.py | rapidsai/xgboost | train | 30 |
fad45349477c4720b55af5af71e50dfc643c06bd | [
"if not matrix or not matrix[0]:\n return False\nxs, xe, ys, ye = (0, len(matrix), 0, len(matrix[0]))\nwhile True:\n row_s, col_s = (map(lambda line: line[ys], matrix), matrix[xs])\n row_s_index = bisect.bisect_left(row_s, target, xs, xe)\n if row_s_index != xe and row_s[row_s_index] == target:\n ... | <|body_start_0|>
if not matrix or not matrix[0]:
return False
xs, xe, ys, ye = (0, len(matrix), 0, len(matrix[0]))
while True:
row_s, col_s = (map(lambda line: line[ys], matrix), matrix[xs])
row_s_index = bisect.bisect_left(row_s, target, xs, xe)
i... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix2(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_028749 | 2,041 | permissive | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix2",
"signature": "def search... | 2 | stack_v2_sparse_classes_30k_train_002694 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix2(self, matrix, target): :type matrix: List[List[int]] :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix2(self, matrix, target): :type matrix: List[List[int]] :typ... | c8bf33af30569177c5276ffcd72a8d93ba4c402a | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix2(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if not matrix or not matrix[0]:
return False
xs, xe, ys, ye = (0, len(matrix), 0, len(matrix[0]))
while True:
row_s, col_s = (map(lambda ... | the_stack_v2_python_sparse | 201-300/231-240/240-search2DArray2/search2DArray2.py | xuychen/Leetcode | train | 0 | |
de8e0ba92c1c3349519a69f6900044727f35e11c | [
"command = command.split(' ')\nprocess = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\ntry:\n output, errors = process.communicate(timeout=8)\n output = output.split('\\n')\n process.terminate()\nexcept subprocess.TimeoutExpired:\n process.kill()\n ... | <|body_start_0|>
command = command.split(' ')
process = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
output, errors = process.communicate(timeout=8)
output = output.split('\n')
process.terminate()
... | Commands that evaluate commands.. | Evaluation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Evaluation:
"""Commands that evaluate commands.."""
async def sh(self, ctx, *, command):
"""Execute a system command. Bot owner only."""
<|body_0|>
async def _eval(self, ctx, *, expression):
"""Evaluate a Python expression. Bot owner only."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_028750 | 2,006 | permissive | [
{
"docstring": "Execute a system command. Bot owner only.",
"name": "sh",
"signature": "async def sh(self, ctx, *, command)"
},
{
"docstring": "Evaluate a Python expression. Bot owner only.",
"name": "_eval",
"signature": "async def _eval(self, ctx, *, expression)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018868 | Implement the Python class `Evaluation` described below.
Class description:
Commands that evaluate commands..
Method signatures and docstrings:
- async def sh(self, ctx, *, command): Execute a system command. Bot owner only.
- async def _eval(self, ctx, *, expression): Evaluate a Python expression. Bot owner only. | Implement the Python class `Evaluation` described below.
Class description:
Commands that evaluate commands..
Method signatures and docstrings:
- async def sh(self, ctx, *, command): Execute a system command. Bot owner only.
- async def _eval(self, ctx, *, expression): Evaluate a Python expression. Bot owner only.
<... | 3a456ad06814181d13d4aabefc151756c55444f4 | <|skeleton|>
class Evaluation:
"""Commands that evaluate commands.."""
async def sh(self, ctx, *, command):
"""Execute a system command. Bot owner only."""
<|body_0|>
async def _eval(self, ctx, *, expression):
"""Evaluate a Python expression. Bot owner only."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Evaluation:
"""Commands that evaluate commands.."""
async def sh(self, ctx, *, command):
"""Execute a system command. Bot owner only."""
command = command.split(' ')
process = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
... | the_stack_v2_python_sparse | cogs/eval.py | sokcheng/Kitsuchan-NG | train | 1 |
6fe9d683ac6844a8fbb28fd4b621a55a9c1813f3 | [
"if 'query' in self.request.GET:\n if self.request.GET['query'] == '':\n messages.warning(self.request, \"You didn't search for anything\")\n return Product.objects.all().order_by('-stock', '-popularity')\n else:\n self.user_query = self.request.GET['query']\n self.vector = SearchV... | <|body_start_0|>
if 'query' in self.request.GET:
if self.request.GET['query'] == '':
messages.warning(self.request, "You didn't search for anything")
return Product.objects.all().order_by('-stock', '-popularity')
else:
self.user_query = sel... | Renders the home page with a Products List. If there is a GET request, performs a search. | ProductListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductListView:
"""Renders the home page with a Products List. If there is a GET request, performs a search."""
def get_queryset(self):
"""Returns either all Products or a query appropriately."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Adds all neces... | stack_v2_sparse_classes_36k_train_028751 | 4,612 | no_license | [
{
"docstring": "Returns either all Products or a query appropriately.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Adds all necessary information to the context",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010280 | Implement the Python class `ProductListView` described below.
Class description:
Renders the home page with a Products List. If there is a GET request, performs a search.
Method signatures and docstrings:
- def get_queryset(self): Returns either all Products or a query appropriately.
- def get_context_data(self, **kw... | Implement the Python class `ProductListView` described below.
Class description:
Renders the home page with a Products List. If there is a GET request, performs a search.
Method signatures and docstrings:
- def get_queryset(self): Returns either all Products or a query appropriately.
- def get_context_data(self, **kw... | 3bcbe14b49ba910a45e23967cad54a37a62ae563 | <|skeleton|>
class ProductListView:
"""Renders the home page with a Products List. If there is a GET request, performs a search."""
def get_queryset(self):
"""Returns either all Products or a query appropriately."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Adds all neces... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductListView:
"""Renders the home page with a Products List. If there is a GET request, performs a search."""
def get_queryset(self):
"""Returns either all Products or a query appropriately."""
if 'query' in self.request.GET:
if self.request.GET['query'] == '':
... | the_stack_v2_python_sparse | products/views.py | Code-Institute-Submissions/neverlost-thrift | train | 0 |
0a709c3f0eec183fc3c8fb349c6ed5fc1322b43b | [
"if len(queryset) > 1:\n self.message_user(request, 'You can only choose one certificate.', level=messages.ERROR)\n return None\nresponse = HttpResponse(content_type='text/plain')\ncert = queryset.first()\nresponse.write(crypto.dump_certificate(crypto.FILETYPE_TEXT, cert.get_certificate()))\nreturn response",... | <|body_start_0|>
if len(queryset) > 1:
self.message_user(request, 'You can only choose one certificate.', level=messages.ERROR)
return None
response = HttpResponse(content_type='text/plain')
cert = queryset.first()
response.write(crypto.dump_certificate(crypto.FIL... | Admin model for certificates. | CertificateAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CertificateAdmin:
"""Admin model for certificates."""
def view_certificate(self, request, queryset):
"""View a text version of the certificate."""
<|body_0|>
def download_certificate(self, request, queryset):
"""Download a certificate."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_028752 | 4,814 | permissive | [
{
"docstring": "View a text version of the certificate.",
"name": "view_certificate",
"signature": "def view_certificate(self, request, queryset)"
},
{
"docstring": "Download a certificate.",
"name": "download_certificate",
"signature": "def download_certificate(self, request, queryset)"... | 2 | stack_v2_sparse_classes_30k_train_010012 | Implement the Python class `CertificateAdmin` described below.
Class description:
Admin model for certificates.
Method signatures and docstrings:
- def view_certificate(self, request, queryset): View a text version of the certificate.
- def download_certificate(self, request, queryset): Download a certificate. | Implement the Python class `CertificateAdmin` described below.
Class description:
Admin model for certificates.
Method signatures and docstrings:
- def view_certificate(self, request, queryset): View a text version of the certificate.
- def download_certificate(self, request, queryset): Download a certificate.
<|ske... | 1c3608e0a02aaba9bd8594d80a247d692cbd04ad | <|skeleton|>
class CertificateAdmin:
"""Admin model for certificates."""
def view_certificate(self, request, queryset):
"""View a text version of the certificate."""
<|body_0|>
def download_certificate(self, request, queryset):
"""Download a certificate."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CertificateAdmin:
"""Admin model for certificates."""
def view_certificate(self, request, queryset):
"""View a text version of the certificate."""
if len(queryset) > 1:
self.message_user(request, 'You can only choose one certificate.', level=messages.ERROR)
return ... | the_stack_v2_python_sparse | webca/webca/web/admin.py | jesusfer/webca | train | 0 |
fcd0455b4f24449edfe52e07cc065d4c2efa7aae | [
"StochasticGradientDescent.__init__(self, loss)\nself.beta_m = beta_m\nself.beta_v = beta_v\nself.epsilon = epsilon\nself.alpha = alpha\nself.beta_m_ac = beta_m\nself.beta_v_ac = beta_v\nself.mE = [0 for _ in self.Q.model.w]\nself.vE = [0 for _ in self.Q.model.w]",
"self.Q.randomDataPoint()\nself.beta_m_ac *= sel... | <|body_start_0|>
StochasticGradientDescent.__init__(self, loss)
self.beta_m = beta_m
self.beta_v = beta_v
self.epsilon = epsilon
self.alpha = alpha
self.beta_m_ac = beta_m
self.beta_v_ac = beta_v
self.mE = [0 for _ in self.Q.model.w]
self.vE = [0 f... | Implementation of Adam. | AdamSGD | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdamSGD:
"""Implementation of Adam."""
def __init__(self, loss, beta_m=1 - 0.1, beta_v=1 - 0.001, epsilon=1e-08, alpha=0.01):
"""loss: the loss function beta_m: decay parameter for the average m beta_v: decay parameter for the average v epsilon: safety parameter (to avoid division by... | stack_v2_sparse_classes_36k_train_028753 | 2,172 | permissive | [
{
"docstring": "loss: the loss function beta_m: decay parameter for the average m beta_v: decay parameter for the average v epsilon: safety parameter (to avoid division by 0) alpha: a learning rate that multiplies the rate.",
"name": "__init__",
"signature": "def __init__(self, loss, beta_m=1 - 0.1, bet... | 2 | stack_v2_sparse_classes_30k_train_020588 | Implement the Python class `AdamSGD` described below.
Class description:
Implementation of Adam.
Method signatures and docstrings:
- def __init__(self, loss, beta_m=1 - 0.1, beta_v=1 - 0.001, epsilon=1e-08, alpha=0.01): loss: the loss function beta_m: decay parameter for the average m beta_v: decay parameter for the ... | Implement the Python class `AdamSGD` described below.
Class description:
Implementation of Adam.
Method signatures and docstrings:
- def __init__(self, loss, beta_m=1 - 0.1, beta_v=1 - 0.001, epsilon=1e-08, alpha=0.01): loss: the loss function beta_m: decay parameter for the average m beta_v: decay parameter for the ... | e12ea464e7845793c88adfff6da4c8454099c03b | <|skeleton|>
class AdamSGD:
"""Implementation of Adam."""
def __init__(self, loss, beta_m=1 - 0.1, beta_v=1 - 0.001, epsilon=1e-08, alpha=0.01):
"""loss: the loss function beta_m: decay parameter for the average m beta_v: decay parameter for the average v epsilon: safety parameter (to avoid division by... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdamSGD:
"""Implementation of Adam."""
def __init__(self, loss, beta_m=1 - 0.1, beta_v=1 - 0.001, epsilon=1e-08, alpha=0.01):
"""loss: the loss function beta_m: decay parameter for the average m beta_v: decay parameter for the average v epsilon: safety parameter (to avoid division by 0) alpha: a ... | the_stack_v2_python_sparse | Optimization/FitData/Stochastic-Gradient-Descent/python/SGD/AdamSGD.py | dkaramit/ASAP | train | 2 |
beb38cc997755610caf12d1abca076ead5e0cf6b | [
"super().__init__()\nself.scene_encoder = ModuleList([Sequential(Conv2d(scene_embedding_channels, out_channels, 1), ReLU(True), Conv2d(out_channels, out_channels, 1)) for _ in range(len(in_channels_list))])\nself.content_encoders = ModuleList()\nself.feature_reencoders = ModuleList()\nfor c in in_channels_list:\n ... | <|body_start_0|>
super().__init__()
self.scene_encoder = ModuleList([Sequential(Conv2d(scene_embedding_channels, out_channels, 1), ReLU(True), Conv2d(out_channels, out_channels, 1)) for _ in range(len(in_channels_list))])
self.content_encoders = ModuleList()
self.feature_reencoders = Mod... | F-S Relation module. | _FSRelation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _FSRelation:
"""F-S Relation module."""
def __init__(self, scene_embedding_channels: int, in_channels_list: list[int], out_channels: int) -> None:
"""Initialize the _FSRelation module. Args: scene_embedding_channels: number of scene embedding channels in_channels_list: a list of inpu... | stack_v2_sparse_classes_36k_train_028754 | 8,033 | permissive | [
{
"docstring": "Initialize the _FSRelation module. Args: scene_embedding_channels: number of scene embedding channels in_channels_list: a list of input channels out_channels: number of output channels",
"name": "__init__",
"signature": "def __init__(self, scene_embedding_channels: int, in_channels_list:... | 2 | null | Implement the Python class `_FSRelation` described below.
Class description:
F-S Relation module.
Method signatures and docstrings:
- def __init__(self, scene_embedding_channels: int, in_channels_list: list[int], out_channels: int) -> None: Initialize the _FSRelation module. Args: scene_embedding_channels: number of ... | Implement the Python class `_FSRelation` described below.
Class description:
F-S Relation module.
Method signatures and docstrings:
- def __init__(self, scene_embedding_channels: int, in_channels_list: list[int], out_channels: int) -> None: Initialize the _FSRelation module. Args: scene_embedding_channels: number of ... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class _FSRelation:
"""F-S Relation module."""
def __init__(self, scene_embedding_channels: int, in_channels_list: list[int], out_channels: int) -> None:
"""Initialize the _FSRelation module. Args: scene_embedding_channels: number of scene embedding channels in_channels_list: a list of inpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _FSRelation:
"""F-S Relation module."""
def __init__(self, scene_embedding_channels: int, in_channels_list: list[int], out_channels: int) -> None:
"""Initialize the _FSRelation module. Args: scene_embedding_channels: number of scene embedding channels in_channels_list: a list of input channels ou... | the_stack_v2_python_sparse | torchgeo/models/farseg.py | microsoft/torchgeo | train | 1,724 |
3b3261318f99b609e8cb300d7c6a0d8414d7805b | [
"super().__init__(parent, **kwargs)\nself.active = False\nself.bind('<Button-1>', self.toggle)",
"if active is not None:\n self.active = active\nelse:\n self.active = not self.active\nbg = BUTTON_ACTIVE_BG if self.active else BUTTON_ACTIVE_FG\nfg = BUTTON_ACTIVE_FG if self.active else BUTTON_ACTIVE_BG\nself... | <|body_start_0|>
super().__init__(parent, **kwargs)
self.active = False
self.bind('<Button-1>', self.toggle)
<|end_body_0|>
<|body_start_1|>
if active is not None:
self.active = active
else:
self.active = not self.active
bg = BUTTON_ACTIVE_BG if s... | ToggleButton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToggleButton:
def __init__(self, parent, **kwargs):
"""Special button to change modes and stay in one state."""
<|body_0|>
def toggle(self, event=None, active=None):
"""Call with no args to toggle or True/False to set button state."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_028755 | 18,668 | no_license | [
{
"docstring": "Special button to change modes and stay in one state.",
"name": "__init__",
"signature": "def __init__(self, parent, **kwargs)"
},
{
"docstring": "Call with no args to toggle or True/False to set button state.",
"name": "toggle",
"signature": "def toggle(self, event=None,... | 2 | stack_v2_sparse_classes_30k_train_013128 | Implement the Python class `ToggleButton` described below.
Class description:
Implement the ToggleButton class.
Method signatures and docstrings:
- def __init__(self, parent, **kwargs): Special button to change modes and stay in one state.
- def toggle(self, event=None, active=None): Call with no args to toggle or Tr... | Implement the Python class `ToggleButton` described below.
Class description:
Implement the ToggleButton class.
Method signatures and docstrings:
- def __init__(self, parent, **kwargs): Special button to change modes and stay in one state.
- def toggle(self, event=None, active=None): Call with no args to toggle or Tr... | 04df21fce6a8ec3e72530726f85bc88c6f80674a | <|skeleton|>
class ToggleButton:
def __init__(self, parent, **kwargs):
"""Special button to change modes and stay in one state."""
<|body_0|>
def toggle(self, event=None, active=None):
"""Call with no args to toggle or True/False to set button state."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ToggleButton:
def __init__(self, parent, **kwargs):
"""Special button to change modes and stay in one state."""
super().__init__(parent, **kwargs)
self.active = False
self.bind('<Button-1>', self.toggle)
def toggle(self, event=None, active=None):
"""Call with no ar... | the_stack_v2_python_sparse | drawtools/view.py | jeffriesd/dsDraw-python | train | 0 | |
db9a4c7c6178e2601f23285786710f08286f9338 | [
"if source_values is None or any((source_value is None for source_value in source_values)):\n return None\nelse:\n return [float(sv) for sv in source_values]",
"assert all([self.is_valid_name(name) for name in names]), 'name not valid'\nsuper().__init__(base_url=base_url or api_url(), write_key=write_key, v... | <|body_start_0|>
if source_values is None or any((source_value is None for source_value in source_values)):
return None
else:
return [float(sv) for sv in source_values]
<|end_body_0|>
<|body_start_1|>
assert all([self.is_valid_name(name) for name in names]), 'name not va... | MultiPoll | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiPoll:
def determine_next_values(self, source_values):
"""Should receive raw source data and decides what to send, if anything :param source_values [ float ] or whatever type is returned by self.func. Simplest would be [ float ] :returns [ float ] or None"""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_028756 | 13,481 | no_license | [
{
"docstring": "Should receive raw source data and decides what to send, if anything :param source_values [ float ] or whatever type is returned by self.func. Simplest would be [ float ] :returns [ float ] or None",
"name": "determine_next_values",
"signature": "def determine_next_values(self, source_va... | 3 | stack_v2_sparse_classes_30k_train_000100 | Implement the Python class `MultiPoll` described below.
Class description:
Implement the MultiPoll class.
Method signatures and docstrings:
- def determine_next_values(self, source_values): Should receive raw source data and decides what to send, if anything :param source_values [ float ] or whatever type is returned... | Implement the Python class `MultiPoll` described below.
Class description:
Implement the MultiPoll class.
Method signatures and docstrings:
- def determine_next_values(self, source_values): Should receive raw source data and decides what to send, if anything :param source_values [ float ] or whatever type is returned... | d0eb095d036c095908533ff8b4f82ada68bc2afe | <|skeleton|>
class MultiPoll:
def determine_next_values(self, source_values):
"""Should receive raw source data and decides what to send, if anything :param source_values [ float ] or whatever type is returned by self.func. Simplest would be [ float ] :returns [ float ] or None"""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiPoll:
def determine_next_values(self, source_values):
"""Should receive raw source data and decides what to send, if anything :param source_values [ float ] or whatever type is returned by self.func. Simplest would be [ float ] :returns [ float ] or None"""
if source_values is None or any... | the_stack_v2_python_sparse | microprediction/polling.py | EricZLou/microprediction | train | 0 | |
511cc047f356abe202618be880a61b85b0397046 | [
"if isinstance(dataframe, cudf.DataFrame):\n self.nodes = dataframe\nelse:\n self.nodes = dataframe.data\n self.edges = dataframe.edges\nif self.edges is not None:\n self.connected_edges = calc_connected_edges(self.nodes, self.edges, self.node_x, self.node_y, self.node_id, self.edge_source, self.edge_ta... | <|body_start_0|>
if isinstance(dataframe, cudf.DataFrame):
self.nodes = dataframe
else:
self.nodes = dataframe.data
self.edges = dataframe.edges
if self.edges is not None:
self.connected_edges = calc_connected_edges(self.nodes, self.edges, self.nod... | Description: | Graph | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graph:
"""Description:"""
def format_source_data(self, dataframe):
"""Description: format source ------------------------------------------- Input: source_dict = { 'X': [], 'Y': [] } ------------------------------------------- Ouput:"""
<|body_0|>
def generate_chart(self... | stack_v2_sparse_classes_36k_train_028757 | 13,717 | permissive | [
{
"docstring": "Description: format source ------------------------------------------- Input: source_dict = { 'X': [], 'Y': [] } ------------------------------------------- Ouput:",
"name": "format_source_data",
"signature": "def format_source_data(self, dataframe)"
},
{
"docstring": "Descriptio... | 4 | stack_v2_sparse_classes_30k_train_004459 | Implement the Python class `Graph` described below.
Class description:
Description:
Method signatures and docstrings:
- def format_source_data(self, dataframe): Description: format source ------------------------------------------- Input: source_dict = { 'X': [], 'Y': [] } ------------------------------------------- ... | Implement the Python class `Graph` described below.
Class description:
Description:
Method signatures and docstrings:
- def format_source_data(self, dataframe): Description: format source ------------------------------------------- Input: source_dict = { 'X': [], 'Y': [] } ------------------------------------------- ... | bc073d73fea6c0dcb25abc496e030d64611b5cd8 | <|skeleton|>
class Graph:
"""Description:"""
def format_source_data(self, dataframe):
"""Description: format source ------------------------------------------- Input: source_dict = { 'X': [], 'Y': [] } ------------------------------------------- Ouput:"""
<|body_0|>
def generate_chart(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Graph:
"""Description:"""
def format_source_data(self, dataframe):
"""Description: format source ------------------------------------------- Input: source_dict = { 'X': [], 'Y': [] } ------------------------------------------- Ouput:"""
if isinstance(dataframe, cudf.DataFrame):
... | the_stack_v2_python_sparse | python/cuxfilter/charts/datashader/plots.py | rapidsai/cuxfilter | train | 253 |
49e2ff6ea58dc32da1126841d7d9d9258427eb66 | [
"n = len(s)\ni = 0\nj = n - 1\nwhile i < j:\n s[i], s[j] = (s[j], s[i])\n i += 1\n j -= 1\nreturn s",
"def helper(i, j):\n if i >= j:\n return\n s[i], s[j] = (s[j], s[i])\n i += 1\n j -= 1\n helper(i, j)\nn = len(s)\ni = 0\nj = n - 1\nhelper(i, j)\nreturn s",
"if head is None:\n ... | <|body_start_0|>
n = len(s)
i = 0
j = n - 1
while i < j:
s[i], s[j] = (s[j], s[i])
i += 1
j -= 1
return s
<|end_body_0|>
<|body_start_1|>
def helper(i, j):
if i >= j:
return
s[i], s[j] = (s[j], s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseString(self, s):
"""迭代的方式 :type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""
<|body_0|>
def reverseString2(self, s):
"""递归的方式 :type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""... | stack_v2_sparse_classes_36k_train_028758 | 2,868 | no_license | [
{
"docstring": "迭代的方式 :type s: List[str] :rtype: None Do not return anything, modify s in-place instead.",
"name": "reverseString",
"signature": "def reverseString(self, s)"
},
{
"docstring": "递归的方式 :type s: List[str] :rtype: None Do not return anything, modify s in-place instead.",
"name": ... | 4 | stack_v2_sparse_classes_30k_train_021007 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseString(self, s): 迭代的方式 :type s: List[str] :rtype: None Do not return anything, modify s in-place instead.
- def reverseString2(self, s): 递归的方式 :type s: List[str] :rtyp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseString(self, s): 迭代的方式 :type s: List[str] :rtype: None Do not return anything, modify s in-place instead.
- def reverseString2(self, s): 递归的方式 :type s: List[str] :rtyp... | 3b13b36f37eb364410b3b5b4f10a1808d8b1111e | <|skeleton|>
class Solution:
def reverseString(self, s):
"""迭代的方式 :type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""
<|body_0|>
def reverseString2(self, s):
"""递归的方式 :type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseString(self, s):
"""迭代的方式 :type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""
n = len(s)
i = 0
j = n - 1
while i < j:
s[i], s[j] = (s[j], s[i])
i += 1
j -= 1
return s
... | the_stack_v2_python_sparse | practice/20191028.py | yanggelinux/algorithm-data-structure | train | 0 | |
744b1263b0fd6f8b6ce1192b112096f5b9851353 | [
"assert self.query.can_filter(), 'Cannot use \"limit\" or \"offset\" with delete.'\nobj: 'ModeratedModel'\nfor obj in self.all():\n obj.delete()\nself._result_cache = None",
"assert self.query.can_filter(), 'Cannot use \"limit\" or \"offset\" with undelete.'\nobj: 'ModeratedModel'\nfor obj in self.all():\n ... | <|body_start_0|>
assert self.query.can_filter(), 'Cannot use "limit" or "offset" with delete.'
obj: 'ModeratedModel'
for obj in self.all():
obj.delete()
self._result_cache = None
<|end_body_0|>
<|body_start_1|>
assert self.query.can_filter(), 'Cannot use "limit" or "... | Default queryset for the ModeratedManager. Calling obj.delete/undelete is inefficient but allows moderated deletes. | ModeratedQuerySet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModeratedQuerySet:
"""Default queryset for the ModeratedManager. Calling obj.delete/undelete is inefficient but allows moderated deletes."""
def delete(self):
"""Override bulk delete behavior."""
<|body_0|>
def undelete(self):
"""Undelete soft-deleted instances."... | stack_v2_sparse_classes_36k_train_028759 | 2,139 | no_license | [
{
"docstring": "Override bulk delete behavior.",
"name": "delete",
"signature": "def delete(self)"
},
{
"docstring": "Undelete soft-deleted instances.",
"name": "undelete",
"signature": "def undelete(self)"
}
] | 2 | null | Implement the Python class `ModeratedQuerySet` described below.
Class description:
Default queryset for the ModeratedManager. Calling obj.delete/undelete is inefficient but allows moderated deletes.
Method signatures and docstrings:
- def delete(self): Override bulk delete behavior.
- def undelete(self): Undelete sof... | Implement the Python class `ModeratedQuerySet` described below.
Class description:
Default queryset for the ModeratedManager. Calling obj.delete/undelete is inefficient but allows moderated deletes.
Method signatures and docstrings:
- def delete(self): Override bulk delete behavior.
- def undelete(self): Undelete sof... | 8bbdc8eec3622af22c17214051c34e36bea8e05a | <|skeleton|>
class ModeratedQuerySet:
"""Default queryset for the ModeratedManager. Calling obj.delete/undelete is inefficient but allows moderated deletes."""
def delete(self):
"""Override bulk delete behavior."""
<|body_0|>
def undelete(self):
"""Undelete soft-deleted instances."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModeratedQuerySet:
"""Default queryset for the ModeratedManager. Calling obj.delete/undelete is inefficient but allows moderated deletes."""
def delete(self):
"""Override bulk delete behavior."""
assert self.query.can_filter(), 'Cannot use "limit" or "offset" with delete.'
obj: 'M... | the_stack_v2_python_sparse | apps/moderation/models/moderated_model/manager.py | abdulwahed-mansour/modularhistory | train | 1 |
c678e68edb104d717d535528680cfac28a545ef4 | [
"super(JDDCodec, self).__init__(search_space, **kwargs)\nself.func_type, self.func_prob = self.get_choices()\nself.func_type_num = len(self.func_type)",
"channel_types = ['16', '32', '48']\nchannel_prob = [1, 0.5, 0.2]\nblock_types = ['R']\nblock_prob = [1]\nmodel_type = self.search_space['modules'][0]\nchannel_t... | <|body_start_0|>
super(JDDCodec, self).__init__(search_space, **kwargs)
self.func_type, self.func_prob = self.get_choices()
self.func_type_num = len(self.func_type)
<|end_body_0|>
<|body_start_1|>
channel_types = ['16', '32', '48']
channel_prob = [1, 0.5, 0.2]
block_type... | Codec of the JDD search space. | JDDCodec | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JDDCodec:
"""Codec of the JDD search space."""
def __init__(self, search_space=None, **kwargs):
"""Construct the SRCodec class. :param codec_name: name of the codec :type codec_name: str :param search_space: Search space of the codec :type search_space: dictionary "S_" means that the... | stack_v2_sparse_classes_36k_train_028760 | 3,268 | permissive | [
{
"docstring": "Construct the SRCodec class. :param codec_name: name of the codec :type codec_name: str :param search_space: Search space of the codec :type search_space: dictionary \"S_\" means that the shrink RDB blcock with 1x1 convolution . \"G_\" means that the RDB block with channel shuffle and group conv... | 3 | stack_v2_sparse_classes_30k_train_014529 | Implement the Python class `JDDCodec` described below.
Class description:
Codec of the JDD search space.
Method signatures and docstrings:
- def __init__(self, search_space=None, **kwargs): Construct the SRCodec class. :param codec_name: name of the codec :type codec_name: str :param search_space: Search space of the... | Implement the Python class `JDDCodec` described below.
Class description:
Codec of the JDD search space.
Method signatures and docstrings:
- def __init__(self, search_space=None, **kwargs): Construct the SRCodec class. :param codec_name: name of the codec :type codec_name: str :param search_space: Search space of the... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class JDDCodec:
"""Codec of the JDD search space."""
def __init__(self, search_space=None, **kwargs):
"""Construct the SRCodec class. :param codec_name: name of the codec :type codec_name: str :param search_space: Search space of the codec :type search_space: dictionary "S_" means that the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JDDCodec:
"""Codec of the JDD search space."""
def __init__(self, search_space=None, **kwargs):
"""Construct the SRCodec class. :param codec_name: name of the codec :type codec_name: str :param search_space: Search space of the codec :type search_space: dictionary "S_" means that the shrink RDB b... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/algorithms/nas/jdd_ea/jdd_ea_codec.py | Huawei-Ascend/modelzoo | train | 1 |
6757e246b92ede37e6d33cb7e1ef9a42812c7d8e | [
"self.granularity = granularity\nself.min_interval = min_interval\nself.adjusted = adjusted",
"str = str.lower()\nif str == 'daily':\n return TickerResolution(TickerGranularity.DAILY)\nif str == 'daily_adjusted':\n return TickerResolution(TickerGranularity.DAILY, adjusted=True)\nif str == 'weekly':\n ret... | <|body_start_0|>
self.granularity = granularity
self.min_interval = min_interval
self.adjusted = adjusted
<|end_body_0|>
<|body_start_1|>
str = str.lower()
if str == 'daily':
return TickerResolution(TickerGranularity.DAILY)
if str == 'daily_adjusted':
... | Storage class for resolution. | TickerResolution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TickerResolution:
"""Storage class for resolution."""
def __init__(self, granularity=TickerGranularity.INTRADAY, min_interval=15, adjusted=False):
"""Creates the resolution method. Args: res: `TickerGranularity` to define the raw resolution min_interval: `int` to define the number of... | stack_v2_sparse_classes_36k_train_028761 | 4,748 | permissive | [
{
"docstring": "Creates the resolution method. Args: res: `TickerGranularity` to define the raw resolution min_interval: `int` to define the number of minutes for `INTRADAY` granularity adjusted: `bool` defines if closing prices should be adjusted",
"name": "__init__",
"signature": "def __init__(self, g... | 2 | stack_v2_sparse_classes_30k_train_020648 | Implement the Python class `TickerResolution` described below.
Class description:
Storage class for resolution.
Method signatures and docstrings:
- def __init__(self, granularity=TickerGranularity.INTRADAY, min_interval=15, adjusted=False): Creates the resolution method. Args: res: `TickerGranularity` to define the r... | Implement the Python class `TickerResolution` described below.
Class description:
Storage class for resolution.
Method signatures and docstrings:
- def __init__(self, granularity=TickerGranularity.INTRADAY, min_interval=15, adjusted=False): Creates the resolution method. Args: res: `TickerGranularity` to define the r... | e9d3f2db19a9af93cc8dc55c2394ae88c1b3ee6e | <|skeleton|>
class TickerResolution:
"""Storage class for resolution."""
def __init__(self, granularity=TickerGranularity.INTRADAY, min_interval=15, adjusted=False):
"""Creates the resolution method. Args: res: `TickerGranularity` to define the raw resolution min_interval: `int` to define the number of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TickerResolution:
"""Storage class for resolution."""
def __init__(self, granularity=TickerGranularity.INTRADAY, min_interval=15, adjusted=False):
"""Creates the resolution method. Args: res: `TickerGranularity` to define the raw resolution min_interval: `int` to define the number of minutes for ... | the_stack_v2_python_sparse | recommender/stocks/Ticker.py | felixnext/stock_trend_analysis | train | 17 |
6b1c63dcbf62cb9c56e782e98dc299aac98953b8 | [
"self.set_header('content-type', 'application/json')\ntry:\n incident = IncidentDao().get_incident_by_id(id).to_dict()\n self.finish(json_dumps({'status': 0, 'msg': 'ok', 'values': incident}))\nexcept Exception as e:\n logger.error(e)\n self.process_error(400, 'fail to get incident from database')",
"... | <|body_start_0|>
self.set_header('content-type', 'application/json')
try:
incident = IncidentDao().get_incident_by_id(id).to_dict()
self.finish(json_dumps({'status': 0, 'msg': 'ok', 'values': incident}))
except Exception as e:
logger.error(e)
self.... | IncidentQueryHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IncidentQueryHandler:
def get(self, id):
"""get a specific incident detail @API summary: get a specific incident detail notes: get a specific incident detail tags: - platform parameters: - name: id in: path required: true type: integer description: id of the incident"""
<|body_0|... | stack_v2_sparse_classes_36k_train_028762 | 20,674 | permissive | [
{
"docstring": "get a specific incident detail @API summary: get a specific incident detail notes: get a specific incident detail tags: - platform parameters: - name: id in: path required: true type: integer description: id of the incident",
"name": "get",
"signature": "def get(self, id)"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_006020 | Implement the Python class `IncidentQueryHandler` described below.
Class description:
Implement the IncidentQueryHandler class.
Method signatures and docstrings:
- def get(self, id): get a specific incident detail @API summary: get a specific incident detail notes: get a specific incident detail tags: - platform para... | Implement the Python class `IncidentQueryHandler` described below.
Class description:
Implement the IncidentQueryHandler class.
Method signatures and docstrings:
- def get(self, id): get a specific incident detail @API summary: get a specific incident detail notes: get a specific incident detail tags: - platform para... | 2e32e6e7b225e0bd87ee8c847c22862f12c51bb1 | <|skeleton|>
class IncidentQueryHandler:
def get(self, id):
"""get a specific incident detail @API summary: get a specific incident detail notes: get a specific incident detail tags: - platform parameters: - name: id in: path required: true type: integer description: id of the incident"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IncidentQueryHandler:
def get(self, id):
"""get a specific incident detail @API summary: get a specific incident detail notes: get a specific incident detail tags: - platform parameters: - name: id in: path required: true type: integer description: id of the incident"""
self.set_header('conten... | the_stack_v2_python_sparse | nebula/views/risk_incident.py | threathunterX/nebula_web | train | 2 | |
0cec5c6ceb1df809854e5dd36576a5b0c1e6acc7 | [
"super(COMA, self).__init__()\naction_shape = squeeze(action_shape)\nactor_input_size = squeeze(obs_shape['agent_state'])\ncritic_input_size = squeeze(obs_shape['agent_state']) + squeeze(obs_shape['global_state']) + agent_num * action_shape + (agent_num - 1) * action_shape\ncritic_hidden_size = actor_hidden_size_li... | <|body_start_0|>
super(COMA, self).__init__()
action_shape = squeeze(action_shape)
actor_input_size = squeeze(obs_shape['agent_state'])
critic_input_size = squeeze(obs_shape['agent_state']) + squeeze(obs_shape['global_state']) + agent_num * action_shape + (agent_num - 1) * action_shape
... | Overview: COMA network is QAC-type actor-critic. | COMA | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class COMA:
"""Overview: COMA network is QAC-type actor-critic."""
def __init__(self, agent_num: int, obs_shape: Dict, action_shape: Union[int, SequenceType], actor_hidden_size_list: SequenceType) -> None:
"""Overview: initialize COMA network Arguments: - agent_num (:obj:`int`): the number... | stack_v2_sparse_classes_36k_train_028763 | 7,790 | permissive | [
{
"docstring": "Overview: initialize COMA network Arguments: - agent_num (:obj:`int`): the number of agent - obs_shape (:obj:`Dict`): the observation information, including agent_state and global_state - action_shape (:obj:`Union[int, SequenceType]`): the dimension of action shape - actor_hidden_size_list (:obj... | 2 | stack_v2_sparse_classes_30k_train_021023 | Implement the Python class `COMA` described below.
Class description:
Overview: COMA network is QAC-type actor-critic.
Method signatures and docstrings:
- def __init__(self, agent_num: int, obs_shape: Dict, action_shape: Union[int, SequenceType], actor_hidden_size_list: SequenceType) -> None: Overview: initialize COM... | Implement the Python class `COMA` described below.
Class description:
Overview: COMA network is QAC-type actor-critic.
Method signatures and docstrings:
- def __init__(self, agent_num: int, obs_shape: Dict, action_shape: Union[int, SequenceType], actor_hidden_size_list: SequenceType) -> None: Overview: initialize COM... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class COMA:
"""Overview: COMA network is QAC-type actor-critic."""
def __init__(self, agent_num: int, obs_shape: Dict, action_shape: Union[int, SequenceType], actor_hidden_size_list: SequenceType) -> None:
"""Overview: initialize COMA network Arguments: - agent_num (:obj:`int`): the number... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class COMA:
"""Overview: COMA network is QAC-type actor-critic."""
def __init__(self, agent_num: int, obs_shape: Dict, action_shape: Union[int, SequenceType], actor_hidden_size_list: SequenceType) -> None:
"""Overview: initialize COMA network Arguments: - agent_num (:obj:`int`): the number of agent - o... | the_stack_v2_python_sparse | ding/model/template/coma.py | shengxuesun/DI-engine | train | 1 |
09f14001bf83041998c835ce9d6bd84c2291bb63 | [
"self.ti_dicts = ti_dicts\nself.transforms = transforms\nself.log = _logger\nself.transformed_collection: list[TransformABC] = []\nself._validate_transforms()",
"if len(self.transforms) > 1:\n for transform in self.transforms:\n if transform.applies is None:\n raise ValueError('If more than o... | <|body_start_0|>
self.ti_dicts = ti_dicts
self.transforms = transforms
self.log = _logger
self.transformed_collection: list[TransformABC] = []
self._validate_transforms()
<|end_body_0|>
<|body_start_1|>
if len(self.transforms) > 1:
for transform in self.trans... | Transform Abstract Base Class | TransformsABC | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformsABC:
"""Transform Abstract Base Class"""
def __init__(self, ti_dicts: list[dict], transforms: list[GroupTransformModel | IndicatorTransformModel]):
"""Initialize instance properties."""
<|body_0|>
def _validate_transforms(self):
"""Validate the transfor... | stack_v2_sparse_classes_36k_train_028764 | 25,335 | permissive | [
{
"docstring": "Initialize instance properties.",
"name": "__init__",
"signature": "def __init__(self, ti_dicts: list[dict], transforms: list[GroupTransformModel | IndicatorTransformModel])"
},
{
"docstring": "Validate the transform model.",
"name": "_validate_transforms",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_021016 | Implement the Python class `TransformsABC` described below.
Class description:
Transform Abstract Base Class
Method signatures and docstrings:
- def __init__(self, ti_dicts: list[dict], transforms: list[GroupTransformModel | IndicatorTransformModel]): Initialize instance properties.
- def _validate_transforms(self): ... | Implement the Python class `TransformsABC` described below.
Class description:
Transform Abstract Base Class
Method signatures and docstrings:
- def __init__(self, ti_dicts: list[dict], transforms: list[GroupTransformModel | IndicatorTransformModel]): Initialize instance properties.
- def _validate_transforms(self): ... | 30dc147e40d63d1082ec2a5e6c62005b60c29c37 | <|skeleton|>
class TransformsABC:
"""Transform Abstract Base Class"""
def __init__(self, ti_dicts: list[dict], transforms: list[GroupTransformModel | IndicatorTransformModel]):
"""Initialize instance properties."""
<|body_0|>
def _validate_transforms(self):
"""Validate the transfor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformsABC:
"""Transform Abstract Base Class"""
def __init__(self, ti_dicts: list[dict], transforms: list[GroupTransformModel | IndicatorTransformModel]):
"""Initialize instance properties."""
self.ti_dicts = ti_dicts
self.transforms = transforms
self.log = _logger
... | the_stack_v2_python_sparse | tcex/api/tc/ti_transform/transform_abc.py | ThreatConnect-Inc/tcex | train | 24 |
a81dbc485d1fe5d0a1f03fec649204af9001c197 | [
"s = s.strip()\nif not len(s):\n return 0\nk = 1 if s[0] in ['+', '-'] else 0\nwhile k < len(s) and s[k].isdigit():\n k += 1\nif k == 1 and s[0] in ['+', '-']:\n return 0\nnum = int(s[0:k]) if k > 0 else 0\nif num < -2 ** 31:\n return -2 ** 31\nelif num > 2 ** 31 - 1:\n return 2 ** 31 - 1\nelse:\n ... | <|body_start_0|>
s = s.strip()
if not len(s):
return 0
k = 1 if s[0] in ['+', '-'] else 0
while k < len(s) and s[k].isdigit():
k += 1
if k == 1 and s[0] in ['+', '-']:
return 0
num = int(s[0:k]) if k > 0 else 0
if num < -2 ** 31... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myAtoi(self, s):
""":type s: str :rtype: int 时间击败66.28%,内存击败35.18%"""
<|body_0|>
def myAtoi1(self, s: str) -> int:
""":type s: str :rtype: int 确定有限状态机(deterministic finite automaton, DFA) 字符串处理的题目往往涉及复杂的流程以及条件情况,如果直接上手写程序,一不小心就会写出极其臃肿的代码。 因此,为了有条理地分析每个输... | stack_v2_sparse_classes_36k_train_028765 | 3,861 | no_license | [
{
"docstring": ":type s: str :rtype: int 时间击败66.28%,内存击败35.18%",
"name": "myAtoi",
"signature": "def myAtoi(self, s)"
},
{
"docstring": ":type s: str :rtype: int 确定有限状态机(deterministic finite automaton, DFA) 字符串处理的题目往往涉及复杂的流程以及条件情况,如果直接上手写程序,一不小心就会写出极其臃肿的代码。 因此,为了有条理地分析每个输入字符的处理方法,我们可以使用自动机这个概念: ... | 2 | stack_v2_sparse_classes_30k_train_001707 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, s): :type s: str :rtype: int 时间击败66.28%,内存击败35.18%
- def myAtoi1(self, s: str) -> int: :type s: str :rtype: int 确定有限状态机(deterministic finite automaton, DFA) 字符串处... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, s): :type s: str :rtype: int 时间击败66.28%,内存击败35.18%
- def myAtoi1(self, s: str) -> int: :type s: str :rtype: int 确定有限状态机(deterministic finite automaton, DFA) 字符串处... | 2dc982e690b153c33bc7e27a63604f754a0df90c | <|skeleton|>
class Solution:
def myAtoi(self, s):
""":type s: str :rtype: int 时间击败66.28%,内存击败35.18%"""
<|body_0|>
def myAtoi1(self, s: str) -> int:
""":type s: str :rtype: int 确定有限状态机(deterministic finite automaton, DFA) 字符串处理的题目往往涉及复杂的流程以及条件情况,如果直接上手写程序,一不小心就会写出极其臃肿的代码。 因此,为了有条理地分析每个输... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def myAtoi(self, s):
""":type s: str :rtype: int 时间击败66.28%,内存击败35.18%"""
s = s.strip()
if not len(s):
return 0
k = 1 if s[0] in ['+', '-'] else 0
while k < len(s) and s[k].isdigit():
k += 1
if k == 1 and s[0] in ['+', '-']:
... | the_stack_v2_python_sparse | 8_string-to-integer-atoi.py | 95275059/Algorithm | train | 0 | |
5594ffb43c6915a3f18f8a7f77fefca50fb367c9 | [
"hist_file = os.path.join(self.base_path, 'index.dat')\nc = ie_history.IEParser(open(hist_file, 'rb'))\nentries = [x for x in c.Parse()]\ntime_results = [x['mtime'] for x in entries]\nself.assertEqual(time_results, sorted(time_results))\nself.assertEqual(entries[1]['url'], 'Visited: testing@http://www.google.com/ch... | <|body_start_0|>
hist_file = os.path.join(self.base_path, 'index.dat')
c = ie_history.IEParser(open(hist_file, 'rb'))
entries = [x for x in c.Parse()]
time_results = [x['mtime'] for x in entries]
self.assertEqual(time_results, sorted(time_results))
self.assertEqual(entrie... | Test parsing of chrome history files. | IEHistoryTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IEHistoryTest:
"""Test parsing of chrome history files."""
def testBasicParsing(self):
"""Test we can parse a standard file."""
<|body_0|>
def testErrors(self):
"""Test empty files don't raise errors."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_028766 | 2,740 | permissive | [
{
"docstring": "Test we can parse a standard file.",
"name": "testBasicParsing",
"signature": "def testBasicParsing(self)"
},
{
"docstring": "Test empty files don't raise errors.",
"name": "testErrors",
"signature": "def testErrors(self)"
}
] | 2 | null | Implement the Python class `IEHistoryTest` described below.
Class description:
Test parsing of chrome history files.
Method signatures and docstrings:
- def testBasicParsing(self): Test we can parse a standard file.
- def testErrors(self): Test empty files don't raise errors. | Implement the Python class `IEHistoryTest` described below.
Class description:
Test parsing of chrome history files.
Method signatures and docstrings:
- def testBasicParsing(self): Test we can parse a standard file.
- def testErrors(self): Test empty files don't raise errors.
<|skeleton|>
class IEHistoryTest:
""... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class IEHistoryTest:
"""Test parsing of chrome history files."""
def testBasicParsing(self):
"""Test we can parse a standard file."""
<|body_0|>
def testErrors(self):
"""Test empty files don't raise errors."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IEHistoryTest:
"""Test parsing of chrome history files."""
def testBasicParsing(self):
"""Test we can parse a standard file."""
hist_file = os.path.join(self.base_path, 'index.dat')
c = ie_history.IEParser(open(hist_file, 'rb'))
entries = [x for x in c.Parse()]
tim... | the_stack_v2_python_sparse | grr/core/grr_response_core/lib/parsers/ie_history_test.py | google/grr | train | 4,683 |
51bf64826c61131d85d1ced664ab7094807bba67 | [
"super().__init__(name, **kwargs)\nself.website_id = 'gizbot'\nself.website_type = 'news'\nself.post_list_xpath = '//*[@id=\"content\"]/section/div/div[1]/div/ul/li'\nself.post_url_xpath = './div[1]/a/@href'\nself.post_list_url_xpath = '(//*[@id=\"content\"]/section/div/div[1]/div/ul/div[1]/div)[last()]/a/@href'\ns... | <|body_start_0|>
super().__init__(name, **kwargs)
self.website_id = 'gizbot'
self.website_type = 'news'
self.post_list_xpath = '//*[@id="content"]/section/div/div[1]/div/ul/li'
self.post_url_xpath = './div[1]/a/@href'
self.post_list_url_xpath = '(//*[@id="content"]/sectio... | 解析数据和爬虫逻辑类 | MySpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySpider:
"""解析数据和爬虫逻辑类"""
def __init__(self, name=None, **kwargs):
"""完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None"""
<|body_0|>
def parse(self, response):
"""解析列表页数据... | stack_v2_sparse_classes_36k_train_028767 | 3,809 | no_license | [
{
"docstring": "完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None",
"name": "__init__",
"signature": "def __init__(self, name=None, **kwargs)"
},
{
"docstring": "解析列表页数据以及构造新闻页和下一列表页请求",
"name": "parse... | 4 | null | Implement the Python class `MySpider` described below.
Class description:
解析数据和爬虫逻辑类
Method signatures and docstrings:
- def __init__(self, name=None, **kwargs): 完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None
- def parse(sel... | Implement the Python class `MySpider` described below.
Class description:
解析数据和爬虫逻辑类
Method signatures and docstrings:
- def __init__(self, name=None, **kwargs): 完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None
- def parse(sel... | 1b42878b694fabc65a02228662ffdf819e5dcc71 | <|skeleton|>
class MySpider:
"""解析数据和爬虫逻辑类"""
def __init__(self, name=None, **kwargs):
"""完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None"""
<|body_0|>
def parse(self, response):
"""解析列表页数据... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MySpider:
"""解析数据和爬虫逻辑类"""
def __init__(self, name=None, **kwargs):
"""完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None"""
super().__init__(name, **kwargs)
self.website_id = 'gizbot'
... | the_stack_v2_python_sparse | wujian/gizbot/gizbot/spiders/gizbot.py | wangsanshi123/spiders | train | 0 |
f90c0ea36d3fa13212380b15cadb34035cd80dc5 | [
"wave = numpy.convolve(one.waveform, two.waveform, mode)\nwave.resize(len(one.waveform))\nsuper().__init__(name, one.times, wave)\nself.one = one\nself.two = two",
"if key in ('', 'both', 'whole', 'self', 0, 3):\n return self\nif key in ('one', 1, self.one.name):\n return self.one\nif key in ('two', 2, self... | <|body_start_0|>
wave = numpy.convolve(one.waveform, two.waveform, mode)
wave.resize(len(one.waveform))
super().__init__(name, one.times, wave)
self.one = one
self.two = two
<|end_body_0|>
<|body_start_1|>
if key in ('', 'both', 'whole', 'self', 0, 3):
return... | A signal formed from the convolution of two signals. | Convolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Convolution:
"""A signal formed from the convolution of two signals."""
def __init__(self, name, one, two, mode='full'):
"""Create measure from two signals."""
<|body_0|>
def component(self, key):
"""Return component by identifying key."""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_028768 | 25,189 | no_license | [
{
"docstring": "Create measure from two signals.",
"name": "__init__",
"signature": "def __init__(self, name, one, two, mode='full')"
},
{
"docstring": "Return component by identifying key.",
"name": "component",
"signature": "def component(self, key)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001091 | Implement the Python class `Convolution` described below.
Class description:
A signal formed from the convolution of two signals.
Method signatures and docstrings:
- def __init__(self, name, one, two, mode='full'): Create measure from two signals.
- def component(self, key): Return component by identifying key. | Implement the Python class `Convolution` described below.
Class description:
A signal formed from the convolution of two signals.
Method signatures and docstrings:
- def __init__(self, name, one, two, mode='full'): Create measure from two signals.
- def component(self, key): Return component by identifying key.
<|sk... | bfaea8464a9f777e5b59216b265fd68fb22564ae | <|skeleton|>
class Convolution:
"""A signal formed from the convolution of two signals."""
def __init__(self, name, one, two, mode='full'):
"""Create measure from two signals."""
<|body_0|>
def component(self, key):
"""Return component by identifying key."""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Convolution:
"""A signal formed from the convolution of two signals."""
def __init__(self, name, one, two, mode='full'):
"""Create measure from two signals."""
wave = numpy.convolve(one.waveform, two.waveform, mode)
wave.resize(len(one.waveform))
super().__init__(name, one... | the_stack_v2_python_sparse | wirecell/sigproc/fwd.py | WireCell/wire-cell-python | train | 0 |
67accf3fed9388232f1475cce18f47182102ffd0 | [
"self.mount_error = mount_error\nself.mount_point = mount_point\nself.volume_name = volume_name",
"if dictionary is None:\n return None\nmount_error = cohesity_management_sdk.models.request_error.RequestError.from_dictionary(dictionary.get('mountError')) if dictionary.get('mountError') else None\nmount_point =... | <|body_start_0|>
self.mount_error = mount_error
self.mount_point = mount_point
self.volume_name = volume_name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
mount_error = cohesity_management_sdk.models.request_error.RequestError.from_dictionary(di... | Implementation of the 'MountVolumeResultDetails' model. Specifies the result of mounting an individual mount volume in a Restore Task. Attributes: mount_error (RequestError): Specifies the cause of the mount failure if the mounting of a volume failed. mount_point (string): Specifies the mount point where the volume is ... | MountVolumeResultDetails | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MountVolumeResultDetails:
"""Implementation of the 'MountVolumeResultDetails' model. Specifies the result of mounting an individual mount volume in a Restore Task. Attributes: mount_error (RequestError): Specifies the cause of the mount failure if the mounting of a volume failed. mount_point (str... | stack_v2_sparse_classes_36k_train_028769 | 2,345 | permissive | [
{
"docstring": "Constructor for the MountVolumeResultDetails class",
"name": "__init__",
"signature": "def __init__(self, mount_error=None, mount_point=None, volume_name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary repr... | 2 | stack_v2_sparse_classes_30k_train_014852 | Implement the Python class `MountVolumeResultDetails` described below.
Class description:
Implementation of the 'MountVolumeResultDetails' model. Specifies the result of mounting an individual mount volume in a Restore Task. Attributes: mount_error (RequestError): Specifies the cause of the mount failure if the mounti... | Implement the Python class `MountVolumeResultDetails` described below.
Class description:
Implementation of the 'MountVolumeResultDetails' model. Specifies the result of mounting an individual mount volume in a Restore Task. Attributes: mount_error (RequestError): Specifies the cause of the mount failure if the mounti... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class MountVolumeResultDetails:
"""Implementation of the 'MountVolumeResultDetails' model. Specifies the result of mounting an individual mount volume in a Restore Task. Attributes: mount_error (RequestError): Specifies the cause of the mount failure if the mounting of a volume failed. mount_point (str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MountVolumeResultDetails:
"""Implementation of the 'MountVolumeResultDetails' model. Specifies the result of mounting an individual mount volume in a Restore Task. Attributes: mount_error (RequestError): Specifies the cause of the mount failure if the mounting of a volume failed. mount_point (string): Specifi... | the_stack_v2_python_sparse | cohesity_management_sdk/models/mount_volume_result_details.py | cohesity/management-sdk-python | train | 24 |
24946af70bd19f4df06148cc31a255e1e471b47b | [
"if not kwargs.get('obj_ids'):\n obj_model = facade.get_route_map_entry_by_search(self.search)\n objects = obj_model['query_set']\n only_main_property = False\nelse:\n ids = kwargs.get('obj_ids').split(';')\n objects = facade.get_route_map_entry_by_ids(ids)\n only_main_property = True\n obj_mod... | <|body_start_0|>
if not kwargs.get('obj_ids'):
obj_model = facade.get_route_map_entry_by_search(self.search)
objects = obj_model['query_set']
only_main_property = False
else:
ids = kwargs.get('obj_ids').split(';')
objects = facade.get_route_map... | RouteMapEntryDBView | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouteMapEntryDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMapEntries by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new RouteMapEntry."""
<|body_1|>
def put(self, request, *args, **kwargs):... | stack_v2_sparse_classes_36k_train_028770 | 9,414 | permissive | [
{
"docstring": "Returns a list of RouteMapEntries by ids ou dict.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Create new RouteMapEntry.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Upda... | 4 | stack_v2_sparse_classes_30k_train_010707 | Implement the Python class `RouteMapEntryDBView` described below.
Class description:
Implement the RouteMapEntryDBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of RouteMapEntries by ids ou dict.
- def post(self, request, *args, **kwargs): Create new RouteMapEn... | Implement the Python class `RouteMapEntryDBView` described below.
Class description:
Implement the RouteMapEntryDBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of RouteMapEntries by ids ou dict.
- def post(self, request, *args, **kwargs): Create new RouteMapEn... | eb27e1d977a1c4bb1fee8fb51b8d8050c64696d9 | <|skeleton|>
class RouteMapEntryDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMapEntries by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new RouteMapEntry."""
<|body_1|>
def put(self, request, *args, **kwargs):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RouteMapEntryDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMapEntries by ids ou dict."""
if not kwargs.get('obj_ids'):
obj_model = facade.get_route_map_entry_by_search(self.search)
objects = obj_model['query_set']
only_main_prope... | the_stack_v2_python_sparse | networkapi/api_route_map/v4/views.py | globocom/GloboNetworkAPI | train | 86 | |
019effdfcef015c899beee77347c884c36cf7b2a | [
"session_id = self.new_session_id()\nif kernel_id is not None and kernel_id in self.kernel_manager:\n pass\nelse:\n kernel_id = (yield self.start_kernel_for_session(session_id, path, name, type, kernel_name, **kwargs))\nresult = (yield gen.maybe_future(self.save_session(session_id, path=path, name=name, type=... | <|body_start_0|>
session_id = self.new_session_id()
if kernel_id is not None and kernel_id in self.kernel_manager:
pass
else:
kernel_id = (yield self.start_kernel_for_session(session_id, path, name, type, kernel_name, **kwargs))
result = (yield gen.maybe_future(se... | Session manager for Jaffle. It extends Jupyter Notebook's SessionManager to pass additional arguments to ``create_session()`` and ``start_kernel_for_session()``. | JaffleSessionManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JaffleSessionManager:
"""Session manager for Jaffle. It extends Jupyter Notebook's SessionManager to pass additional arguments to ``create_session()`` and ``start_kernel_for_session()``."""
def create_session(self, path=None, name=None, type=None, kernel_name=None, kernel_id=None, **kwargs):... | stack_v2_sparse_classes_36k_train_028771 | 2,847 | permissive | [
{
"docstring": "Creates a session and returns its model. This method overwrites ``SessionManager.create_session()`` to pass kwargs (e.g. ``env={...}``). Parameters ---------- path : str the path for the given session name: str the name of the session type: string the type of the session kernel_name : str The na... | 2 | null | Implement the Python class `JaffleSessionManager` described below.
Class description:
Session manager for Jaffle. It extends Jupyter Notebook's SessionManager to pass additional arguments to ``create_session()`` and ``start_kernel_for_session()``.
Method signatures and docstrings:
- def create_session(self, path=None... | Implement the Python class `JaffleSessionManager` described below.
Class description:
Session manager for Jaffle. It extends Jupyter Notebook's SessionManager to pass additional arguments to ``create_session()`` and ``start_kernel_for_session()``.
Method signatures and docstrings:
- def create_session(self, path=None... | ab8352716c973eef9c224ff80d0dd66b95c606a3 | <|skeleton|>
class JaffleSessionManager:
"""Session manager for Jaffle. It extends Jupyter Notebook's SessionManager to pass additional arguments to ``create_session()`` and ``start_kernel_for_session()``."""
def create_session(self, path=None, name=None, type=None, kernel_name=None, kernel_id=None, **kwargs):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JaffleSessionManager:
"""Session manager for Jaffle. It extends Jupyter Notebook's SessionManager to pass additional arguments to ``create_session()`` and ``start_kernel_for_session()``."""
def create_session(self, path=None, name=None, type=None, kernel_name=None, kernel_id=None, **kwargs):
"""C... | the_stack_v2_python_sparse | jaffle/session.py | daniel-covelli/jaffle | train | 0 |
f19a89ec438223a482fb060b25194ccfd77b3767 | [
"super().__init__(parent)\nself.channels = [ch.replace('CH', '') for ch in self._left_axis_1_data_labels]\nself.channels_widget = _TemperatureChannelsWidget(self.channels)\nself.add_widgets_next_to_plot(self.channels_widget)\nself.pbt_configure = _QPushButton('Configure Channels')\nself.pbt_configure.clicked.connec... | <|body_start_0|>
super().__init__(parent)
self.channels = [ch.replace('CH', '') for ch in self._left_axis_1_data_labels]
self.channels_widget = _TemperatureChannelsWidget(self.channels)
self.add_widgets_next_to_plot(self.channels_widget)
self.pbt_configure = _QPushButton('Configu... | Temperature Widget class for the Hall Bench Control application. | TemperatureWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemperatureWidget:
"""Temperature Widget class for the Hall Bench Control application."""
def __init__(self, parent=None):
"""Set up the ui and signal/slot connections."""
<|body_0|>
def closeEvent(self, event):
"""Close widget."""
<|body_1|>
def che... | stack_v2_sparse_classes_36k_train_028772 | 6,709 | no_license | [
{
"docstring": "Set up the ui and signal/slot connections.",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Close widget.",
"name": "closeEvent",
"signature": "def closeEvent(self, event)"
},
{
"docstring": "Check devices connection.",
"... | 6 | stack_v2_sparse_classes_30k_train_017947 | Implement the Python class `TemperatureWidget` described below.
Class description:
Temperature Widget class for the Hall Bench Control application.
Method signatures and docstrings:
- def __init__(self, parent=None): Set up the ui and signal/slot connections.
- def closeEvent(self, event): Close widget.
- def check_c... | Implement the Python class `TemperatureWidget` described below.
Class description:
Temperature Widget class for the Hall Bench Control application.
Method signatures and docstrings:
- def __init__(self, parent=None): Set up the ui and signal/slot connections.
- def closeEvent(self, event): Close widget.
- def check_c... | 25a9256522ea82e181639294e6d23ab2372a76b4 | <|skeleton|>
class TemperatureWidget:
"""Temperature Widget class for the Hall Bench Control application."""
def __init__(self, parent=None):
"""Set up the ui and signal/slot connections."""
<|body_0|>
def closeEvent(self, event):
"""Close widget."""
<|body_1|>
def che... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemperatureWidget:
"""Temperature Widget class for the Hall Bench Control application."""
def __init__(self, parent=None):
"""Set up the ui and signal/slot connections."""
super().__init__(parent)
self.channels = [ch.replace('CH', '') for ch in self._left_axis_1_data_labels]
... | the_stack_v2_python_sparse | hallbench/gui/temperaturewidget.py | lnls-ima/hall-bench-control | train | 1 |
00fdf36af55bfc88aa1151778124560fa93a8a1c | [
"_db = Session.object_session(collection)\nlookup_client = lookup_client or MetadataWranglerOPDSLookup.from_config(_db, collection=collection)\nsuper(BaseMetadataWranglerCoverageProvider, self).__init__(collection, lookup_client, **kwargs)\nif not self.lookup_client.authenticated:\n raise CannotLoadConfiguration... | <|body_start_0|>
_db = Session.object_session(collection)
lookup_client = lookup_client or MetadataWranglerOPDSLookup.from_config(_db, collection=collection)
super(BaseMetadataWranglerCoverageProvider, self).__init__(collection, lookup_client, **kwargs)
if not self.lookup_client.authenti... | Makes sure the metadata wrangler knows about all Identifiers licensed to a Collection. This has two subclasses: MetadataWranglerCollectionRegistrar (which adds Identifiers from a circulation manager's catalog to the corresponding catalog on the metadata wrangler) and MetadataWranglerCollectionReaper (which removes Iden... | BaseMetadataWranglerCoverageProvider | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseMetadataWranglerCoverageProvider:
"""Makes sure the metadata wrangler knows about all Identifiers licensed to a Collection. This has two subclasses: MetadataWranglerCollectionRegistrar (which adds Identifiers from a circulation manager's catalog to the corresponding catalog on the metadata wr... | stack_v2_sparse_classes_36k_train_028773 | 20,614 | permissive | [
{
"docstring": "Since we are processing a specific collection, we must be able to get an _authenticated_ metadata wrangler lookup client for the collection.",
"name": "__init__",
"signature": "def __init__(self, collection, lookup_client=None, **kwargs)"
},
{
"docstring": "The metadata wrangler ... | 2 | null | Implement the Python class `BaseMetadataWranglerCoverageProvider` described below.
Class description:
Makes sure the metadata wrangler knows about all Identifiers licensed to a Collection. This has two subclasses: MetadataWranglerCollectionRegistrar (which adds Identifiers from a circulation manager's catalog to the c... | Implement the Python class `BaseMetadataWranglerCoverageProvider` described below.
Class description:
Makes sure the metadata wrangler knows about all Identifiers licensed to a Collection. This has two subclasses: MetadataWranglerCollectionRegistrar (which adds Identifiers from a circulation manager's catalog to the c... | 662cc7e0721d0153857c8c17a37e2a6df86f8ce6 | <|skeleton|>
class BaseMetadataWranglerCoverageProvider:
"""Makes sure the metadata wrangler knows about all Identifiers licensed to a Collection. This has two subclasses: MetadataWranglerCollectionRegistrar (which adds Identifiers from a circulation manager's catalog to the corresponding catalog on the metadata wr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseMetadataWranglerCoverageProvider:
"""Makes sure the metadata wrangler knows about all Identifiers licensed to a Collection. This has two subclasses: MetadataWranglerCollectionRegistrar (which adds Identifiers from a circulation manager's catalog to the corresponding catalog on the metadata wrangler) and M... | the_stack_v2_python_sparse | api/metadata_wrangler.py | NYPL-Simplified/circulation | train | 20 |
4b612ccddcca123d374e51540159ac2215f18f3c | [
"groups = Group.query.all()\ngroups_list = []\nfor group in groups:\n groups_list.append(group.__jsonapi__())\nreturn {'data': groups_list}",
"data = request.get_json()['data']\ngroup = Group(name=data['attributes']['name'])\ntry:\n group.abilities = list((id['id'] for id in data['relationships']['abilities... | <|body_start_0|>
groups = Group.query.all()
groups_list = []
for group in groups:
groups_list.append(group.__jsonapi__())
return {'data': groups_list}
<|end_body_0|>
<|body_start_1|>
data = request.get_json()['data']
group = Group(name=data['attributes']['nam... | GroupsList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupsList:
def get(self):
"""Get groups list"""
<|body_0|>
def post(self):
"""Create group"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
groups = Group.query.all()
groups_list = []
for group in groups:
groups_list.appe... | stack_v2_sparse_classes_36k_train_028774 | 46,738 | permissive | [
{
"docstring": "Get groups list",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create group",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001001 | Implement the Python class `GroupsList` described below.
Class description:
Implement the GroupsList class.
Method signatures and docstrings:
- def get(self): Get groups list
- def post(self): Create group | Implement the Python class `GroupsList` described below.
Class description:
Implement the GroupsList class.
Method signatures and docstrings:
- def get(self): Get groups list
- def post(self): Create group
<|skeleton|>
class GroupsList:
def get(self):
"""Get groups list"""
<|body_0|>
def po... | 3439a2dd0bd527c5d604801fec3a5aac904a72e2 | <|skeleton|>
class GroupsList:
def get(self):
"""Get groups list"""
<|body_0|>
def post(self):
"""Create group"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupsList:
def get(self):
"""Get groups list"""
groups = Group.query.all()
groups_list = []
for group in groups:
groups_list.append(group.__jsonapi__())
return {'data': groups_list}
def post(self):
"""Create group"""
data = request.get_... | the_stack_v2_python_sparse | app/views.py | taidos/lxc-rest | train | 0 | |
2df5df756ce58a338d527cf8296f173414b6e2d5 | [
"self.regex = {}\nif regex_src:\n self.regex[0] = regex_src\nif regex_trg:\n self.regex[1] = regex_trg\nif regex_all:\n for i, v in enumerate(regex_all):\n self.regex[i] = v",
"for i, sent in enumerate(sents):\n if type(sent) == list:\n sent = ' '.join(sent)\n if self.regex.get(i) is ... | <|body_start_0|>
self.regex = {}
if regex_src:
self.regex[0] = regex_src
if regex_trg:
self.regex[1] = regex_trg
if regex_all:
for i, v in enumerate(regex_all):
self.regex[i] = v
<|end_body_0|>
<|body_start_1|>
for i, sent in e... | Filters sentences via regular expressions. A sentence must match the expression to be kept. | SentenceFiltererMatchingRegex | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SentenceFiltererMatchingRegex:
"""Filters sentences via regular expressions. A sentence must match the expression to be kept."""
def __init__(self, regex_src: Optional[str], regex_trg: Optional[str], regex_all: Optional[Sequence[str]]) -> None:
"""Specifies the regular expressions to... | stack_v2_sparse_classes_36k_train_028775 | 32,168 | permissive | [
{
"docstring": "Specifies the regular expressions to filter the sentences that we'll be getting. Args: regex_src: regular expression for source language (language index 0) regex_trg: regular expression for target language (language index 1) regex_all: list of regular expressions for all languages in order",
... | 2 | stack_v2_sparse_classes_30k_train_019730 | Implement the Python class `SentenceFiltererMatchingRegex` described below.
Class description:
Filters sentences via regular expressions. A sentence must match the expression to be kept.
Method signatures and docstrings:
- def __init__(self, regex_src: Optional[str], regex_trg: Optional[str], regex_all: Optional[Sequ... | Implement the Python class `SentenceFiltererMatchingRegex` described below.
Class description:
Filters sentences via regular expressions. A sentence must match the expression to be kept.
Method signatures and docstrings:
- def __init__(self, regex_src: Optional[str], regex_trg: Optional[str], regex_all: Optional[Sequ... | b5e6985d3bedfac102312cab030a60594bc17baf | <|skeleton|>
class SentenceFiltererMatchingRegex:
"""Filters sentences via regular expressions. A sentence must match the expression to be kept."""
def __init__(self, regex_src: Optional[str], regex_trg: Optional[str], regex_all: Optional[Sequence[str]]) -> None:
"""Specifies the regular expressions to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SentenceFiltererMatchingRegex:
"""Filters sentences via regular expressions. A sentence must match the expression to be kept."""
def __init__(self, regex_src: Optional[str], regex_trg: Optional[str], regex_all: Optional[Sequence[str]]) -> None:
"""Specifies the regular expressions to filter the s... | the_stack_v2_python_sparse | xnmt/preproc.py | philip30/xnmt | train | 0 |
501c3f7e1fa1aa0f2fc339dff951168b06f44ace | [
"super(AttentionWeights, self).__init__()\nself.w_enc = nn.Linear(size_enc_hidden, size_att_hidden, bias=False)\nself.w_query = nn.Linear(size_dec_hidden, size_att_hidden, bias=False)\nself.w_out = nn.Linear(size_att_hidden, 1, bias=False)",
"query_part = self.w_query(query)\nenc_part = self.w_enc(encoder_sequenc... | <|body_start_0|>
super(AttentionWeights, self).__init__()
self.w_enc = nn.Linear(size_enc_hidden, size_att_hidden, bias=False)
self.w_query = nn.Linear(size_dec_hidden, size_att_hidden, bias=False)
self.w_out = nn.Linear(size_att_hidden, 1, bias=False)
<|end_body_0|>
<|body_start_1|>
... | AttentionWeights | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionWeights:
def __init__(self, size_enc_hidden, size_dec_hidden, size_att_hidden):
"""Create attention weights layer. It's responsibility is to convert encoder sequence into vector of attention weights :param size_enc_hidden: size of hidden encoder state :param size_dec_hidden: siz... | stack_v2_sparse_classes_36k_train_028776 | 6,283 | no_license | [
{
"docstring": "Create attention weights layer. It's responsibility is to convert encoder sequence into vector of attention weights :param size_enc_hidden: size of hidden encoder state :param size_dec_hidden: size of hidden decoder state (aka query) :param size_att_hidden: size of attention hidden state (middle... | 2 | stack_v2_sparse_classes_30k_train_013791 | Implement the Python class `AttentionWeights` described below.
Class description:
Implement the AttentionWeights class.
Method signatures and docstrings:
- def __init__(self, size_enc_hidden, size_dec_hidden, size_att_hidden): Create attention weights layer. It's responsibility is to convert encoder sequence into vec... | Implement the Python class `AttentionWeights` described below.
Class description:
Implement the AttentionWeights class.
Method signatures and docstrings:
- def __init__(self, size_enc_hidden, size_dec_hidden, size_att_hidden): Create attention weights layer. It's responsibility is to convert encoder sequence into vec... | cded13e89559ad0e0b41ad8aad150469ac962dee | <|skeleton|>
class AttentionWeights:
def __init__(self, size_enc_hidden, size_dec_hidden, size_att_hidden):
"""Create attention weights layer. It's responsibility is to convert encoder sequence into vector of attention weights :param size_enc_hidden: size of hidden encoder state :param size_dec_hidden: siz... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttentionWeights:
def __init__(self, size_enc_hidden, size_dec_hidden, size_att_hidden):
"""Create attention weights layer. It's responsibility is to convert encoder sequence into vector of attention weights :param size_enc_hidden: size of hidden encoder state :param size_dec_hidden: size of hidden de... | the_stack_v2_python_sparse | deep_bayes/sem_attention/task1_sorting.py | Shmuma/pytorch_tests | train | 0 | |
68f19fa1f9c4c766b1970591d4bc16b9c6068a60 | [
"if context is None:\n context = {}\nres = {}\nresult = []\ndepartment_obj = self.pool.get('hr.department')\ndepartment_condition = ''\ndepartment_ids = department_obj.search(cr, uid, [('id', 'child_of', department_id)])\nif len(department_ids) == 1:\n department_condition = ' and cust.department_id in (%s)' ... | <|body_start_0|>
if context is None:
context = {}
res = {}
result = []
department_obj = self.pool.get('hr.department')
department_condition = ''
department_ids = department_obj.search(cr, uid, [('id', 'child_of', department_id)])
if len(department_ids)... | Class to Create Custody Release Request From wizard | create_custody_release_request | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class create_custody_release_request:
"""Class to Create Custody Release Request From wizard"""
def change_department(self, cr, uid, ids, department_id, context=None):
"""To get default values for the object. @return: A dictionary which of fields with values."""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_028777 | 5,827 | no_license | [
{
"docstring": "To get default values for the object. @return: A dictionary which of fields with values.",
"name": "change_department",
"signature": "def change_department(self, cr, uid, ids, department_id, context=None)"
},
{
"docstring": "Button function to create release order for custody @re... | 2 | stack_v2_sparse_classes_30k_train_011529 | Implement the Python class `create_custody_release_request` described below.
Class description:
Class to Create Custody Release Request From wizard
Method signatures and docstrings:
- def change_department(self, cr, uid, ids, department_id, context=None): To get default values for the object. @return: A dictionary wh... | Implement the Python class `create_custody_release_request` described below.
Class description:
Class to Create Custody Release Request From wizard
Method signatures and docstrings:
- def change_department(self, cr, uid, ids, department_id, context=None): To get default values for the object. @return: A dictionary wh... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class create_custody_release_request:
"""Class to Create Custody Release Request From wizard"""
def change_department(self, cr, uid, ids, department_id, context=None):
"""To get default values for the object. @return: A dictionary which of fields with values."""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class create_custody_release_request:
"""Class to Create Custody Release Request From wizard"""
def change_department(self, cr, uid, ids, department_id, context=None):
"""To get default values for the object. @return: A dictionary which of fields with values."""
if context is None:
... | the_stack_v2_python_sparse | v_7/NISS/shamil_v3/custody_management/wizard/partial_release_wizrd.py | musabahmed/baba | train | 0 |
249afcc1baf17e0c4f49320743d6afb282fcfda3 | [
"if not root:\n return ''\nq = deque()\ns = []\nq.append(root)\nwhile q:\n node = q.popleft()\n if node != 'null':\n s.append(str(node.val))\n if node.left:\n q.append(node.left)\n else:\n q.append('null')\n if node.right:\n q.append(node.right)\... | <|body_start_0|>
if not root:
return ''
q = deque()
s = []
q.append(root)
while q:
node = q.popleft()
if node != 'null':
s.append(str(node.val))
if node.left:
q.append(node.left)
... | 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_028778 | 2,151 | 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_002174 | 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... | 4beea4d4423ff5952f84c9a5c9c44aaae2e02271 | <|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 ''
q = deque()
s = []
q.append(root)
while q:
node = q.popleft()
if node != 'null':
s.append(str(n... | the_stack_v2_python_sparse | October Challenge/Serialize and Deserialize BST.py | Akash-Nair/LeetCode | train | 0 | |
57ae12a9f13b9adc2e6a9eaf132f6c739c842850 | [
"self.N = N\nself.n = n\nself.K_xyz_amplitude = K_xyz_extent\nself.values = np.zeros((N, N, N), dtype=np.complex)\nkx = ky = kz = np.linspace(-K_xyz_extent, K_xyz_extent, N)\nself.KX, self.KY, self.KZ = np.meshgrid(kx, ky, kz)\nself.dK = kx[1] - kx[0]\nx = y = z = np.fft.fftfreq(self.N, self.dK)\nself.dr = x[1] - x... | <|body_start_0|>
self.N = N
self.n = n
self.K_xyz_amplitude = K_xyz_extent
self.values = np.zeros((N, N, N), dtype=np.complex)
kx = ky = kz = np.linspace(-K_xyz_extent, K_xyz_extent, N)
self.KX, self.KY, self.KZ = np.meshgrid(kx, ky, kz)
self.dK = kx[1] - kx[0]
... | Generare an Amplitude Transfer Function (or Coherent Transfer function) from an Ewald sphere, projecting a 2D pupil on the sphere | amplitude_transfer_function | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class amplitude_transfer_function:
"""Generare an Amplitude Transfer Function (or Coherent Transfer function) from an Ewald sphere, projecting a 2D pupil on the sphere"""
def __init__(self, N=256, K_xyz_extent=2.0, n=1.0):
"""Constructor. Creates a space KX,KY,KZ. The K space extends betwe... | stack_v2_sparse_classes_36k_train_028779 | 3,810 | no_license | [
{
"docstring": "Constructor. Creates a space KX,KY,KZ. The K space extends between -+ K_xyz_extent N**3 is the number of voxels n is the refractive index. Inizializes the ATF (self.values) to zero. dK is the sampling step in the K space dr is the sampling step in the real space",
"name": "__init__",
"si... | 4 | stack_v2_sparse_classes_30k_train_016591 | Implement the Python class `amplitude_transfer_function` described below.
Class description:
Generare an Amplitude Transfer Function (or Coherent Transfer function) from an Ewald sphere, projecting a 2D pupil on the sphere
Method signatures and docstrings:
- def __init__(self, N=256, K_xyz_extent=2.0, n=1.0): Constru... | Implement the Python class `amplitude_transfer_function` described below.
Class description:
Generare an Amplitude Transfer Function (or Coherent Transfer function) from an Ewald sphere, projecting a 2D pupil on the sphere
Method signatures and docstrings:
- def __init__(self, N=256, K_xyz_extent=2.0, n=1.0): Constru... | 6f5b8eecb1b1c2df952e166493d96882e30233b3 | <|skeleton|>
class amplitude_transfer_function:
"""Generare an Amplitude Transfer Function (or Coherent Transfer function) from an Ewald sphere, projecting a 2D pupil on the sphere"""
def __init__(self, N=256, K_xyz_extent=2.0, n=1.0):
"""Constructor. Creates a space KX,KY,KZ. The K space extends betwe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class amplitude_transfer_function:
"""Generare an Amplitude Transfer Function (or Coherent Transfer function) from an Ewald sphere, projecting a 2D pupil on the sphere"""
def __init__(self, N=256, K_xyz_extent=2.0, n=1.0):
"""Constructor. Creates a space KX,KY,KZ. The K space extends between -+ K_xyz_e... | the_stack_v2_python_sparse | EwaldSphere/AmplitudeTransferFunction_3D.py | andreabassi78/BiophotonicsLectures | train | 3 |
5b2d9b847408c6bd8df3ed9f69b8e6c100e9a79c | [
"user: User = Retrieve.byid(userid)\ntry:\n index = user.indexs.get(typeid=typeid)\nexcept mongoengine.errors.DoesNotExist as _error:\n return user.indexs\nuser.indexs.remove(index)\nuser.indexs.save()\ntry:\n authdoc = auth.Retrieve.byindex(index.value)\nexcept error.AuthenticationNotFound as _error:\n ... | <|body_start_0|>
user: User = Retrieve.byid(userid)
try:
index = user.indexs.get(typeid=typeid)
except mongoengine.errors.DoesNotExist as _error:
return user.indexs
user.indexs.remove(index)
user.indexs.save()
try:
authdoc = auth.Retrie... | 删除用户静态函数集合 | Delete | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Delete:
"""删除用户静态函数集合"""
def index(userid: ObjectId, typeid: str) -> NoReturn:
"""删除用户的某一种 Index 同时要删除该 Index 对应的 Auth 文档"""
<|body_0|>
def group(userid: ObjectId, groupid: ObjectId) -> NoReturn:
"""将用户从某个用户组中移除: 将用户从用户组中移除 将组中的用户记录删除"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_028780 | 4,956 | permissive | [
{
"docstring": "删除用户的某一种 Index 同时要删除该 Index 对应的 Auth 文档",
"name": "index",
"signature": "def index(userid: ObjectId, typeid: str) -> NoReturn"
},
{
"docstring": "将用户从某个用户组中移除: 将用户从用户组中移除 将组中的用户记录删除",
"name": "group",
"signature": "def group(userid: ObjectId, groupid: ObjectId) -> NoRetur... | 2 | null | Implement the Python class `Delete` described below.
Class description:
删除用户静态函数集合
Method signatures and docstrings:
- def index(userid: ObjectId, typeid: str) -> NoReturn: 删除用户的某一种 Index 同时要删除该 Index 对应的 Auth 文档
- def group(userid: ObjectId, groupid: ObjectId) -> NoReturn: 将用户从某个用户组中移除: 将用户从用户组中移除 将组中的用户记录删除 | Implement the Python class `Delete` described below.
Class description:
删除用户静态函数集合
Method signatures and docstrings:
- def index(userid: ObjectId, typeid: str) -> NoReturn: 删除用户的某一种 Index 同时要删除该 Index 对应的 Auth 文档
- def group(userid: ObjectId, groupid: ObjectId) -> NoReturn: 将用户从某个用户组中移除: 将用户从用户组中移除 将组中的用户记录删除
<|skel... | 79e34f4b8fba8c6fd208b5a3049103dca2064ab5 | <|skeleton|>
class Delete:
"""删除用户静态函数集合"""
def index(userid: ObjectId, typeid: str) -> NoReturn:
"""删除用户的某一种 Index 同时要删除该 Index 对应的 Auth 文档"""
<|body_0|>
def group(userid: ObjectId, groupid: ObjectId) -> NoReturn:
"""将用户从某个用户组中移除: 将用户从用户组中移除 将组中的用户记录删除"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Delete:
"""删除用户静态函数集合"""
def index(userid: ObjectId, typeid: str) -> NoReturn:
"""删除用户的某一种 Index 同时要删除该 Index 对应的 Auth 文档"""
user: User = Retrieve.byid(userid)
try:
index = user.indexs.get(typeid=typeid)
except mongoengine.errors.DoesNotExist as _error:
... | the_stack_v2_python_sparse | leaf/rbac/functions/user.py | guiqiqi/leaf | train | 122 |
66ec79927e1c484caebf62b4ac99667edc64381b | [
"self.file = file\nself.db = SqliteDB()\nwith self.db as cur:\n cur.execute('SELECT * from salaries ORDER BY department_code, position_type;')\n self.work_data = cur.fetchall()\nself.fill = PatternFill(fill_type='solid', start_color='c1c1c1', end_color='c2c2c2')\nself.border = Border(left=Side(border_style='t... | <|body_start_0|>
self.file = file
self.db = SqliteDB()
with self.db as cur:
cur.execute('SELECT * from salaries ORDER BY department_code, position_type;')
self.work_data = cur.fetchall()
self.fill = PatternFill(fill_type='solid', start_color='c1c1c1', end_color='c... | Класс, выгружающий штатное расписание в файл Excel для заполнения отклонений | FullShtatToExcel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullShtatToExcel:
"""Класс, выгружающий штатное расписание в файл Excel для заполнения отклонений"""
def __init__(self, file: str):
"""Метод инициализации класса :param file: Название файла для отклонений"""
<|body_0|>
def full_shtat_to_excel(self) -> None:
"""Ме... | stack_v2_sparse_classes_36k_train_028781 | 4,837 | no_license | [
{
"docstring": "Метод инициализации класса :param file: Название файла для отклонений",
"name": "__init__",
"signature": "def __init__(self, file: str)"
},
{
"docstring": "Метод выгрузки штатного расписания в файл :return: None",
"name": "full_shtat_to_excel",
"signature": "def full_shta... | 2 | stack_v2_sparse_classes_30k_val_001198 | Implement the Python class `FullShtatToExcel` described below.
Class description:
Класс, выгружающий штатное расписание в файл Excel для заполнения отклонений
Method signatures and docstrings:
- def __init__(self, file: str): Метод инициализации класса :param file: Название файла для отклонений
- def full_shtat_to_ex... | Implement the Python class `FullShtatToExcel` described below.
Class description:
Класс, выгружающий штатное расписание в файл Excel для заполнения отклонений
Method signatures and docstrings:
- def __init__(self, file: str): Метод инициализации класса :param file: Название файла для отклонений
- def full_shtat_to_ex... | f63d5db6780cc02cb064e70d2076eba94cb45785 | <|skeleton|>
class FullShtatToExcel:
"""Класс, выгружающий штатное расписание в файл Excel для заполнения отклонений"""
def __init__(self, file: str):
"""Метод инициализации класса :param file: Название файла для отклонений"""
<|body_0|>
def full_shtat_to_excel(self) -> None:
"""Ме... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullShtatToExcel:
"""Класс, выгружающий штатное расписание в файл Excel для заполнения отклонений"""
def __init__(self, file: str):
"""Метод инициализации класса :param file: Название файла для отклонений"""
self.file = file
self.db = SqliteDB()
with self.db as cur:
... | the_stack_v2_python_sparse | save_loads/full_shtat_to_excel.py | Pheeneek/Salary | train | 0 |
71ff235d3f73fe3fb34e79e8b4d81d0208f0d0e1 | [
"lo, hi = (matrix[0][0], matrix[-1][-1])\nwhile lo < hi:\n mid = (lo + hi) // 2\n if sum((bisect.bisect_right(row, mid) for row in matrix)) < k:\n lo = mid + 1\n else:\n hi = mid\nreturn lo",
"heap = [(row[0], i, 0) for i, row in enumerate(matrix)]\nheapq.heapify(heap)\nret = 0\nfor _ in ra... | <|body_start_0|>
lo, hi = (matrix[0][0], matrix[-1][-1])
while lo < hi:
mid = (lo + hi) // 2
if sum((bisect.bisect_right(row, mid) for row in matrix)) < k:
lo = mid + 1
else:
hi = mid
return lo
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int https://discuss.leetcode.com/topic/52912/binary-search-heap-and-sorting-comparison-with-concise-code-and-1-liners-python-72-ms binary search time: O(n * log(n) * log(N)), where N is the ... | stack_v2_sparse_classes_36k_train_028782 | 1,799 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type k: int :rtype: int https://discuss.leetcode.com/topic/52912/binary-search-heap-and-sorting-comparison-with-concise-code-and-1-liners-python-72-ms binary search time: O(n * log(n) * log(N)), where N is the search space that ranges from the smallest element to t... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: int https://discuss.leetcode.com/topic/52912/binary-search-heap-and-sorting-comparison-with-c... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: int https://discuss.leetcode.com/topic/52912/binary-search-heap-and-sorting-comparison-with-c... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def kthSmallest(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int https://discuss.leetcode.com/topic/52912/binary-search-heap-and-sorting-comparison-with-concise-code-and-1-liners-python-72-ms binary search time: O(n * log(n) * log(N)), where N is the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kthSmallest(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int https://discuss.leetcode.com/topic/52912/binary-search-heap-and-sorting-comparison-with-concise-code-and-1-liners-python-72-ms binary search time: O(n * log(n) * log(N)), where N is the search space t... | the_stack_v2_python_sparse | LeetCode/378_kth_smallest_element_in_a_sorted_matrix.py | yao23/Machine_Learning_Playground | train | 12 | |
61900cf4de1078c0b6b81020c7cbd6b4807d6201 | [
"n = len(matrix)\nnew_matrix = [[0] * n for _ in range(n)]\nfor i in range(n):\n for j in range(n):\n new_matrix[j][n - i - 1] = matrix[i][j]\nprint(new_matrix)\nmatrix[:] = new_matrix",
"n = len(matrix)\nfor i in range(n // 2):\n for j in range((n + 1) // 2):\n print(matrix[i][j], matrix[i][n... | <|body_start_0|>
n = len(matrix)
new_matrix = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
new_matrix[j][n - i - 1] = matrix[i][j]
print(new_matrix)
matrix[:] = new_matrix
<|end_body_0|>
<|body_start_1|>
n = len(matrix)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""# 对于矩阵中的第 i 行的第 j 个元素,在旋转后,它出现在倒数第 i 列的第 j 个位置。"""
<|body_0|>
def rotete2(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_028783 | 1,924 | no_license | [
{
"docstring": "# 对于矩阵中的第 i 行的第 j 个元素,在旋转后,它出现在倒数第 i 列的第 j 个位置。",
"name": "rotate",
"signature": "def rotate(self, matrix: List[List[int]]) -> None"
},
{
"docstring": "Do not return anything, modify matrix in-place instead.",
"name": "rotete2",
"signature": "def rotete2(self, matrix: Lis... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix: List[List[int]]) -> None: # 对于矩阵中的第 i 行的第 j 个元素,在旋转后,它出现在倒数第 i 列的第 j 个位置。
- def rotete2(self, matrix: List[List[int]]) -> None: Do not return anything, m... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix: List[List[int]]) -> None: # 对于矩阵中的第 i 行的第 j 个元素,在旋转后,它出现在倒数第 i 列的第 j 个位置。
- def rotete2(self, matrix: List[List[int]]) -> None: Do not return anything, m... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""# 对于矩阵中的第 i 行的第 j 个元素,在旋转后,它出现在倒数第 i 列的第 j 个位置。"""
<|body_0|>
def rotete2(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""# 对于矩阵中的第 i 行的第 j 个元素,在旋转后,它出现在倒数第 i 列的第 j 个位置。"""
n = len(matrix)
new_matrix = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
new_matrix[j][n - i - 1] = matrix[i][j]
... | the_stack_v2_python_sparse | LCCI/01_07_RotateMatrix.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
d57b3824bdfca75f2c31c7c6116607f269eb7e22 | [
"if geo_opt:\n self.settings.input.Geometry\nself.settings.input.Basis.type = 'DZP'\nself.settings.input.Basis.core = 'None'\nself.settings.input.XC.GGA = 'BP86'\nself.settings.input.AnalyticalFreq\nself.settings.input.SYMMETRY = 'NOSYM'\nself.settings.input.VCD = 'Yes'",
"if init:\n if path is None:\n ... | <|body_start_0|>
if geo_opt:
self.settings.input.Geometry
self.settings.input.Basis.type = 'DZP'
self.settings.input.Basis.core = 'None'
self.settings.input.XC.GGA = 'BP86'
self.settings.input.AnalyticalFreq
self.settings.input.SYMMETRY = 'NOSYM'
self.... | Class used for geometry optimization + frequency jobs using DFT | DFTJob | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DFTJob:
"""Class used for geometry optimization + frequency jobs using DFT"""
def _set_std_settings(self, geo_opt=False):
"""Method that specifies standard settings for a DFT geometry optimization + freqs job"""
<|body_0|>
def run(self, init=True, path=None):
"""... | stack_v2_sparse_classes_36k_train_028784 | 3,480 | no_license | [
{
"docstring": "Method that specifies standard settings for a DFT geometry optimization + freqs job",
"name": "_set_std_settings",
"signature": "def _set_std_settings(self, geo_opt=False)"
},
{
"docstring": "Method that runs this job",
"name": "run",
"signature": "def run(self, init=True... | 2 | stack_v2_sparse_classes_30k_train_003289 | Implement the Python class `DFTJob` described below.
Class description:
Class used for geometry optimization + frequency jobs using DFT
Method signatures and docstrings:
- def _set_std_settings(self, geo_opt=False): Method that specifies standard settings for a DFT geometry optimization + freqs job
- def run(self, in... | Implement the Python class `DFTJob` described below.
Class description:
Class used for geometry optimization + frequency jobs using DFT
Method signatures and docstrings:
- def _set_std_settings(self, geo_opt=False): Method that specifies standard settings for a DFT geometry optimization + freqs job
- def run(self, in... | 30b64bd89023b8b7cdd37270bb8970b04c7a7081 | <|skeleton|>
class DFTJob:
"""Class used for geometry optimization + frequency jobs using DFT"""
def _set_std_settings(self, geo_opt=False):
"""Method that specifies standard settings for a DFT geometry optimization + freqs job"""
<|body_0|>
def run(self, init=True, path=None):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DFTJob:
"""Class used for geometry optimization + frequency jobs using DFT"""
def _set_std_settings(self, geo_opt=False):
"""Method that specifies standard settings for a DFT geometry optimization + freqs job"""
if geo_opt:
self.settings.input.Geometry
self.settings.in... | the_stack_v2_python_sparse | comparion data and code/modules/jobs.py | YHordijk/bachelorproject | train | 0 |
4b3868365dea2e67344d19503e9b90fc795b2f13 | [
"if USE_SUMMARY_DATA:\n mu = 2.8\n sigma = 0.3\nelse:\n mu = 2.8\n sigma = 0.85\npmf = thinkbayes2.MakeNormalPmf(mu, sigma, 4)\nthinkbayes2.Suite.__init__(self, pmf, label=label)",
"lam = hypo\nk = data\nlike = thinkbayes2.EvalPoissonPmf(k, lam)\nreturn like"
] | <|body_start_0|>
if USE_SUMMARY_DATA:
mu = 2.8
sigma = 0.3
else:
mu = 2.8
sigma = 0.85
pmf = thinkbayes2.MakeNormalPmf(mu, sigma, 4)
thinkbayes2.Suite.__init__(self, pmf, label=label)
<|end_body_0|>
<|body_start_1|>
lam = hypo
... | Represents hypotheses about the scoring rate for a team. | Hockey | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hockey:
"""Represents hypotheses about the scoring rate for a team."""
def __init__(self, label=None):
"""Initializes the Hockey object. label: string"""
<|body_0|>
def Likelihood(self, data, hypo):
"""Computes the likelihood of the data under the hypothesis. Eva... | stack_v2_sparse_classes_36k_train_028785 | 7,098 | permissive | [
{
"docstring": "Initializes the Hockey object. label: string",
"name": "__init__",
"signature": "def __init__(self, label=None)"
},
{
"docstring": "Computes the likelihood of the data under the hypothesis. Evaluates the Poisson PMF for lambda and k. hypo: goal scoring rate in goals per game data... | 2 | null | Implement the Python class `Hockey` described below.
Class description:
Represents hypotheses about the scoring rate for a team.
Method signatures and docstrings:
- def __init__(self, label=None): Initializes the Hockey object. label: string
- def Likelihood(self, data, hypo): Computes the likelihood of the data unde... | Implement the Python class `Hockey` described below.
Class description:
Represents hypotheses about the scoring rate for a team.
Method signatures and docstrings:
- def __init__(self, label=None): Initializes the Hockey object. label: string
- def Likelihood(self, data, hypo): Computes the likelihood of the data unde... | 53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f | <|skeleton|>
class Hockey:
"""Represents hypotheses about the scoring rate for a team."""
def __init__(self, label=None):
"""Initializes the Hockey object. label: string"""
<|body_0|>
def Likelihood(self, data, hypo):
"""Computes the likelihood of the data under the hypothesis. Eva... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Hockey:
"""Represents hypotheses about the scoring rate for a team."""
def __init__(self, label=None):
"""Initializes the Hockey object. label: string"""
if USE_SUMMARY_DATA:
mu = 2.8
sigma = 0.3
else:
mu = 2.8
sigma = 0.85
p... | the_stack_v2_python_sparse | python/learn/thinkbayes/hockey.py | qrsforever/workspace | train | 2 |
a1ce9297e106296f06ebe0eea12a302008a4aa00 | [
"template_id = kwargs.pop('template_id')\ntemplate = template_api.get_by_id(template_id, request=request)\nversion_manager = template.version_manager\nversion_number = version_manager_api.get_version_number(version_manager, template_id, request=request)\ntry:\n template_xsl_rendering = template_xsl_rendering_api... | <|body_start_0|>
template_id = kwargs.pop('template_id')
template = template_api.get_by_id(template_id, request=request)
version_manager = template.version_manager
version_number = version_manager_api.get_version_number(version_manager, template_id, request=request)
try:
... | Template XSL rendering view. | TemplateXSLRenderingView | [
"NIST-Software"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateXSLRenderingView:
"""Template XSL rendering view."""
def get(self, request, *args, **kwargs):
"""GET request. Create/Show the form for the configuration. Args: request: *args: **kwargs: Returns:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""P... | stack_v2_sparse_classes_36k_train_028786 | 35,208 | permissive | [
{
"docstring": "GET request. Create/Show the form for the configuration. Args: request: *args: **kwargs: Returns:",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "POST request. Try to save the configuration. Args: request: *args: **kwargs: Returns:",
... | 3 | null | Implement the Python class `TemplateXSLRenderingView` described below.
Class description:
Template XSL rendering view.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): GET request. Create/Show the form for the configuration. Args: request: *args: **kwargs: Returns:
- def post(self, request... | Implement the Python class `TemplateXSLRenderingView` described below.
Class description:
Template XSL rendering view.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): GET request. Create/Show the form for the configuration. Args: request: *args: **kwargs: Returns:
- def post(self, request... | f032036d95076f92b164389fdbec7415567e7b0f | <|skeleton|>
class TemplateXSLRenderingView:
"""Template XSL rendering view."""
def get(self, request, *args, **kwargs):
"""GET request. Create/Show the form for the configuration. Args: request: *args: **kwargs: Returns:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemplateXSLRenderingView:
"""Template XSL rendering view."""
def get(self, request, *args, **kwargs):
"""GET request. Create/Show the form for the configuration. Args: request: *args: **kwargs: Returns:"""
template_id = kwargs.pop('template_id')
template = template_api.get_by_id(t... | the_stack_v2_python_sparse | core_main_app/views/common/views.py | usnistgov/core_main_app | train | 3 |
7387bab29ac5d28b0c2f0d976b5a11cb4da7842b | [
"super(DialogProblems, self).__init__(parent=parent)\nself._parent = parent\nself._problems = problems\nself.style_sheet = None\nself.list = ListWidgetProblems(parent=self)\nself.button_ok = ButtonPrimary('Ok')\nself.frame_title_bar.setVisible(False)\nself.list.setFrameStyle(QFrame.NoFrame)\nself.list.setFrameShape... | <|body_start_0|>
super(DialogProblems, self).__init__(parent=parent)
self._parent = parent
self._problems = problems
self.style_sheet = None
self.list = ListWidgetProblems(parent=self)
self.button_ok = ButtonPrimary('Ok')
self.frame_title_bar.setVisible(False)
... | Dialog to display anaconda project problems. | DialogProblems | [
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DialogProblems:
"""Dialog to display anaconda project problems."""
def __init__(self, parent=None, problems=None):
"""Dialog to display anaconda project problems."""
<|body_0|>
def update_style_sheet(self, style_sheet=None):
"""Update custom css style sheets."""
... | stack_v2_sparse_classes_36k_train_028787 | 20,046 | permissive | [
{
"docstring": "Dialog to display anaconda project problems.",
"name": "__init__",
"signature": "def __init__(self, parent=None, problems=None)"
},
{
"docstring": "Update custom css style sheets.",
"name": "update_style_sheet",
"signature": "def update_style_sheet(self, style_sheet=None)... | 3 | null | Implement the Python class `DialogProblems` described below.
Class description:
Dialog to display anaconda project problems.
Method signatures and docstrings:
- def __init__(self, parent=None, problems=None): Dialog to display anaconda project problems.
- def update_style_sheet(self, style_sheet=None): Update custom ... | Implement the Python class `DialogProblems` described below.
Class description:
Dialog to display anaconda project problems.
Method signatures and docstrings:
- def __init__(self, parent=None, problems=None): Dialog to display anaconda project problems.
- def update_style_sheet(self, style_sheet=None): Update custom ... | 74476c9f00ee43338af696da7e9cd02b273f9005 | <|skeleton|>
class DialogProblems:
"""Dialog to display anaconda project problems."""
def __init__(self, parent=None, problems=None):
"""Dialog to display anaconda project problems."""
<|body_0|>
def update_style_sheet(self, style_sheet=None):
"""Update custom css style sheets."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DialogProblems:
"""Dialog to display anaconda project problems."""
def __init__(self, parent=None, problems=None):
"""Dialog to display anaconda project problems."""
super(DialogProblems, self).__init__(parent=parent)
self._parent = parent
self._problems = problems
... | the_stack_v2_python_sparse | python/anaconda/lib/python2.7/site-packages/anaconda_navigator/widgets/dialogs/projects.py | locolucco209/MongoScraper | train | 3 |
8bea32e0c40809e29ef954d409ad692cb05f4efc | [
"self.bank = dict()\nself.n_grams = []\nself.meta_tables = dict()\nself.alignment = dict()",
"sample, _ = self.bank['train'][0]\nfor table in sample.values():\n table.meta_table.n_records = len(table)",
"ret = list()\nfor _, sentences in self.bank[phase]:\n ret.extend(sentences)\n if len(ret) > limit:\... | <|body_start_0|>
self.bank = dict()
self.n_grams = []
self.meta_tables = dict()
self.alignment = dict()
<|end_body_0|>
<|body_start_1|>
sample, _ = self.bank['train'][0]
for table in sample.values():
table.meta_table.n_records = len(table)
<|end_body_1|>
<|b... | Scenarios | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scenarios:
def __init__(self):
"""Abstract constructor."""
<|body_0|>
def _record_count(self):
"""Count the number of records. :rtype: None"""
<|body_1|>
def extract_sentence(self, phase, limit=999999999):
"""Extract all sentences. :param str pha... | stack_v2_sparse_classes_36k_train_028788 | 957 | permissive | [
{
"docstring": "Abstract constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Count the number of records. :rtype: None",
"name": "_record_count",
"signature": "def _record_count(self)"
},
{
"docstring": "Extract all sentences. :param str phase:... | 3 | stack_v2_sparse_classes_30k_test_000613 | Implement the Python class `Scenarios` described below.
Class description:
Implement the Scenarios class.
Method signatures and docstrings:
- def __init__(self): Abstract constructor.
- def _record_count(self): Count the number of records. :rtype: None
- def extract_sentence(self, phase, limit=999999999): Extract all... | Implement the Python class `Scenarios` described below.
Class description:
Implement the Scenarios class.
Method signatures and docstrings:
- def __init__(self): Abstract constructor.
- def _record_count(self): Count the number of records. :rtype: None
- def extract_sentence(self, phase, limit=999999999): Extract all... | 4c46f8a8d2867712399ac7c0e7f7f34ef911a69a | <|skeleton|>
class Scenarios:
def __init__(self):
"""Abstract constructor."""
<|body_0|>
def _record_count(self):
"""Count the number of records. :rtype: None"""
<|body_1|>
def extract_sentence(self, phase, limit=999999999):
"""Extract all sentences. :param str pha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scenarios:
def __init__(self):
"""Abstract constructor."""
self.bank = dict()
self.n_grams = []
self.meta_tables = dict()
self.alignment = dict()
def _record_count(self):
"""Count the number of records. :rtype: None"""
sample, _ = self.bank['train']... | the_stack_v2_python_sparse | preprocess/Scenarios.py | hiaoxui/D2T-Grounding | train | 15 | |
c0b4c87aaa163e72d45bcdf5d48a4ca8405bffde | [
"base_dir = os.path.dirname(os.path.abspath(__file__))\nbase_app.__init__(self, base_dir)\nbase_app.index.im_func.exposed = True\nbase_app.input_select.im_func.exposed = True\nbase_app.input_upload.im_func.exposed = True\nbase_app.params.im_func.exposed = True\nbase_app.result.im_func.exposed = True\nself.timestamp... | <|body_start_0|>
base_dir = os.path.dirname(os.path.abspath(__file__))
base_app.__init__(self, base_dir)
base_app.index.im_func.exposed = True
base_app.input_select.im_func.exposed = True
base_app.input_upload.im_func.exposed = True
base_app.params.im_func.exposed = True
... | Automatic Lens Distortion Correction Using One Parameter Division Models app | app | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class app:
"""Automatic Lens Distortion Correction Using One Parameter Division Models app"""
def __init__(self):
"""app setup"""
<|body_0|>
def build(self):
"""program build/update"""
<|body_1|>
def params(self, newrun=False, msg=None):
"""configu... | stack_v2_sparse_classes_36k_train_028789 | 8,364 | no_license | [
{
"docstring": "app setup",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "program build/update",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "configure the algo execution",
"name": "params",
"signature": "def params(self, n... | 6 | null | Implement the Python class `app` described below.
Class description:
Automatic Lens Distortion Correction Using One Parameter Division Models app
Method signatures and docstrings:
- def __init__(self): app setup
- def build(self): program build/update
- def params(self, newrun=False, msg=None): configure the algo exe... | Implement the Python class `app` described below.
Class description:
Automatic Lens Distortion Correction Using One Parameter Division Models app
Method signatures and docstrings:
- def __init__(self): app setup
- def build(self): program build/update
- def params(self, newrun=False, msg=None): configure the algo exe... | 1ee176ad8578be2f0d48d2ffcacf7a0073e1b630 | <|skeleton|>
class app:
"""Automatic Lens Distortion Correction Using One Parameter Division Models app"""
def __init__(self):
"""app setup"""
<|body_0|>
def build(self):
"""program build/update"""
<|body_1|>
def params(self, newrun=False, msg=None):
"""configu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class app:
"""Automatic Lens Distortion Correction Using One Parameter Division Models app"""
def __init__(self):
"""app setup"""
base_dir = os.path.dirname(os.path.abspath(__file__))
base_app.__init__(self, base_dir)
base_app.index.im_func.exposed = True
base_app.input_... | the_stack_v2_python_sparse | app/106/app.py | nilx/ipol_demo | train | 1 |
74c3421712d658d3d0f656ead4382a1a05bacf19 | [
"if isinstance(info, dict):\n info = VirtualMachine.VirtualMachineError.FormatDebugInfo(info, error_message)\n return cls(info)\nraise TypeError('The argument of FromDebugInfo should be an instance of dictionary.')",
"sep = '\\n%s\\n' % ('-' * 65)\n\ndef AddHeader(error, header, message):\n error += '{se... | <|body_start_0|>
if isinstance(info, dict):
info = VirtualMachine.VirtualMachineError.FormatDebugInfo(info, error_message)
return cls(info)
raise TypeError('The argument of FromDebugInfo should be an instance of dictionary.')
<|end_body_0|>
<|body_start_1|>
sep = '\n%s\n... | An error raised when VM is having an issue. | VirtualMachineError | [
"Classpath-exception-2.0",
"BSD-3-Clause",
"AGPL-3.0-only",
"MIT",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VirtualMachineError:
"""An error raised when VM is having an issue."""
def FromDebugInfo(cls, info, error_message):
"""Create VirtualMachineError class from debug information. Args: info: A dictionary containing debug information (such as traceroute info). error_message: the error me... | stack_v2_sparse_classes_36k_train_028790 | 6,889 | permissive | [
{
"docstring": "Create VirtualMachineError class from debug information. Args: info: A dictionary containing debug information (such as traceroute info). error_message: the error message from the originating code. Returns: a cls exception class Raises: TypeError: if info is not an instance of dictionary.",
... | 2 | null | Implement the Python class `VirtualMachineError` described below.
Class description:
An error raised when VM is having an issue.
Method signatures and docstrings:
- def FromDebugInfo(cls, info, error_message): Create VirtualMachineError class from debug information. Args: info: A dictionary containing debug informati... | Implement the Python class `VirtualMachineError` described below.
Class description:
An error raised when VM is having an issue.
Method signatures and docstrings:
- def FromDebugInfo(cls, info, error_message): Create VirtualMachineError class from debug information. Args: info: A dictionary containing debug informati... | d0699f32998898757b036704fba39e5471641f01 | <|skeleton|>
class VirtualMachineError:
"""An error raised when VM is having an issue."""
def FromDebugInfo(cls, info, error_message):
"""Create VirtualMachineError class from debug information. Args: info: A dictionary containing debug information (such as traceroute info). error_message: the error me... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VirtualMachineError:
"""An error raised when VM is having an issue."""
def FromDebugInfo(cls, info, error_message):
"""Create VirtualMachineError class from debug information. Args: info: A dictionary containing debug information (such as traceroute info). error_message: the error message from th... | the_stack_v2_python_sparse | perfkitbenchmarker/errors.py | GoogleCloudPlatform/PerfKitBenchmarker | train | 1,923 |
679ed362b417426834e4a63c70aa986721ec2eeb | [
"self.stack = []\nself.flag = False\nvisited = [0] * numCourses\ncourses = {}\nfor x in prerequisites:\n courses[x[1]] = courses.get(x[1], []) + [x[0]]\nfor i in range(numCourses):\n self.DFS(i, numCourses, visited, courses)\nreturn self.stack[::-1] if not self.flag else []",
"if visited[i] != 0:\n if vi... | <|body_start_0|>
self.stack = []
self.flag = False
visited = [0] * numCourses
courses = {}
for x in prerequisites:
courses[x[1]] = courses.get(x[1], []) + [x[0]]
for i in range(numCourses):
self.DFS(i, numCourses, visited, courses)
return s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
"""https://www.youtube.com/watch?v=qe_pQCh09yU (course II) https://www.youtube.com/watch?v=kXy0ABd1vwo (course I) topological sorting. DAG: directed acyclic diagram O(V+E) V:vertex, E: edge good ... | stack_v2_sparse_classes_36k_train_028791 | 1,837 | no_license | [
{
"docstring": "https://www.youtube.com/watch?v=qe_pQCh09yU (course II) https://www.youtube.com/watch?v=kXy0ABd1vwo (course I) topological sorting. DAG: directed acyclic diagram O(V+E) V:vertex, E: edge good test examples: * [[1,0], [2,1], [3,2], [0,3]], cyclic * [[2,5],[0,5],[2,4],[1,4],[1,3],[3,0],[2,0]], sor... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: https://www.youtube.com/watch?v=qe_pQCh09yU (course II) https://www.youtube.com/watch?v=kXy0ABd... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: https://www.youtube.com/watch?v=qe_pQCh09yU (course II) https://www.youtube.com/watch?v=kXy0ABd... | 54d777e11b91c5debe49c1aef723234c66a5d2cc | <|skeleton|>
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
"""https://www.youtube.com/watch?v=qe_pQCh09yU (course II) https://www.youtube.com/watch?v=kXy0ABd1vwo (course I) topological sorting. DAG: directed acyclic diagram O(V+E) V:vertex, E: edge good ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
"""https://www.youtube.com/watch?v=qe_pQCh09yU (course II) https://www.youtube.com/watch?v=kXy0ABd1vwo (course I) topological sorting. DAG: directed acyclic diagram O(V+E) V:vertex, E: edge good test examples:... | the_stack_v2_python_sparse | leetcode_solution/graph/#210.Course_Schedule_II.py | HsiangHung/Code-Challenges | train | 0 | |
c120acd5af964ec3df331bad4fdbd6ba6a8889a2 | [
"super(BertIntermediate, self).__init__()\nself.dense = nn.Dense(config.hidden_size, config.intermediate_size).to_float(mindspore.float16)\nself.intermediate_act_fn = GeLU()\nself.cast = ops.Cast()",
"hidden_states = self.cast(hidden_states, mindspore.float16)\nhidden_states = self.dense(hidden_states)\nhidden_st... | <|body_start_0|>
super(BertIntermediate, self).__init__()
self.dense = nn.Dense(config.hidden_size, config.intermediate_size).to_float(mindspore.float16)
self.intermediate_act_fn = GeLU()
self.cast = ops.Cast()
<|end_body_0|>
<|body_start_1|>
hidden_states = self.cast(hidden_sta... | bert intermdiate fun | BertIntermediate | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertIntermediate:
"""bert intermdiate fun"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states):
"""construct fun"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(BertIntermediate, self).__init__()
... | stack_v2_sparse_classes_36k_train_028792 | 16,172 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "construct fun",
"name": "construct",
"signature": "def construct(self, hidden_states)"
}
] | 2 | null | Implement the Python class `BertIntermediate` described below.
Class description:
bert intermdiate fun
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states): construct fun | Implement the Python class `BertIntermediate` described below.
Class description:
bert intermdiate fun
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states): construct fun
<|skeleton|>
class BertIntermediate:
"""bert intermdiate fun"""
def __init__(sel... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class BertIntermediate:
"""bert intermdiate fun"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states):
"""construct fun"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BertIntermediate:
"""bert intermdiate fun"""
def __init__(self, config):
"""init fun"""
super(BertIntermediate, self).__init__()
self.dense = nn.Dense(config.hidden_size, config.intermediate_size).to_float(mindspore.float16)
self.intermediate_act_fn = GeLU()
self.c... | the_stack_v2_python_sparse | research/nlp/luke/src/luke/robert.py | mindspore-ai/models | train | 301 |
bb13fec6ce0926c6021ab9b3adfaa5ecd3266142 | [
"if 'AVALON_TASK' in session:\n return True\nreturn False",
"with pype.modified_environ(**session):\n app = lib.get_application(self.name)\n executable = lib.which(app['executable'])\n arguments = []\n tools_env = acre.get_tools([self.name])\n env = acre.compute(tools_env)\n env = acre.merge(... | <|body_start_0|>
if 'AVALON_TASK' in session:
return True
return False
<|end_body_0|>
<|body_start_1|>
with pype.modified_environ(**session):
app = lib.get_application(self.name)
executable = lib.which(app['executable'])
arguments = []
... | PremierePro | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PremierePro:
def is_compatible(self, session):
"""Return whether the action is compatible with the session"""
<|body_0|>
def process(self, session, **kwargs):
"""Implement the behavior for when the action is triggered Args: session (dict): environment dictionary Retu... | stack_v2_sparse_classes_36k_train_028793 | 2,565 | permissive | [
{
"docstring": "Return whether the action is compatible with the session",
"name": "is_compatible",
"signature": "def is_compatible(self, session)"
},
{
"docstring": "Implement the behavior for when the action is triggered Args: session (dict): environment dictionary Returns: Popen instance of n... | 2 | stack_v2_sparse_classes_30k_train_015436 | Implement the Python class `PremierePro` described below.
Class description:
Implement the PremierePro class.
Method signatures and docstrings:
- def is_compatible(self, session): Return whether the action is compatible with the session
- def process(self, session, **kwargs): Implement the behavior for when the actio... | Implement the Python class `PremierePro` described below.
Class description:
Implement the PremierePro class.
Method signatures and docstrings:
- def is_compatible(self, session): Return whether the action is compatible with the session
- def process(self, session, **kwargs): Implement the behavior for when the actio... | 47ef4b64f297186c6d929a8f56ecfb93dd0f44e8 | <|skeleton|>
class PremierePro:
def is_compatible(self, session):
"""Return whether the action is compatible with the session"""
<|body_0|>
def process(self, session, **kwargs):
"""Implement the behavior for when the action is triggered Args: session (dict): environment dictionary Retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PremierePro:
def is_compatible(self, session):
"""Return whether the action is compatible with the session"""
if 'AVALON_TASK' in session:
return True
return False
def process(self, session, **kwargs):
"""Implement the behavior for when the action is triggered ... | the_stack_v2_python_sparse | pype/plugins/launcher/actions/unused/PremierePro.py | jrsndl/pype | train | 1 | |
6ee1bb586d333e76bec486e80803a9f27b43ee60 | [
"self.Wh = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"t = np.exp(z - np.max(z))\nsf = t / t.sum(axis=1, keepdims=True)\nreturn sf",
"tanh_input = np.concatenate((h_prev, x_t), axis=1)\nh_next = np.tanh(np.dot(tanh_input, ... | <|body_start_0|>
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bh = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
t = np.exp(z - np.max(z))
sf = t / t.sum(axis=1, keepdims=True)
return sf
<|... | the class RNNCell | RNNCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNCell:
"""the class RNNCell"""
def __init__(self, i, h, o):
"""ARGS: -i is the dimensionality of the data -h is the dimensionality of the hidden state -o is the dimensionality of the outputs -Wh,Wy, bh, by :weights and biases of the cell -Wh and bh are for the concatenated hidden s... | stack_v2_sparse_classes_36k_train_028794 | 1,549 | no_license | [
{
"docstring": "ARGS: -i is the dimensionality of the data -h is the dimensionality of the hidden state -o is the dimensionality of the outputs -Wh,Wy, bh, by :weights and biases of the cell -Wh and bh are for the concatenated hidden state and input data -Wy and by are for the output",
"name": "__init__",
... | 3 | stack_v2_sparse_classes_30k_train_016111 | Implement the Python class `RNNCell` described below.
Class description:
the class RNNCell
Method signatures and docstrings:
- def __init__(self, i, h, o): ARGS: -i is the dimensionality of the data -h is the dimensionality of the hidden state -o is the dimensionality of the outputs -Wh,Wy, bh, by :weights and biases... | Implement the Python class `RNNCell` described below.
Class description:
the class RNNCell
Method signatures and docstrings:
- def __init__(self, i, h, o): ARGS: -i is the dimensionality of the data -h is the dimensionality of the hidden state -o is the dimensionality of the outputs -Wh,Wy, bh, by :weights and biases... | 7dafc37d306fcf2ea0f5af5bd97dfd78d388100c | <|skeleton|>
class RNNCell:
"""the class RNNCell"""
def __init__(self, i, h, o):
"""ARGS: -i is the dimensionality of the data -h is the dimensionality of the hidden state -o is the dimensionality of the outputs -Wh,Wy, bh, by :weights and biases of the cell -Wh and bh are for the concatenated hidden s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNCell:
"""the class RNNCell"""
def __init__(self, i, h, o):
"""ARGS: -i is the dimensionality of the data -h is the dimensionality of the hidden state -o is the dimensionality of the outputs -Wh,Wy, bh, by :weights and biases of the cell -Wh and bh are for the concatenated hidden state and inpu... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/0-rnn_cell.py | AndresSern/holbertonschool-machine_learning-1 | train | 0 |
f03ac6f1c5b3195905159d7351005912baf91630 | [
"super().__init__()\nself.flows = nn.LayerList()\nfor i in range(flows):\n self.flows.append(ResidualAffineCouplingLayer(in_channels=in_channels, hidden_channels=hidden_channels, kernel_size=kernel_size, base_dilation=base_dilation, layers=layers, stacks=1, global_channels=global_channels, dropout_rate=dropout_r... | <|body_start_0|>
super().__init__()
self.flows = nn.LayerList()
for i in range(flows):
self.flows.append(ResidualAffineCouplingLayer(in_channels=in_channels, hidden_channels=hidden_channels, kernel_size=kernel_size, base_dilation=base_dilation, layers=layers, stacks=1, global_channel... | Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`: https://ar... | ResidualAffineCouplingBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualAffineCouplingBlock:
"""Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversar... | stack_v2_sparse_classes_36k_train_028795 | 9,159 | permissive | [
{
"docstring": "Initilize ResidualAffineCouplingBlock module. Args: in_channels (int): Number of input channels. hidden_channels (int): Number of hidden channels. flows (int): Number of flows. kernel_size (int): Kernel size for WaveNet. base_dilation (int): Base dilation factor for WaveNet. layers (int): Number... | 2 | null | Implement the Python class `ResidualAffineCouplingBlock` described below.
Class description:
Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditiona... | Implement the Python class `ResidualAffineCouplingBlock` described below.
Class description:
Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditiona... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class ResidualAffineCouplingBlock:
"""Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResidualAffineCouplingBlock:
"""Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning ... | the_stack_v2_python_sparse | paddlespeech/t2s/models/vits/residual_coupling.py | anniyanvr/DeepSpeech-1 | train | 0 |
a9825ade439b5e76d1eb5f7c299325c652f11f0f | [
"self.pool_handle = await common.create_and_open_pool_ledger_for_steps(self.steps, self.pool_name, constant.pool_genesis_txn_file)\nself.wallet_handle = await common.create_and_open_wallet_for_steps(self.steps, self.wallet_name, self.pool_name)\nself.steps.add_step(\"Create and store did of default trustee as 'did_... | <|body_start_0|>
self.pool_handle = await common.create_and_open_pool_ledger_for_steps(self.steps, self.pool_name, constant.pool_genesis_txn_file)
self.wallet_handle = await common.create_and_open_wallet_for_steps(self.steps, self.wallet_name, self.pool_name)
self.steps.add_step("Create and stor... | TestInvalidSchema | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestInvalidSchema:
async def test_cannot_build_req_with_invalid_schema(self, schema_data):
"""Test all schema that make schema request cannot be built. :param schema_data:"""
<|body_0|>
async def test_cannot_submit_req_with_invalid_schema(self, schema_data):
"""Test ... | stack_v2_sparse_classes_36k_train_028796 | 7,304 | permissive | [
{
"docstring": "Test all schema that make schema request cannot be built. :param schema_data:",
"name": "test_cannot_build_req_with_invalid_schema",
"signature": "async def test_cannot_build_req_with_invalid_schema(self, schema_data)"
},
{
"docstring": "Test all schema that make the schema reque... | 2 | null | Implement the Python class `TestInvalidSchema` described below.
Class description:
Implement the TestInvalidSchema class.
Method signatures and docstrings:
- async def test_cannot_build_req_with_invalid_schema(self, schema_data): Test all schema that make schema request cannot be built. :param schema_data:
- async de... | Implement the Python class `TestInvalidSchema` described below.
Class description:
Implement the TestInvalidSchema class.
Method signatures and docstrings:
- async def test_cannot_build_req_with_invalid_schema(self, schema_data): Test all schema that make schema request cannot be built. :param schema_data:
- async de... | a19cb3c66f0adea6bb4c1fc20e1509cc97bd3d5f | <|skeleton|>
class TestInvalidSchema:
async def test_cannot_build_req_with_invalid_schema(self, schema_data):
"""Test all schema that make schema request cannot be built. :param schema_data:"""
<|body_0|>
async def test_cannot_submit_req_with_invalid_schema(self, schema_data):
"""Test ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestInvalidSchema:
async def test_cannot_build_req_with_invalid_schema(self, schema_data):
"""Test all schema that make schema request cannot be built. :param schema_data:"""
self.pool_handle = await common.create_and_open_pool_ledger_for_steps(self.steps, self.pool_name, constant.pool_genesis... | the_stack_v2_python_sparse | test_scripts/functional_tests/negative_and_boundary/schema_invalid_test.py | hyperledger-archives/indy-post-install-automation | train | 2 | |
d0f7ca20a7c3b2a626b99eb78da818fef4330d7b | [
"self.form_application_date = answer_dict['form_application_date']\nself.form_application_date = datetime.strptime(self.form_application_date, '%Y-%m-%d').date()\nself.email = answer_dict['email']\nself.sex = answer_dict['sex']\nself.birth_date = answer_dict['birth_date']\nself.household_income = answer_dict['house... | <|body_start_0|>
self.form_application_date = answer_dict['form_application_date']
self.form_application_date = datetime.strptime(self.form_application_date, '%Y-%m-%d').date()
self.email = answer_dict['email']
self.sex = answer_dict['sex']
self.birth_date = answer_dict['birth_da... | Model that takes all information from a participant answer to the research questionnaire | Questionnaire | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Questionnaire:
"""Model that takes all information from a participant answer to the research questionnaire"""
def __init__(self, answer_dict):
"""Every date attribute is according to this pattern: YYY-MM-DD"""
<|body_0|>
def get_bdi(self, category=True):
"""Retur... | stack_v2_sparse_classes_36k_train_028797 | 7,597 | no_license | [
{
"docstring": "Every date attribute is according to this pattern: YYY-MM-DD",
"name": "__init__",
"signature": "def __init__(self, answer_dict)"
},
{
"docstring": "Return the bdi category as a discrete category value if category is True, or the BDI original value if category is False. Return: 0... | 3 | stack_v2_sparse_classes_30k_train_002624 | Implement the Python class `Questionnaire` described below.
Class description:
Model that takes all information from a participant answer to the research questionnaire
Method signatures and docstrings:
- def __init__(self, answer_dict): Every date attribute is according to this pattern: YYY-MM-DD
- def get_bdi(self, ... | Implement the Python class `Questionnaire` described below.
Class description:
Model that takes all information from a participant answer to the research questionnaire
Method signatures and docstrings:
- def __init__(self, answer_dict): Every date attribute is according to this pattern: YYY-MM-DD
- def get_bdi(self, ... | 8cbb27f1118277c1898180d837ca9462c05320e4 | <|skeleton|>
class Questionnaire:
"""Model that takes all information from a participant answer to the research questionnaire"""
def __init__(self, answer_dict):
"""Every date attribute is according to this pattern: YYY-MM-DD"""
<|body_0|>
def get_bdi(self, category=True):
"""Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Questionnaire:
"""Model that takes all information from a participant answer to the research questionnaire"""
def __init__(self, answer_dict):
"""Every date attribute is according to this pattern: YYY-MM-DD"""
self.form_application_date = answer_dict['form_application_date']
self.... | the_stack_v2_python_sparse | readorsee/data/models.py | paulomann/ReadAndSee | train | 5 |
5ad7d83638a968bff55d0c73405012fd59fcba4d | [
"carry, res = (1, [])\nfor x in digits[::-1]:\n if carry == 0:\n res.append(x)\n else:\n carry, x = divmod(x + carry, 10)\n res.append(x)\nif carry:\n res.append(carry)\nreturn res[::-1]",
"carry, lens = (1, len(digits) - 1)\nfor i, x in enumerate(digits[::-1]):\n if carry == 0:\n... | <|body_start_0|>
carry, res = (1, [])
for x in digits[::-1]:
if carry == 0:
res.append(x)
else:
carry, x = divmod(x + carry, 10)
res.append(x)
if carry:
res.append(carry)
return res[::-1]
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plusOne1(self, digits: list) -> list:
"""使用新数组记录"""
<|body_0|>
def plusOne2(self, digits: list) -> list:
"""修改原数组"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
carry, res = (1, [])
for x in digits[::-1]:
if carry ... | stack_v2_sparse_classes_36k_train_028798 | 1,303 | no_license | [
{
"docstring": "使用新数组记录",
"name": "plusOne1",
"signature": "def plusOne1(self, digits: list) -> list"
},
{
"docstring": "修改原数组",
"name": "plusOne2",
"signature": "def plusOne2(self, digits: list) -> list"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne1(self, digits: list) -> list: 使用新数组记录
- def plusOne2(self, digits: list) -> list: 修改原数组 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne1(self, digits: list) -> list: 使用新数组记录
- def plusOne2(self, digits: list) -> list: 修改原数组
<|skeleton|>
class Solution:
def plusOne1(self, digits: list) -> list:
... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def plusOne1(self, digits: list) -> list:
"""使用新数组记录"""
<|body_0|>
def plusOne2(self, digits: list) -> list:
"""修改原数组"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def plusOne1(self, digits: list) -> list:
"""使用新数组记录"""
carry, res = (1, [])
for x in digits[::-1]:
if carry == 0:
res.append(x)
else:
carry, x = divmod(x + carry, 10)
res.append(x)
if carry:
... | the_stack_v2_python_sparse | 066_plus-one.py | helloocc/algorithm | train | 1 | |
7c2685859a31cb7cb635fb74b4549625d5749252 | [
"if user.is_government_user and user.has_perm('DOCUMENTS_GOVERNMENT_REVIEW') and (document.status.status in ['Received', 'Submitted']):\n return True\nif not user.is_government_user and (not privileged) and (document.status.status in ['Draft', 'Submitted']):\n return True\nreturn False",
"current_status = c... | <|body_start_0|>
if user.is_government_user and user.has_perm('DOCUMENTS_GOVERNMENT_REVIEW') and (document.status.status in ['Received', 'Submitted']):
return True
if not user.is_government_user and (not privileged) and (document.status.status in ['Draft', 'Submitted']):
return T... | Used by Viewset to check permissions for API requests | DocumentCommentPermissions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentCommentPermissions:
"""Used by Viewset to check permissions for API requests"""
def user_can_comment(user, document, privileged):
"""Check whether the user should have authority to add a comment. Government Users with abilities to review the documents should always have autho... | stack_v2_sparse_classes_36k_train_028799 | 4,753 | permissive | [
{
"docstring": "Check whether the user should have authority to add a comment. Government Users with abilities to review the documents should always have authority to add a comment, unless it's archived. Fuel Suppliers with abilities to add or submit can add a comment if the document is either in draft or submi... | 4 | stack_v2_sparse_classes_30k_train_008979 | Implement the Python class `DocumentCommentPermissions` described below.
Class description:
Used by Viewset to check permissions for API requests
Method signatures and docstrings:
- def user_can_comment(user, document, privileged): Check whether the user should have authority to add a comment. Government Users with a... | Implement the Python class `DocumentCommentPermissions` described below.
Class description:
Used by Viewset to check permissions for API requests
Method signatures and docstrings:
- def user_can_comment(user, document, privileged): Check whether the user should have authority to add a comment. Government Users with a... | 80ae1ef5938ef5e580128ed0c622071b307fc7e1 | <|skeleton|>
class DocumentCommentPermissions:
"""Used by Viewset to check permissions for API requests"""
def user_can_comment(user, document, privileged):
"""Check whether the user should have authority to add a comment. Government Users with abilities to review the documents should always have autho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DocumentCommentPermissions:
"""Used by Viewset to check permissions for API requests"""
def user_can_comment(user, document, privileged):
"""Check whether the user should have authority to add a comment. Government Users with abilities to review the documents should always have authority to add a... | the_stack_v2_python_sparse | backend/api/permissions/DocumentComment.py | kuanfandevops/tfrs | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.