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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
02c384edbe10f3eb243f3ef56c90f36b17d24a08 | [
"super().__init__()\nif not isinstance(source_resource.storage_url, storage_url.CloudUrl) or not isinstance(destination_resource.storage_url, storage_url.CloudUrl):\n raise ValueError('DaisyChainCopyTask is for copies between cloud providers.')\nself._source_resource = source_resource\nself._destination_resource... | <|body_start_0|>
super().__init__()
if not isinstance(source_resource.storage_url, storage_url.CloudUrl) or not isinstance(destination_resource.storage_url, storage_url.CloudUrl):
raise ValueError('DaisyChainCopyTask is for copies between cloud providers.')
self._source_resource = so... | Represents an operation to copy by downloading and uploading. This task downloads from one cloud location and uplaods to another cloud location by keeping an in-memory buffer. | DaisyChainCopyTask | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DaisyChainCopyTask:
"""Represents an operation to copy by downloading and uploading. This task downloads from one cloud location and uplaods to another cloud location by keeping an in-memory buffer."""
def __init__(self, source_resource, destination_resource, user_request_args=None):
... | stack_v2_sparse_classes_36k_train_021000 | 17,228 | permissive | [
{
"docstring": "Initializes task. Args: source_resource (resource_reference.ObjectResource): Must contain the full object path of existing object. Directories will not be accepted. destination_resource (resource_reference.UnknownResource): Must contain the full object path. Object may not exist yet. Existing ob... | 3 | null | Implement the Python class `DaisyChainCopyTask` described below.
Class description:
Represents an operation to copy by downloading and uploading. This task downloads from one cloud location and uplaods to another cloud location by keeping an in-memory buffer.
Method signatures and docstrings:
- def __init__(self, sou... | Implement the Python class `DaisyChainCopyTask` described below.
Class description:
Represents an operation to copy by downloading and uploading. This task downloads from one cloud location and uplaods to another cloud location by keeping an in-memory buffer.
Method signatures and docstrings:
- def __init__(self, sou... | 060174026ac068b6442b6c58bedf5adc7bc549cb | <|skeleton|>
class DaisyChainCopyTask:
"""Represents an operation to copy by downloading and uploading. This task downloads from one cloud location and uplaods to another cloud location by keeping an in-memory buffer."""
def __init__(self, source_resource, destination_resource, user_request_args=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DaisyChainCopyTask:
"""Represents an operation to copy by downloading and uploading. This task downloads from one cloud location and uplaods to another cloud location by keeping an in-memory buffer."""
def __init__(self, source_resource, destination_resource, user_request_args=None):
"""Initializ... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/storage/tasks/cp/daisy_chain_copy_task.py | salewski/google-cloud-sdk | train | 0 |
caded07d490f3bcfc325fab4d47314fd06a3dec9 | [
"self.trans2id = {Del: 0, Ins: 1, Sub: 2}\ntry:\n for a, b in perturbation:\n assert isinstance(a, Del) or isinstance(a, Ins) or isinstance(a, Sub)\n assert isinstance(b, int)\nexcept:\n raise AttributeError('param perturbation %s is not in the correct form. Notice that we currently only support... | <|body_start_0|>
self.trans2id = {Del: 0, Ins: 1, Sub: 2}
try:
for a, b in perturbation:
assert isinstance(a, Del) or isinstance(a, Ins) or isinstance(a, Sub)
assert isinstance(b, int)
except:
raise AttributeError('param perturbation %s is ... | HotFlipAttackTree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HotFlipAttackTree:
def __init__(self, perturbation: list, use_random_aug=False):
"""General HotFlip Attack for trees (on TreeLSTM) :param list perturbation: A perturbation space specified in the DSL. For example, [(Sub(), 2), (Del(), 1)] means at most 2 Sub string transformations and at ... | stack_v2_sparse_classes_36k_train_021001 | 9,283 | permissive | [
{
"docstring": "General HotFlip Attack for trees (on TreeLSTM) :param list perturbation: A perturbation space specified in the DSL. For example, [(Sub(), 2), (Del(), 1)] means at most 2 Sub string transformations and at most 1 Del string transformation. Sub and Del are default string transformations (see transf... | 2 | stack_v2_sparse_classes_30k_train_002228 | Implement the Python class `HotFlipAttackTree` described below.
Class description:
Implement the HotFlipAttackTree class.
Method signatures and docstrings:
- def __init__(self, perturbation: list, use_random_aug=False): General HotFlip Attack for trees (on TreeLSTM) :param list perturbation: A perturbation space spec... | Implement the Python class `HotFlipAttackTree` described below.
Class description:
Implement the HotFlipAttackTree class.
Method signatures and docstrings:
- def __init__(self, perturbation: list, use_random_aug=False): General HotFlip Attack for trees (on TreeLSTM) :param list perturbation: A perturbation space spec... | b715d86ee71536b1e268b64db9173db1838f9edc | <|skeleton|>
class HotFlipAttackTree:
def __init__(self, perturbation: list, use_random_aug=False):
"""General HotFlip Attack for trees (on TreeLSTM) :param list perturbation: A perturbation space specified in the DSL. For example, [(Sub(), 2), (Del(), 1)] means at most 2 Sub string transformations and at ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HotFlipAttackTree:
def __init__(self, perturbation: list, use_random_aug=False):
"""General HotFlip Attack for trees (on TreeLSTM) :param list perturbation: A perturbation space specified in the DSL. For example, [(Sub(), 2), (Del(), 1)] means at most 2 Sub string transformations and at most 1 Del str... | the_stack_v2_python_sparse | src/DSL/specialized_HotFlip_trees.py | ForeverZyh/certified_lstms | train | 2 | |
9ceeaecd6eb28b8e2a803aeca3251367da63b365 | [
"TextStaticPanel.__init__(self, container, *args, **kwargs)\nself.attributes[-1].Destroy()\nself.attributes[-1] = wx.CheckBox(self, wx.ID_ANY)\nself._set_attributes(self.attributes)",
"attributes = []\nfor atr in self.attributes:\n attributes.append(atr.GetValue())\nreturn attributes",
"for text in self.get_... | <|body_start_0|>
TextStaticPanel.__init__(self, container, *args, **kwargs)
self.attributes[-1].Destroy()
self.attributes[-1] = wx.CheckBox(self, wx.ID_ANY)
self._set_attributes(self.attributes)
<|end_body_0|>
<|body_start_1|>
attributes = []
for atr in self.attributes:
... | StaticWorkplacePanel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StaticWorkplacePanel:
def __init__(self, container, *args, **kwargs):
"""The default constructor container: a data container object"""
<|body_0|>
def get_attributes(self):
"""Return a list of all attributes. return: a list, that contains this panel's attribute values... | stack_v2_sparse_classes_36k_train_021002 | 11,497 | no_license | [
{
"docstring": "The default constructor container: a data container object",
"name": "__init__",
"signature": "def __init__(self, container, *args, **kwargs)"
},
{
"docstring": "Return a list of all attributes. return: a list, that contains this panel's attribute values.",
"name": "get_attri... | 3 | null | Implement the Python class `StaticWorkplacePanel` described below.
Class description:
Implement the StaticWorkplacePanel class.
Method signatures and docstrings:
- def __init__(self, container, *args, **kwargs): The default constructor container: a data container object
- def get_attributes(self): Return a list of al... | Implement the Python class `StaticWorkplacePanel` described below.
Class description:
Implement the StaticWorkplacePanel class.
Method signatures and docstrings:
- def __init__(self, container, *args, **kwargs): The default constructor container: a data container object
- def get_attributes(self): Return a list of al... | 781ce419b51b5bd99bbd1b155c03843cb434cb8c | <|skeleton|>
class StaticWorkplacePanel:
def __init__(self, container, *args, **kwargs):
"""The default constructor container: a data container object"""
<|body_0|>
def get_attributes(self):
"""Return a list of all attributes. return: a list, that contains this panel's attribute values... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StaticWorkplacePanel:
def __init__(self, container, *args, **kwargs):
"""The default constructor container: a data container object"""
TextStaticPanel.__init__(self, container, *args, **kwargs)
self.attributes[-1].Destroy()
self.attributes[-1] = wx.CheckBox(self, wx.ID_ANY)
... | the_stack_v2_python_sparse | gui/static_data.py | mcepar1/Scheduler | train | 0 | |
b6c3c67c7269b50387c5bc9ae708004357ee5d9f | [
"if not num_rows:\n return [[]]\ntriangle = []\nfor row_num in range(num_rows):\n row = [None for _ in range(row_num + 1)]\n row[0], row[-1] = (1, 1)\n for i in range(1, len(row) - 1):\n row[i] = triangle[row_num - 1][i - 1] + triangle[row_num - 1][i]\n triangle.append(row)\nreturn triangle",
... | <|body_start_0|>
if not num_rows:
return [[]]
triangle = []
for row_num in range(num_rows):
row = [None for _ in range(row_num + 1)]
row[0], row[-1] = (1, 1)
for i in range(1, len(row) - 1):
row[i] = triangle[row_num - 1][i - 1] + t... | Pascal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pascal:
def generate_triangle(self, num_rows: int) -> List[List[int]]:
"""Approach: DP Time Complexity: O(N^2) Space Complexity: O(N^2) :param num_rows: :return:"""
<|body_0|>
def generate(self, num_rows: int) -> List[List[int]]:
"""Approach: Time Complexity: O(N^2) ... | stack_v2_sparse_classes_36k_train_021003 | 1,233 | no_license | [
{
"docstring": "Approach: DP Time Complexity: O(N^2) Space Complexity: O(N^2) :param num_rows: :return:",
"name": "generate_triangle",
"signature": "def generate_triangle(self, num_rows: int) -> List[List[int]]"
},
{
"docstring": "Approach: Time Complexity: O(N^2) Space Complexity: O(N^2) :param... | 2 | null | Implement the Python class `Pascal` described below.
Class description:
Implement the Pascal class.
Method signatures and docstrings:
- def generate_triangle(self, num_rows: int) -> List[List[int]]: Approach: DP Time Complexity: O(N^2) Space Complexity: O(N^2) :param num_rows: :return:
- def generate(self, num_rows: ... | Implement the Python class `Pascal` described below.
Class description:
Implement the Pascal class.
Method signatures and docstrings:
- def generate_triangle(self, num_rows: int) -> List[List[int]]: Approach: DP Time Complexity: O(N^2) Space Complexity: O(N^2) :param num_rows: :return:
- def generate(self, num_rows: ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Pascal:
def generate_triangle(self, num_rows: int) -> List[List[int]]:
"""Approach: DP Time Complexity: O(N^2) Space Complexity: O(N^2) :param num_rows: :return:"""
<|body_0|>
def generate(self, num_rows: int) -> List[List[int]]:
"""Approach: Time Complexity: O(N^2) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pascal:
def generate_triangle(self, num_rows: int) -> List[List[int]]:
"""Approach: DP Time Complexity: O(N^2) Space Complexity: O(N^2) :param num_rows: :return:"""
if not num_rows:
return [[]]
triangle = []
for row_num in range(num_rows):
row = [None fo... | the_stack_v2_python_sparse | revisited_2021/arrays/pascals_triangle.py | Shiv2157k/leet_code | train | 1 | |
cc74ad25502fa98ff6343a619261c0b017b04439 | [
"assert type(margin) == float\nassert 0 <= margin\nself.margin = margin",
"assert type(points_2d) == list\nfor elem in points_2d:\n assert len(elem) == 2\nbbox = self._compute_bounding_box(points_2d)\nassert len(bbox) == 4\nreturn bbox",
"max_x = max(map(lambda point: int(point[0]), points_2d))\nmin_x = min(... | <|body_start_0|>
assert type(margin) == float
assert 0 <= margin
self.margin = margin
<|end_body_0|>
<|body_start_1|>
assert type(points_2d) == list
for elem in points_2d:
assert len(elem) == 2
bbox = self._compute_bounding_box(points_2d)
assert len(b... | This class is the implementation of a square bounding box for 2D points. | BoundingBox | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoundingBox:
"""This class is the implementation of a square bounding box for 2D points."""
def __init__(self, margin=0.0):
""":param margin: The margin that will be added to the bounding box. Since it is squared the same amount is added in all directions. That amount is half of the ... | stack_v2_sparse_classes_36k_train_021004 | 2,053 | no_license | [
{
"docstring": ":param margin: The margin that will be added to the bounding box. Since it is squared the same amount is added in all directions. That amount is half of the margin",
"name": "__init__",
"signature": "def __init__(self, margin=0.0)"
},
{
"docstring": "The function computes the bou... | 3 | stack_v2_sparse_classes_30k_train_009549 | Implement the Python class `BoundingBox` described below.
Class description:
This class is the implementation of a square bounding box for 2D points.
Method signatures and docstrings:
- def __init__(self, margin=0.0): :param margin: The margin that will be added to the bounding box. Since it is squared the same amoun... | Implement the Python class `BoundingBox` described below.
Class description:
This class is the implementation of a square bounding box for 2D points.
Method signatures and docstrings:
- def __init__(self, margin=0.0): :param margin: The margin that will be added to the bounding box. Since it is squared the same amoun... | f5c2da86b126dbf8bcad81a4022c73d6e77f504e | <|skeleton|>
class BoundingBox:
"""This class is the implementation of a square bounding box for 2D points."""
def __init__(self, margin=0.0):
""":param margin: The margin that will be added to the bounding box. Since it is squared the same amount is added in all directions. That amount is half of the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BoundingBox:
"""This class is the implementation of a square bounding box for 2D points."""
def __init__(self, margin=0.0):
""":param margin: The margin that will be added to the bounding box. Since it is squared the same amount is added in all directions. That amount is half of the margin"""
... | the_stack_v2_python_sparse | CropPipeline/BoundingBoxes/tight_bounding_box.py | astorfi/mvc | train | 0 |
b194fd6ef5edaca01839b82883d5fd101d0e7493 | [
"self.cache = {}\nself.order = []\nself.capacity = capacity",
"if key in self.cache:\n if key != self.order[-1]:\n self.order.remove(key)\n self.order.append(key)\n return self.cache[key]\nelse:\n return -1",
"if key in self.cache:\n self.cache[key] = value\n if key != self.order[-1... | <|body_start_0|>
self.cache = {}
self.order = []
self.capacity = capacity
<|end_body_0|>
<|body_start_1|>
if key in self.cache:
if key != self.order[-1]:
self.order.remove(key)
self.order.append(key)
return self.cache[key]
... | 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: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_021005 | 2,489 | 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: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_017400 | 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: void | 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: void
<|sk... | 7a459e9742958e63be8886874904e5ab2489411a | <|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: void"""
<|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.cache = {}
self.order = []
self.capacity = capacity
def get(self, key):
""":type key: int :rtype: int"""
if key in self.cache:
if key != self.order[-1]:
self.... | the_stack_v2_python_sparse | Hard/146.py | Hellofafar/Leetcode | train | 6 | |
e260071b88e1e3db4901e5e49b3da716dd479f3d | [
"if not nums:\n return 0\nmax_sum = running_sum = nums[0]\nfor num in itertools.islice(nums, 1, None):\n running_sum = max(running_sum + num, num)\n max_sum = max(max_sum, running_sum)\nreturn max_sum",
"if not nums:\n return 0\nreturn reduce(lambda max_t, num: (max(max_t[0] + num, num), max(max_t[1],... | <|body_start_0|>
if not nums:
return 0
max_sum = running_sum = nums[0]
for num in itertools.islice(nums, 1, None):
running_sum = max(running_sum + num, num)
max_sum = max(max_sum, running_sum)
return max_sum
<|end_body_0|>
<|body_start_1|>
if ... | SolutionMaxSubArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionMaxSubArray:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArrayReduce(self, nums):
"""Advanced method :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:... | stack_v2_sparse_classes_36k_train_021006 | 2,488 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
},
{
"docstring": "Advanced method :type nums: List[int] :rtype: int",
"name": "maxSubArrayReduce",
"signature": "def maxSubArrayReduce(self, nums)"
}
] | 2 | null | Implement the Python class `SolutionMaxSubArray` described below.
Class description:
Implement the SolutionMaxSubArray class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int
- def maxSubArrayReduce(self, nums): Advanced method :type nums: List[int] :rtype: int | Implement the Python class `SolutionMaxSubArray` described below.
Class description:
Implement the SolutionMaxSubArray class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int
- def maxSubArrayReduce(self, nums): Advanced method :type nums: List[int] :rtype: int
<|ske... | ccc3d86000367f809fe34a1b000ec8bbe0506a36 | <|skeleton|>
class SolutionMaxSubArray:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArrayReduce(self, nums):
"""Advanced method :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolutionMaxSubArray:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
max_sum = running_sum = nums[0]
for num in itertools.islice(nums, 1, None):
running_sum = max(running_sum + num, num)
max_sum = ma... | the_stack_v2_python_sparse | arrays/maxsubarraysum.py | AdsophicSolutions/freecodecamp | train | 1 | |
72d4701be087bf41d2adbe10df69520779aa2db2 | [
"super().__init__()\nself._sample_keys = sample_keys\nself._dataset = dataset",
"name, dataset_index = get_sample_id(sample_dict)\nsample_values = self._dataset[dataset_index]\nif not isinstance(sample_values, Sequence):\n sample_values = [sample_values]\nassert len(self._sample_keys) == len(sample_values), f'... | <|body_start_0|>
super().__init__()
self._sample_keys = sample_keys
self._dataset = dataset
<|end_body_0|>
<|body_start_1|>
name, dataset_index = get_sample_id(sample_dict)
sample_values = self._dataset[dataset_index]
if not isinstance(sample_values, Sequence):
... | Op that extract data from pytorch dataset that returning sequence of values and adds those values to sample_dict | OpReadDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpReadDataset:
"""Op that extract data from pytorch dataset that returning sequence of values and adds those values to sample_dict"""
def __init__(self, dataset: Dataset, sample_keys: Sequence[str]):
""":param dataset: the pytorch dataset to convert. The dataset[i] expected to return... | stack_v2_sparse_classes_36k_train_021007 | 4,510 | permissive | [
{
"docstring": ":param dataset: the pytorch dataset to convert. The dataset[i] expected to return sequence of values or a single value :param sample_keys: sequence keys - naming each value returned by dataset[i]",
"name": "__init__",
"signature": "def __init__(self, dataset: Dataset, sample_keys: Sequen... | 2 | stack_v2_sparse_classes_30k_train_008543 | Implement the Python class `OpReadDataset` described below.
Class description:
Op that extract data from pytorch dataset that returning sequence of values and adds those values to sample_dict
Method signatures and docstrings:
- def __init__(self, dataset: Dataset, sample_keys: Sequence[str]): :param dataset: the pyto... | Implement the Python class `OpReadDataset` described below.
Class description:
Op that extract data from pytorch dataset that returning sequence of values and adds those values to sample_dict
Method signatures and docstrings:
- def __init__(self, dataset: Dataset, sample_keys: Sequence[str]): :param dataset: the pyto... | 8f22cd46c836245b9394b73ce2957afc03706bfc | <|skeleton|>
class OpReadDataset:
"""Op that extract data from pytorch dataset that returning sequence of values and adds those values to sample_dict"""
def __init__(self, dataset: Dataset, sample_keys: Sequence[str]):
""":param dataset: the pytorch dataset to convert. The dataset[i] expected to return... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpReadDataset:
"""Op that extract data from pytorch dataset that returning sequence of values and adds those values to sample_dict"""
def __init__(self, dataset: Dataset, sample_keys: Sequence[str]):
""":param dataset: the pytorch dataset to convert. The dataset[i] expected to return sequence of ... | the_stack_v2_python_sparse | fuse/data/datasets/dataset_wrap_seq_to_dict.py | BiomedSciAI/fuse-med-ml | train | 45 |
cc3d18bf9ef6e89f6122a6df06bc337f2051547c | [
"try:\n ec = self.tags.get('ec', 0)\n self.set_tag('ec', ec + 1)\n if tags is not None and isinstance(tags, dict):\n for key in tags:\n self.set_tag(key, tags[key])\nexcept Exception:\n logger.debug('span.mark_as_errored', exc_info=True)",
"try:\n ec = self.tags.get('ec', None)\n ... | <|body_start_0|>
try:
ec = self.tags.get('ec', 0)
self.set_tag('ec', ec + 1)
if tags is not None and isinstance(tags, dict):
for key in tags:
self.set_tag(key, tags[key])
except Exception:
logger.debug('span.mark_as_erro... | InstanaSpan | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanaSpan:
def mark_as_errored(self, tags=None):
"""Mark this span as errored. @param tags: optional tags to add to the span"""
<|body_0|>
def assure_errored(self):
"""Make sure that this span is marked as errored. @return: None"""
<|body_1|>
def log_e... | stack_v2_sparse_classes_36k_train_021008 | 24,069 | permissive | [
{
"docstring": "Mark this span as errored. @param tags: optional tags to add to the span",
"name": "mark_as_errored",
"signature": "def mark_as_errored(self, tags=None)"
},
{
"docstring": "Make sure that this span is marked as errored. @return: None",
"name": "assure_errored",
"signature... | 3 | stack_v2_sparse_classes_30k_val_000643 | Implement the Python class `InstanaSpan` described below.
Class description:
Implement the InstanaSpan class.
Method signatures and docstrings:
- def mark_as_errored(self, tags=None): Mark this span as errored. @param tags: optional tags to add to the span
- def assure_errored(self): Make sure that this span is marke... | Implement the Python class `InstanaSpan` described below.
Class description:
Implement the InstanaSpan class.
Method signatures and docstrings:
- def mark_as_errored(self, tags=None): Mark this span as errored. @param tags: optional tags to add to the span
- def assure_errored(self): Make sure that this span is marke... | 4b2d90baf67db3b923c23564590dabe89a0e41d2 | <|skeleton|>
class InstanaSpan:
def mark_as_errored(self, tags=None):
"""Mark this span as errored. @param tags: optional tags to add to the span"""
<|body_0|>
def assure_errored(self):
"""Make sure that this span is marked as errored. @return: None"""
<|body_1|>
def log_e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstanaSpan:
def mark_as_errored(self, tags=None):
"""Mark this span as errored. @param tags: optional tags to add to the span"""
try:
ec = self.tags.get('ec', 0)
self.set_tag('ec', ec + 1)
if tags is not None and isinstance(tags, dict):
for ... | the_stack_v2_python_sparse | instana/span.py | instana/python-sensor | train | 69 | |
734f2ebf461d2224a1bf3764aec326ceb6686102 | [
"if root == None:\n return '[null]'\nre, ls, levelCnt, lev = ([], [[root, 1]], 1, 0)\nwhile len(ls) > 0:\n p = ls.pop(0)\n if lev != p[1]:\n if levelCnt <= 0:\n break\n lev, levelCnt = (p[1], 0)\n if p[0] != None:\n re.append(str(p[0].val))\n ls.append([p[0].left, ... | <|body_start_0|>
if root == None:
return '[null]'
re, ls, levelCnt, lev = ([], [[root, 1]], 1, 0)
while len(ls) > 0:
p = ls.pop(0)
if lev != p[1]:
if levelCnt <= 0:
break
lev, levelCnt = (p[1], 0)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_021009 | 3,082 | 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 | stack_v2_sparse_classes_30k_train_018767 | 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:... | 737b9bac5a73c319e46cda8c3e9d729f734d7792 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root == None:
return '[null]'
re, ls, levelCnt, lev = ([], [[root, 1]], 1, 0)
while len(ls) > 0:
p = ls.pop(0)
if lev != p[1]:
... | the_stack_v2_python_sparse | leetcode/python/297-serialize-and-deserialize-binary-tree.py | iampkuhz/OnlineJudge_cpp | train | 0 | |
0d6258fd183701035f7a9d5ba101e0704e0b8223 | [
"maxLength = 0\nfor numUnique in range(1, 26):\n maxLength = max(self.longestSubstringOfRepeatChar(s, k, numUnique), maxLength)\nreturn maxLength",
"charMap = {}\nstart = 0\nnumUnique = 0\nnumNoLessThanK = 0\nmaxLength = 0\nfor end in range(len(s)):\n count = charMap.get(s[end], 0) + 1\n charMap[s[end]] ... | <|body_start_0|>
maxLength = 0
for numUnique in range(1, 26):
maxLength = max(self.longestSubstringOfRepeatChar(s, k, numUnique), maxLength)
return maxLength
<|end_body_0|>
<|body_start_1|>
charMap = {}
start = 0
numUnique = 0
numNoLessThanK = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def longestSubstringOfRepeatChar(self, s, k, numUniqueTarget):
""":type s: str :type k: int k repeat :type targetCount: int number of different characters :rtype: int""... | stack_v2_sparse_classes_36k_train_021010 | 1,571 | no_license | [
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "longestSubstring",
"signature": "def longestSubstring(self, s, k)"
},
{
"docstring": ":type s: str :type k: int k repeat :type targetCount: int number of different characters :rtype: int",
"name": "longestSubstringOfRepeatChar"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstringOfRepeatChar(self, s, k, numUniqueTarget): :type s: str :type k: int k repeat :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstringOfRepeatChar(self, s, k, numUniqueTarget): :type s: str :type k: int k repeat :type ... | c2fbf457d5da366c67c7a1f17fb2be9b2833d441 | <|skeleton|>
class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def longestSubstringOfRepeatChar(self, s, k, numUniqueTarget):
""":type s: str :type k: int k repeat :type targetCount: int number of different characters :rtype: int""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
maxLength = 0
for numUnique in range(1, 26):
maxLength = max(self.longestSubstringOfRepeatChar(s, k, numUnique), maxLength)
return maxLength
def longestSubstringOfRepeatChar... | the_stack_v2_python_sparse | mySolutions/395. Longest Substring with At Least K Repeating Characters/395. Longest Substring with At Least K Repeating Characters.py | brandonhyc/note_collection | train | 0 | |
1b6cfb0af8fd7570097c7061b38ccdfa551fa74d | [
"self.client = Client()\nself.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')\nself.test_user.is_superuser = True\nself.test_user.is_active = True\nself.test_user.save()\nself.assertEqual(self.test_user.is_superuser, True)\nlogin = self.client.login(username='testuser', password='t... | <|body_start_0|>
self.client = Client()
self.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')
self.test_user.is_superuser = True
self.test_user.is_active = True
self.test_user.save()
self.assertEqual(self.test_user.is_superuser, True)
... | LicenseViewTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LicenseViewTests:
def setUp(self):
"""Instantiate the test client. Creates a test user."""
<|body_0|>
def tearDown(self):
"""Depopulate created model instances from test database."""
<|body_1|>
def test_license_detail(self):
"""This tests the lic... | stack_v2_sparse_classes_36k_train_021011 | 24,415 | no_license | [
{
"docstring": "Instantiate the test client. Creates a test user.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Depopulate created model instances from test database.",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "This tests the ... | 5 | null | Implement the Python class `LicenseViewTests` described below.
Class description:
Implement the LicenseViewTests class.
Method signatures and docstrings:
- def setUp(self): Instantiate the test client. Creates a test user.
- def tearDown(self): Depopulate created model instances from test database.
- def test_license... | Implement the Python class `LicenseViewTests` described below.
Class description:
Implement the LicenseViewTests class.
Method signatures and docstrings:
- def setUp(self): Instantiate the test client. Creates a test user.
- def tearDown(self): Depopulate created model instances from test database.
- def test_license... | e2718e8def826c2927e258d01763040290077f16 | <|skeleton|>
class LicenseViewTests:
def setUp(self):
"""Instantiate the test client. Creates a test user."""
<|body_0|>
def tearDown(self):
"""Depopulate created model instances from test database."""
<|body_1|>
def test_license_detail(self):
"""This tests the lic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LicenseViewTests:
def setUp(self):
"""Instantiate the test client. Creates a test user."""
self.client = Client()
self.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')
self.test_user.is_superuser = True
self.test_user.is_active = True
... | the_stack_v2_python_sparse | reagents/tests.py | BridgesLab/ExperimentDB | train | 0 | |
9e975a91f23ffc051662d7fdaf27dbbb288286f5 | [
"self._parent = parent\nself.builder = gtk.Builder()\ndialogpath = os.path.join(os.path.dirname(__file__), 'dialog.glade')\nself.builder.add_from_file(dialogpath)\nself.window = self.builder.get_object('dialog')\nself.window.add_buttons(gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)\nif... | <|body_start_0|>
self._parent = parent
self.builder = gtk.Builder()
dialogpath = os.path.join(os.path.dirname(__file__), 'dialog.glade')
self.builder.add_from_file(dialogpath)
self.window = self.builder.get_object('dialog')
self.window.add_buttons(gtk.STOCK_OPEN, gtk.RESP... | rief | open_ru_loader_dialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class open_ru_loader_dialog:
"""rief"""
def __init__(self, parent):
"""rief \\param parent - loader_dialog class instance"""
<|body_0|>
def run(self):
"""rief run dialog, load data if necessary and hide window"""
<|body_1|>
def prepare_dialog(self):
... | stack_v2_sparse_classes_36k_train_021012 | 3,456 | no_license | [
{
"docstring": "\brief \\\\param parent - loader_dialog class instance",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "\brief run dialog, load data if necessary and hide window",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "\br... | 5 | null | Implement the Python class `open_ru_loader_dialog` described below.
Class description:
rief
Method signatures and docstrings:
- def __init__(self, parent): rief \\param parent - loader_dialog class instance
- def run(self): rief run dialog, load data if necessary and hide window
- def prepare_dialog(self): rief f... | Implement the Python class `open_ru_loader_dialog` described below.
Class description:
rief
Method signatures and docstrings:
- def __init__(self, parent): rief \\param parent - loader_dialog class instance
- def run(self): rief run dialog, load data if necessary and hide window
- def prepare_dialog(self): rief f... | eb151afa9ee939ed7943da9eeed1e976ac816fec | <|skeleton|>
class open_ru_loader_dialog:
"""rief"""
def __init__(self, parent):
"""rief \\param parent - loader_dialog class instance"""
<|body_0|>
def run(self):
"""rief run dialog, load data if necessary and hide window"""
<|body_1|>
def prepare_dialog(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class open_ru_loader_dialog:
"""rief"""
def __init__(self, parent):
"""rief \\param parent - loader_dialog class instance"""
self._parent = parent
self.builder = gtk.Builder()
dialogpath = os.path.join(os.path.dirname(__file__), 'dialog.glade')
self.builder.add_from_fi... | the_stack_v2_python_sparse | src/loaders/open_ru/open_ru_loader_dialog.py | s9gf4ult/track-deal | train | 1 |
2899aff747f1c0272c7db9245565b82d2dab036f | [
"logger.info('Generating new ID for the new multicast group')\nID = uuid4().hex\nwhile ID in self._data:\n ID = uuid4().hex\nlogger.info('Validating query')\nInitMulticastGroupValidator.validate(query)\nlogger.info('Initialized multicast group %.8s from profile' % ID)\nconfiguration = query\nself._data[ID] = con... | <|body_start_0|>
logger.info('Generating new ID for the new multicast group')
ID = uuid4().hex
while ID in self._data:
ID = uuid4().hex
logger.info('Validating query')
InitMulticastGroupValidator.validate(query)
logger.info('Initialized multicast group %.8s fr... | Manager of multicast group state is a dict of multicast group. Keys are group IDs. For more information, please check the JSON schema. The class exposes methods of GET, CREATE, UPDATE and DELETE. All the WRITE operations should be performed w.r.t. given methods, but READ operations are always allowed. | MulticastGroupManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MulticastGroupManager:
"""Manager of multicast group state is a dict of multicast group. Keys are group IDs. For more information, please check the JSON schema. The class exposes methods of GET, CREATE, UPDATE and DELETE. All the WRITE operations should be performed w.r.t. given methods, but READ... | stack_v2_sparse_classes_36k_train_021013 | 3,548 | no_license | [
{
"docstring": "Create a multicast group. Parameters ---------- query : dict Multicast group parameters. Returns ------- info : dict A state dict of the multicast group.",
"name": "create",
"signature": "def create(self, query)"
},
{
"docstring": "Update a multicast group. Parameters ---------- ... | 3 | stack_v2_sparse_classes_30k_train_002883 | Implement the Python class `MulticastGroupManager` described below.
Class description:
Manager of multicast group state is a dict of multicast group. Keys are group IDs. For more information, please check the JSON schema. The class exposes methods of GET, CREATE, UPDATE and DELETE. All the WRITE operations should be p... | Implement the Python class `MulticastGroupManager` described below.
Class description:
Manager of multicast group state is a dict of multicast group. Keys are group IDs. For more information, please check the JSON schema. The class exposes methods of GET, CREATE, UPDATE and DELETE. All the WRITE operations should be p... | 85f8d5ba41bf4fa79abf7af25e533de846c3718f | <|skeleton|>
class MulticastGroupManager:
"""Manager of multicast group state is a dict of multicast group. Keys are group IDs. For more information, please check the JSON schema. The class exposes methods of GET, CREATE, UPDATE and DELETE. All the WRITE operations should be performed w.r.t. given methods, but READ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MulticastGroupManager:
"""Manager of multicast group state is a dict of multicast group. Keys are group IDs. For more information, please check the JSON schema. The class exposes methods of GET, CREATE, UPDATE and DELETE. All the WRITE operations should be performed w.r.t. given methods, but READ operations a... | the_stack_v2_python_sparse | backend/src/data/mcast.py | yf-yang/Net-Configurator | train | 1 |
1b32a71943ebd0ab60af7f4131810d85a084db2a | [
"if value_renderer_class is None:\n value_renderer_class = Value\nreturn super(List, cls).from_value_iterable(value_iterable=value_iterable, value_renderer_class=value_renderer_class, frame_renderer_class=frame_renderer_class, **listkwargs)",
"css_classes = super(List, self).get_base_css_classes_list()\ncss_cl... | <|body_start_0|>
if value_renderer_class is None:
value_renderer_class = Value
return super(List, cls).from_value_iterable(value_iterable=value_iterable, value_renderer_class=value_renderer_class, frame_renderer_class=frame_renderer_class, **listkwargs)
<|end_body_0|>
<|body_start_1|>
... | Renders a list for previewing selection in :class:`cradmin_legacy.viewhelpers.multiselect2.manytomanywidget.Widget`. | List | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class List:
"""Renders a list for previewing selection in :class:`cradmin_legacy.viewhelpers.multiselect2.manytomanywidget.Widget`."""
def from_value_iterable(cls, value_iterable, value_renderer_class=None, frame_renderer_class=None, **listkwargs):
"""Overrides :meth:`.cradmin_legacy.viewh... | stack_v2_sparse_classes_36k_train_021014 | 2,880 | permissive | [
{
"docstring": "Overrides :meth:`.cradmin_legacy.viewhelpers.listbuilder.base.List.from_value_iterable` to set :class:`.Value` as the default ``value_renderer_class``.",
"name": "from_value_iterable",
"signature": "def from_value_iterable(cls, value_iterable, value_renderer_class=None, frame_renderer_cl... | 2 | stack_v2_sparse_classes_30k_train_018410 | Implement the Python class `List` described below.
Class description:
Renders a list for previewing selection in :class:`cradmin_legacy.viewhelpers.multiselect2.manytomanywidget.Widget`.
Method signatures and docstrings:
- def from_value_iterable(cls, value_iterable, value_renderer_class=None, frame_renderer_class=No... | Implement the Python class `List` described below.
Class description:
Renders a list for previewing selection in :class:`cradmin_legacy.viewhelpers.multiselect2.manytomanywidget.Widget`.
Method signatures and docstrings:
- def from_value_iterable(cls, value_iterable, value_renderer_class=None, frame_renderer_class=No... | 31a9d114a2aed6cf1e54dac2e6a096c3503b4e3c | <|skeleton|>
class List:
"""Renders a list for previewing selection in :class:`cradmin_legacy.viewhelpers.multiselect2.manytomanywidget.Widget`."""
def from_value_iterable(cls, value_iterable, value_renderer_class=None, frame_renderer_class=None, **listkwargs):
"""Overrides :meth:`.cradmin_legacy.viewh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class List:
"""Renders a list for previewing selection in :class:`cradmin_legacy.viewhelpers.multiselect2.manytomanywidget.Widget`."""
def from_value_iterable(cls, value_iterable, value_renderer_class=None, frame_renderer_class=None, **listkwargs):
"""Overrides :meth:`.cradmin_legacy.viewhelpers.listbu... | the_stack_v2_python_sparse | cradmin_legacy/viewhelpers/multiselect2/widget_preview_renderer.py | appressoas/cradmin_legacy | train | 0 |
9606f016b37b2952441428714b13aca6895d55a8 | [
"q = collections.deque()\nq.append(root)\nres = []\nif not root:\n return ''\nwhile q:\n node = q.popleft()\n if not node:\n res.append('#')\n else:\n res.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\nwhile res[-1] == '#':\n res.pop()\nreturn ' '.join... | <|body_start_0|>
q = collections.deque()
q.append(root)
res = []
if not root:
return ''
while q:
node = q.popleft()
if not node:
res.append('#')
else:
res.append(str(node.val))
q.appen... | 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_021015 | 2,251 | 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:... | e890bd480de93418ce10867085b52137be2caa7a | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
q = collections.deque()
q.append(root)
res = []
if not root:
return ''
while q:
node = q.popleft()
if not node:
... | the_stack_v2_python_sparse | python/297.py | LichAmnesia/LeetCode | train | 0 | |
cf6ffee68ce51fa649af4f0c816608b8e4ee6bce | [
"def post_order(root, array):\n if not root:\n pass\n else:\n post_order(root.left, array)\n post_order(root.right, array)\n array.append(root.val)\n return array\nreturn ' '.join(map(str, post_order(root, [])))",
"def helper(low=float('-inf'), high=float('inf')):\n if not ... | <|body_start_0|>
def post_order(root, array):
if not root:
pass
else:
post_order(root.left, array)
post_order(root.right, array)
array.append(root.val)
return array
return ' '.join(map(str, post_order(roo... | 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|>
def post_order... | stack_v2_sparse_classes_36k_train_021016 | 3,114 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 1bcf3206cd3acc428ec690cb883c612aaf708aac | <|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."""
def post_order(root, array):
if not root:
pass
else:
post_order(root.left, array)
post_order(root.right, array)
ar... | the_stack_v2_python_sparse | problem-list/Tree/449.serialize-and-deserialize-bst.py | KevinChen1994/leetcode-algorithm | train | 2 | |
6cdb3adfdbc3a14202ca58d75f46d53aedf4b7cd | [
"seen = []\nwhile head:\n if head in seen:\n return True\n else:\n seen.append(head)\n head = head.next\nreturn False",
"if not head:\n return False\npointer1 = head\npointer2 = head.next\nwhile pointer1 != pointer2:\n if not pointer2 or not pointer2.next:\n return False\n p... | <|body_start_0|>
seen = []
while head:
if head in seen:
return True
else:
seen.append(head)
head = head.next
return False
<|end_body_0|>
<|body_start_1|>
if not head:
return False
pointer1 = head
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasCycle(self, head: ListNode) -> bool:
"""Hash table solution. Appends head instead of head.val because head records different objects. It is a solution to storing the same value to seen and having the same value show up in a different object. Time Complexity: O(n), Space ... | stack_v2_sparse_classes_36k_train_021017 | 1,398 | no_license | [
{
"docstring": "Hash table solution. Appends head instead of head.val because head records different objects. It is a solution to storing the same value to seen and having the same value show up in a different object. Time Complexity: O(n), Space Complexity: O(n)",
"name": "hasCycle",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_009792 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle(self, head: ListNode) -> bool: Hash table solution. Appends head instead of head.val because head records different objects. It is a solution to storing the same val... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle(self, head: ListNode) -> bool: Hash table solution. Appends head instead of head.val because head records different objects. It is a solution to storing the same val... | f33d004d7629d46fbc5670f5b384f8a604d7f1e7 | <|skeleton|>
class Solution:
def hasCycle(self, head: ListNode) -> bool:
"""Hash table solution. Appends head instead of head.val because head records different objects. It is a solution to storing the same value to seen and having the same value show up in a different object. Time Complexity: O(n), Space ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hasCycle(self, head: ListNode) -> bool:
"""Hash table solution. Appends head instead of head.val because head records different objects. It is a solution to storing the same value to seen and having the same value show up in a different object. Time Complexity: O(n), Space Complexity: O(... | the_stack_v2_python_sparse | Linked List Cycle.py | aulee888/LeetCode | train | 0 | |
cf66275eab2e795e4eb55cebce49343bb4c6325b | [
"self.config = config\nself.dotbot = dotbot\nself.bot = None\nself.logger = None\nself.azure_location = ''\nself.azure_subscription_key = ''\nself.logger_level = ''",
"self.bot = bot\nself.logger = DotFlow2LoggerAdapter(logging.getLogger('df2_ext.ssent_an'), self, self.bot, '$simpleSentimentAnalysis')\nbot.regist... | <|body_start_0|>
self.config = config
self.dotbot = dotbot
self.bot = None
self.logger = None
self.azure_location = ''
self.azure_subscription_key = ''
self.logger_level = ''
<|end_body_0|>
<|body_start_1|>
self.bot = bot
self.logger = DotFlow2Log... | ChatScript DotFlow2 function | DotFlow2MSCSSentimentAnalysis | [
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DotFlow2MSCSSentimentAnalysis:
"""ChatScript DotFlow2 function"""
def __init__(self, config: dict, dotbot: dict) -> None:
"""Initialize class"""
<|body_0|>
def init(self, bot: ChatbotEngine):
"""Initialize extension :param bot: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_021018 | 2,523 | permissive | [
{
"docstring": "Initialize class",
"name": "__init__",
"signature": "def __init__(self, config: dict, dotbot: dict) -> None"
},
{
"docstring": "Initialize extension :param bot: :return:",
"name": "init",
"signature": "def init(self, bot: ChatbotEngine)"
},
{
"docstring": "Detects... | 3 | null | Implement the Python class `DotFlow2MSCSSentimentAnalysis` described below.
Class description:
ChatScript DotFlow2 function
Method signatures and docstrings:
- def __init__(self, config: dict, dotbot: dict) -> None: Initialize class
- def init(self, bot: ChatbotEngine): Initialize extension :param bot: :return:
- def... | Implement the Python class `DotFlow2MSCSSentimentAnalysis` described below.
Class description:
ChatScript DotFlow2 function
Method signatures and docstrings:
- def __init__(self, config: dict, dotbot: dict) -> None: Initialize class
- def init(self, bot: ChatbotEngine): Initialize extension :param bot: :return:
- def... | b94ef5e75411ac4a214f5ac54d04ce00d9108ec0 | <|skeleton|>
class DotFlow2MSCSSentimentAnalysis:
"""ChatScript DotFlow2 function"""
def __init__(self, config: dict, dotbot: dict) -> None:
"""Initialize class"""
<|body_0|>
def init(self, bot: ChatbotEngine):
"""Initialize extension :param bot: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DotFlow2MSCSSentimentAnalysis:
"""ChatScript DotFlow2 function"""
def __init__(self, config: dict, dotbot: dict) -> None:
"""Initialize class"""
self.config = config
self.dotbot = dotbot
self.bot = None
self.logger = None
self.azure_location = ''
se... | the_stack_v2_python_sparse | engines/dotflow2/extensions/mscs_sentiment_analysis.py | SeedVault/rhizome | train | 8 |
248c173660460c1ea541e1c7c86e4271ede3fcc8 | [
"self._name = name\nself._weighted_slot = weighted_slot\nself._key = '%s:%s' % (force_text(self._weighted_slot), force_text(self._name))\nself._slot, self._crc = get_unique_slot_from_key(self._key)",
"if isinstance(that, int):\n return self._slot > that\nelif isinstance(that, RingNode):\n return self._slot ... | <|body_start_0|>
self._name = name
self._weighted_slot = weighted_slot
self._key = '%s:%s' % (force_text(self._weighted_slot), force_text(self._name))
self._slot, self._crc = get_unique_slot_from_key(self._key)
<|end_body_0|>
<|body_start_1|>
if isinstance(that, int):
... | Defines the Node object for the HashRing | RingNode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RingNode:
"""Defines the Node object for the HashRing"""
def __init__(self, name, weighted_slot):
"""Initializes the Node with name and weightage"""
<|body_0|>
def __gt__(self, that):
"""Definition for greater than This is used inside insort"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_021019 | 4,088 | permissive | [
{
"docstring": "Initializes the Node with name and weightage",
"name": "__init__",
"signature": "def __init__(self, name, weighted_slot)"
},
{
"docstring": "Definition for greater than This is used inside insort",
"name": "__gt__",
"signature": "def __gt__(self, that)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_004928 | Implement the Python class `RingNode` described below.
Class description:
Defines the Node object for the HashRing
Method signatures and docstrings:
- def __init__(self, name, weighted_slot): Initializes the Node with name and weightage
- def __gt__(self, that): Definition for greater than This is used inside insort
... | Implement the Python class `RingNode` described below.
Class description:
Defines the Node object for the HashRing
Method signatures and docstrings:
- def __init__(self, name, weighted_slot): Initializes the Node with name and weightage
- def __gt__(self, that): Definition for greater than This is used inside insort
... | f5af1b0a9ec6f3e95fd96adfd3ebb8703058ae71 | <|skeleton|>
class RingNode:
"""Defines the Node object for the HashRing"""
def __init__(self, name, weighted_slot):
"""Initializes the Node with name and weightage"""
<|body_0|>
def __gt__(self, that):
"""Definition for greater than This is used inside insort"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RingNode:
"""Defines the Node object for the HashRing"""
def __init__(self, name, weighted_slot):
"""Initializes the Node with name and weightage"""
self._name = name
self._weighted_slot = weighted_slot
self._key = '%s:%s' % (force_text(self._weighted_slot), force_text(sel... | the_stack_v2_python_sparse | django_redis_sdk/utils/hashring.py | midhuncnair/django_redis_sdk | train | 1 |
1721273ee26acd5efc5b6e084f073f876eb7691c | [
"self.capacity = capacity\nself.h = {}\nself.head = Node(None, None)\nself.tail = Node(None, None)\nself.head.next = self.tail\nself.tail.previous = self.head",
"if key in self.h:\n self.h[key].previous.next = self.h[key].next\n self.h[key].next.previous = self.h[key].previous\n self.h[key].next = self.h... | <|body_start_0|>
self.capacity = capacity
self.h = {}
self.head = Node(None, None)
self.tail = Node(None, None)
self.head.next = self.tail
self.tail.previous = self.head
<|end_body_0|>
<|body_start_1|>
if key in self.h:
self.h[key].previous.next = sel... | 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_021020 | 2,681 | 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... | 6c45f2de86a8af8259137c40808e826e07aba2d8 | <|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.capacity = capacity
self.h = {}
self.head = Node(None, None)
self.tail = Node(None, None)
self.head.next = self.tail
self.tail.previous = self.head
def get(self, key):
""... | the_stack_v2_python_sparse | 146. LRU Cache 138 Copy List with Random Pointer.py | kevicao/python | train | 1 | |
e1f18609127cb27249f632cf7a86026ec4719baf | [
"self.bar: BarData = None\nself.on_bar: Callable = on_bar\nself.interval: Interval = interval\nself.interval_count: int = 0\nself.window: int = window\nself.window_bar: BarData = None\nself.on_window_bar: Callable = on_window_bar\nself.last_tick: TickData = None\nself.last_bar: BarData = None",
"new_minute = Fals... | <|body_start_0|>
self.bar: BarData = None
self.on_bar: Callable = on_bar
self.interval: Interval = interval
self.interval_count: int = 0
self.window: int = window
self.window_bar: BarData = None
self.on_window_bar: Callable = on_window_bar
self.last_tick: ... | For: 1. generating 1 minute bar data from tick data 2. generateing x minute bar/x hour bar data from 1 minute data Notice: 1. for x minute bar, x must be able to divide 60: 2, 3, 5, 6, 10, 15, 20, 30 2. for x hour bar, x can be any number | BarGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BarGenerator:
"""For: 1. generating 1 minute bar data from tick data 2. generateing x minute bar/x hour bar data from 1 minute data Notice: 1. for x minute bar, x must be able to divide 60: 2, 3, 5, 6, 10, 15, 20, 30 2. for x hour bar, x can be any number"""
def __init__(self, on_bar: Callab... | stack_v2_sparse_classes_36k_train_021021 | 41,911 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, on_bar: Callable, window: int=0, on_window_bar: Callable=None, interval: Interval=Interval.MINUTE)"
},
{
"docstring": "Update new tick data into generator.",
"name": "update_tick",
"signature": "def update... | 4 | null | Implement the Python class `BarGenerator` described below.
Class description:
For: 1. generating 1 minute bar data from tick data 2. generateing x minute bar/x hour bar data from 1 minute data Notice: 1. for x minute bar, x must be able to divide 60: 2, 3, 5, 6, 10, 15, 20, 30 2. for x hour bar, x can be any number
M... | Implement the Python class `BarGenerator` described below.
Class description:
For: 1. generating 1 minute bar data from tick data 2. generateing x minute bar/x hour bar data from 1 minute data Notice: 1. for x minute bar, x must be able to divide 60: 2, 3, 5, 6, 10, 15, 20, 30 2. for x hour bar, x can be any number
M... | 7f4fd3cd202712b083ed7dc2f346ba4bb1bda6d7 | <|skeleton|>
class BarGenerator:
"""For: 1. generating 1 minute bar data from tick data 2. generateing x minute bar/x hour bar data from 1 minute data Notice: 1. for x minute bar, x must be able to divide 60: 2, 3, 5, 6, 10, 15, 20, 30 2. for x hour bar, x can be any number"""
def __init__(self, on_bar: Callab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BarGenerator:
"""For: 1. generating 1 minute bar data from tick data 2. generateing x minute bar/x hour bar data from 1 minute data Notice: 1. for x minute bar, x must be able to divide 60: 2, 3, 5, 6, 10, 15, 20, 30 2. for x hour bar, x can be any number"""
def __init__(self, on_bar: Callable, window: i... | the_stack_v2_python_sparse | vnpy/trader/utility.py | msincenselee/vnpy | train | 359 |
769ba3c26a12b5da98c7ac272498417e41cdc123 | [
"self.port = 5555\nself.host = ''\nself.addr = (self.host, self.port)\nself.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nself.p = self.connect()",
"try:\n self.client.connect(self.addr)\n return int(self.client.recv(2048).decode())\nexcept socket.error as e:\n code = e.errno\n error = s... | <|body_start_0|>
self.port = 5555
self.host = ''
self.addr = (self.host, self.port)
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.p = self.connect()
<|end_body_0|>
<|body_start_1|>
try:
self.client.connect(self.addr)
return ... | Network | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Network:
def __init__(self):
"""Initializes the object"""
<|body_0|>
def connect(self):
"""Connects to the server :return: int (player id)"""
<|body_1|>
def send(self, data):
"""Sends codes to server :return: Game"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_36k_train_021022 | 1,662 | no_license | [
{
"docstring": "Initializes the object",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Connects to the server :return: int (player id)",
"name": "connect",
"signature": "def connect(self)"
},
{
"docstring": "Sends codes to server :return: Game",
"na... | 3 | stack_v2_sparse_classes_30k_train_010634 | Implement the Python class `Network` described below.
Class description:
Implement the Network class.
Method signatures and docstrings:
- def __init__(self): Initializes the object
- def connect(self): Connects to the server :return: int (player id)
- def send(self, data): Sends codes to server :return: Game | Implement the Python class `Network` described below.
Class description:
Implement the Network class.
Method signatures and docstrings:
- def __init__(self): Initializes the object
- def connect(self): Connects to the server :return: int (player id)
- def send(self, data): Sends codes to server :return: Game
<|skele... | 3dd9f15fca25b41f20c94e7f1ece17b48f37a3fa | <|skeleton|>
class Network:
def __init__(self):
"""Initializes the object"""
<|body_0|>
def connect(self):
"""Connects to the server :return: int (player id)"""
<|body_1|>
def send(self, data):
"""Sends codes to server :return: Game"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Network:
def __init__(self):
"""Initializes the object"""
self.port = 5555
self.host = ''
self.addr = (self.host, self.port)
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.p = self.connect()
def connect(self):
"""Connects to th... | the_stack_v2_python_sparse | code/Memoria/Client/NetworkAssistant.py | StephanGuingor/Memory-GUI-Client-Server | train | 0 | |
1a22ba5e6fcfa02a21d5f2862e9b24eec49b1aed | [
"m = len(s)\nresults = []\nself.dfs(m, [], 0, s, results)\nreturn results",
"if ptr == m:\n results.append(parts[:])\n return\nfor ptr2 in range(ptr + 1, m + 1):\n if self.palindrome(s, ptr, ptr2):\n print(ptr, ptr2, s[ptr:ptr2])\n parts.append(s[ptr:ptr2])\n self.dfs(m, parts, ptr2,... | <|body_start_0|>
m = len(s)
results = []
self.dfs(m, [], 0, s, results)
return results
<|end_body_0|>
<|body_start_1|>
if ptr == m:
results.append(parts[:])
return
for ptr2 in range(ptr + 1, m + 1):
if self.palindrome(s, ptr, ptr2):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def partition(self, s):
""":type s: str :rtype: List[List[str]]"""
<|body_0|>
def dfs(self, m, parts, ptr, s, results):
"""parts: list of substrings of s ptr: starting index for next palindrome"""
<|body_1|>
def palindrome(self, s, start, end):... | stack_v2_sparse_classes_36k_train_021023 | 1,254 | no_license | [
{
"docstring": ":type s: str :rtype: List[List[str]]",
"name": "partition",
"signature": "def partition(self, s)"
},
{
"docstring": "parts: list of substrings of s ptr: starting index for next palindrome",
"name": "dfs",
"signature": "def dfs(self, m, parts, ptr, s, results)"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partition(self, s): :type s: str :rtype: List[List[str]]
- def dfs(self, m, parts, ptr, s, results): parts: list of substrings of s ptr: starting index for next palindrome
- ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partition(self, s): :type s: str :rtype: List[List[str]]
- def dfs(self, m, parts, ptr, s, results): parts: list of substrings of s ptr: starting index for next palindrome
- ... | e00cf94c5b86c8cca27e3bee69ad21e727b7679b | <|skeleton|>
class Solution:
def partition(self, s):
""":type s: str :rtype: List[List[str]]"""
<|body_0|>
def dfs(self, m, parts, ptr, s, results):
"""parts: list of substrings of s ptr: starting index for next palindrome"""
<|body_1|>
def palindrome(self, s, start, end):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def partition(self, s):
""":type s: str :rtype: List[List[str]]"""
m = len(s)
results = []
self.dfs(m, [], 0, s, results)
return results
def dfs(self, m, parts, ptr, s, results):
"""parts: list of substrings of s ptr: starting index for next palin... | the_stack_v2_python_sparse | backtracking/prob131.py | binchen15/leet-python | train | 1 | |
bc2dfa0aa1f1aa977745b410566de6a4f4166f92 | [
"super().__init__()\nself.dropout = tf.keras.layers.Dropout(dropout_rate)\nself.attention_heads1 = [GraphAttentionLayer(node_feature_dim, out_node_feature_dim, constant_attention) for _ in range(attention_heads)]\nself.attention_heads2 = [GraphAttentionLayer(out_node_feature_dim * attention_heads, out_node_feature_... | <|body_start_0|>
super().__init__()
self.dropout = tf.keras.layers.Dropout(dropout_rate)
self.attention_heads1 = [GraphAttentionLayer(node_feature_dim, out_node_feature_dim, constant_attention) for _ in range(attention_heads)]
self.attention_heads2 = [GraphAttentionLayer(out_node_feature... | A model that implements molecule classification via graph attention. #### References [1]: Petar Veličković, et. al. Graph Attention Networks. ICLR 2018. https://arxiv.org/abs/1710.10903 | GATModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GATModel:
"""A model that implements molecule classification via graph attention. #### References [1]: Petar Veličković, et. al. Graph Attention Networks. ICLR 2018. https://arxiv.org/abs/1710.10903"""
def __init__(self, attention_heads, node_feature_dim, out_node_feature_dim, readout_layer_... | stack_v2_sparse_classes_36k_train_021024 | 14,737 | permissive | [
{
"docstring": "Construct a graph attention model. Args: attention_heads: number (integer) of attention heads. node_feature_dim: dimension (integer) of incoming node level features. out_node_feature_dim: dimension (integer) of node level features outcoming from the attention layer. readout_layer_size: dimension... | 3 | null | Implement the Python class `GATModel` described below.
Class description:
A model that implements molecule classification via graph attention. #### References [1]: Petar Veličković, et. al. Graph Attention Networks. ICLR 2018. https://arxiv.org/abs/1710.10903
Method signatures and docstrings:
- def __init__(self, att... | Implement the Python class `GATModel` described below.
Class description:
A model that implements molecule classification via graph attention. #### References [1]: Petar Veličković, et. al. Graph Attention Networks. ICLR 2018. https://arxiv.org/abs/1710.10903
Method signatures and docstrings:
- def __init__(self, att... | f5f6f50f82bd441339c9d9efbef3f09e72c5fef6 | <|skeleton|>
class GATModel:
"""A model that implements molecule classification via graph attention. #### References [1]: Petar Veličković, et. al. Graph Attention Networks. ICLR 2018. https://arxiv.org/abs/1710.10903"""
def __init__(self, attention_heads, node_feature_dim, out_node_feature_dim, readout_layer_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GATModel:
"""A model that implements molecule classification via graph attention. #### References [1]: Petar Veličković, et. al. Graph Attention Networks. ICLR 2018. https://arxiv.org/abs/1710.10903"""
def __init__(self, attention_heads, node_feature_dim, out_node_feature_dim, readout_layer_size, num_cla... | the_stack_v2_python_sparse | uncertainty_baselines/models/gat.py | google/uncertainty-baselines | train | 1,235 |
95b3fceab4c4819328ec4740432265d3e218dec7 | [
"cmd = msg.split(' ')\nif msg.lower().strip().startswith('!tenta ') or msg.lower().strip().startswith('!penta ') or msg.lower().strip().startswith('!hentai '):\n if len(cmd) == 2:\n arg = cmd[1].strip()\n 'Check if arg is an emote.'\n if arg in bot.emotes.get_emotes():\n return Tr... | <|body_start_0|>
cmd = msg.split(' ')
if msg.lower().strip().startswith('!tenta ') or msg.lower().strip().startswith('!penta ') or msg.lower().strip().startswith('!hentai '):
if len(cmd) == 2:
arg = cmd[1].strip()
'Check if arg is an emote.'
if... | Reply with squid emotes or penta emotes. | TentaReply | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TentaReply:
"""Reply with squid emotes or penta emotes."""
def match(self, bot, user, msg, tag_info):
"""Match if the message starts with '!tenta ' or '!penta ' followed by an emote."""
<|body_0|>
def run(self, bot, user, msg, tag_info):
"""Reply with squid or pe... | stack_v2_sparse_classes_36k_train_021025 | 1,417 | permissive | [
{
"docstring": "Match if the message starts with '!tenta ' or '!penta ' followed by an emote.",
"name": "match",
"signature": "def match(self, bot, user, msg, tag_info)"
},
{
"docstring": "Reply with squid or penta message.",
"name": "run",
"signature": "def run(self, bot, user, msg, tag... | 2 | stack_v2_sparse_classes_30k_train_015461 | Implement the Python class `TentaReply` described below.
Class description:
Reply with squid emotes or penta emotes.
Method signatures and docstrings:
- def match(self, bot, user, msg, tag_info): Match if the message starts with '!tenta ' or '!penta ' followed by an emote.
- def run(self, bot, user, msg, tag_info): R... | Implement the Python class `TentaReply` described below.
Class description:
Reply with squid emotes or penta emotes.
Method signatures and docstrings:
- def match(self, bot, user, msg, tag_info): Match if the message starts with '!tenta ' or '!penta ' followed by an emote.
- def run(self, bot, user, msg, tag_info): R... | 6bef453bf5042401ecdafcdda404452dfd982ecf | <|skeleton|>
class TentaReply:
"""Reply with squid emotes or penta emotes."""
def match(self, bot, user, msg, tag_info):
"""Match if the message starts with '!tenta ' or '!penta ' followed by an emote."""
<|body_0|>
def run(self, bot, user, msg, tag_info):
"""Reply with squid or pe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TentaReply:
"""Reply with squid emotes or penta emotes."""
def match(self, bot, user, msg, tag_info):
"""Match if the message starts with '!tenta ' or '!penta ' followed by an emote."""
cmd = msg.split(' ')
if msg.lower().strip().startswith('!tenta ') or msg.lower().strip().starts... | the_stack_v2_python_sparse | bot/commands/tentareply.py | ghostduck/monkalot | train | 0 |
6e131255a5e2cf2d58e865f0a736daa9d308d1e1 | [
"from bokeh.util.deprecation import deprecated\ndeprecated(\"'from_py_func' is deprecated and will be removed in an eventual 2.0 release. Use CustomJSTransform directly instead.\")\nif not isinstance(func, FunctionType) or not isinstance(v_func, FunctionType):\n raise ValueError('CustomJSTransform.from_py_func o... | <|body_start_0|>
from bokeh.util.deprecation import deprecated
deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. Use CustomJSTransform directly instead.")
if not isinstance(func, FunctionType) or not isinstance(v_func, FunctionType):
raise Value... | Apply a custom defined transform to data. .. warning:: The explicit purpose of this Bokeh Model is to embed *raw JavaScript code* for a browser to execute. If any part of the code is derived from untrusted user inputs, then you must take appropriate care to sanitize the user input prior to passing to Bokeh. | CustomJSTransform | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomJSTransform:
"""Apply a custom defined transform to data. .. warning:: The explicit purpose of this Bokeh Model is to embed *raw JavaScript code* for a browser to execute. If any part of the code is derived from untrusted user inputs, then you must take appropriate care to sanitize the user... | stack_v2_sparse_classes_36k_train_021026 | 13,400 | permissive | [
{
"docstring": "Create a ``CustomJSTransform`` instance from a pair of Python functions. The function is translated to JavaScript using PScript. The python functions must have no positional arguments. It's possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword arguments to the functions. The ``f... | 2 | stack_v2_sparse_classes_30k_train_003638 | Implement the Python class `CustomJSTransform` described below.
Class description:
Apply a custom defined transform to data. .. warning:: The explicit purpose of this Bokeh Model is to embed *raw JavaScript code* for a browser to execute. If any part of the code is derived from untrusted user inputs, then you must tak... | Implement the Python class `CustomJSTransform` described below.
Class description:
Apply a custom defined transform to data. .. warning:: The explicit purpose of this Bokeh Model is to embed *raw JavaScript code* for a browser to execute. If any part of the code is derived from untrusted user inputs, then you must tak... | 1ad7ec05fb1e3676ac879585296c513c3ee50ef9 | <|skeleton|>
class CustomJSTransform:
"""Apply a custom defined transform to data. .. warning:: The explicit purpose of this Bokeh Model is to embed *raw JavaScript code* for a browser to execute. If any part of the code is derived from untrusted user inputs, then you must take appropriate care to sanitize the user... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomJSTransform:
"""Apply a custom defined transform to data. .. warning:: The explicit purpose of this Bokeh Model is to embed *raw JavaScript code* for a browser to execute. If any part of the code is derived from untrusted user inputs, then you must take appropriate care to sanitize the user input prior ... | the_stack_v2_python_sparse | Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/models/transforms.py | holzschu/Carnets | train | 541 |
f4bc479ce6564f62a032c892a5f4afbfa832db78 | [
"self.host = host\nself.header = header\nself.postSite = requests.session()\nself.rf = ManageConfig().getConfig('pds')",
"try:\n if r.status_code == 302 and self.rf['pds'] in r.headers['location']:\n header = json.loads(self.header)\n header['cookie'] = self.rf['pdscookie']\n self.postSite... | <|body_start_0|>
self.host = host
self.header = header
self.postSite = requests.session()
self.rf = ManageConfig().getConfig('pds')
<|end_body_0|>
<|body_start_1|>
try:
if r.status_code == 302 and self.rf['pds'] in r.headers['location']:
header = json... | 发送请求类 | sendRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sendRequest:
"""发送请求类"""
def __init__(self, host, header):
"""请求数据初始化 @host:请求的地址前缀 @header:请求头信息"""
<|body_0|>
def hooks(self, r, *args, **kwargs):
"""为解决302跨域跳转到pds时,不传cookie实现的钩子方法,人为指定cookie并去请求302跳转连接 :param r: 原始请求的响应信息 :param args: :param kwargs: :return: ... | stack_v2_sparse_classes_36k_train_021027 | 2,867 | no_license | [
{
"docstring": "请求数据初始化 @host:请求的地址前缀 @header:请求头信息",
"name": "__init__",
"signature": "def __init__(self, host, header)"
},
{
"docstring": "为解决302跨域跳转到pds时,不传cookie实现的钩子方法,人为指定cookie并去请求302跳转连接 :param r: 原始请求的响应信息 :param args: :param kwargs: :return: and \"Set-Cookie\" in r.headers.keys()",
... | 3 | stack_v2_sparse_classes_30k_train_009313 | Implement the Python class `sendRequest` described below.
Class description:
发送请求类
Method signatures and docstrings:
- def __init__(self, host, header): 请求数据初始化 @host:请求的地址前缀 @header:请求头信息
- def hooks(self, r, *args, **kwargs): 为解决302跨域跳转到pds时,不传cookie实现的钩子方法,人为指定cookie并去请求302跳转连接 :param r: 原始请求的响应信息 :param args: :pa... | Implement the Python class `sendRequest` described below.
Class description:
发送请求类
Method signatures and docstrings:
- def __init__(self, host, header): 请求数据初始化 @host:请求的地址前缀 @header:请求头信息
- def hooks(self, r, *args, **kwargs): 为解决302跨域跳转到pds时,不传cookie实现的钩子方法,人为指定cookie并去请求302跳转连接 :param r: 原始请求的响应信息 :param args: :pa... | c3af12063eea585afbfb97d1ef933a41f110c919 | <|skeleton|>
class sendRequest:
"""发送请求类"""
def __init__(self, host, header):
"""请求数据初始化 @host:请求的地址前缀 @header:请求头信息"""
<|body_0|>
def hooks(self, r, *args, **kwargs):
"""为解决302跨域跳转到pds时,不传cookie实现的钩子方法,人为指定cookie并去请求302跳转连接 :param r: 原始请求的响应信息 :param args: :param kwargs: :return: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class sendRequest:
"""发送请求类"""
def __init__(self, host, header):
"""请求数据初始化 @host:请求的地址前缀 @header:请求头信息"""
self.host = host
self.header = header
self.postSite = requests.session()
self.rf = ManageConfig().getConfig('pds')
def hooks(self, r, *args, **kwargs):
... | the_stack_v2_python_sparse | Webservice/BaseAutomationTestFramework_HB/util/HttpMethod.py | Simonluepang/Upgrading-is-the-happiest-thing | train | 1 |
d877c2032423b15c87fdc51be36f75182101048b | [
"if not SHOWPLOTS:\n return\nrad = 128\nzn_m = calc_zernike([1, 2, 3, 4, 5, 6], rad, mask=True)\nzn_unm = calc_zernike([1, 2, 3, 4, 5, 6], rad, mask=False)\nmask = mk_rad_mask(2 * rad) <= 1\ninter_imshow(zn_m, desc='Masked Zernike')\ninter_imshow(zn_unm, desc='Unmasked Zernike')",
"if not SHOWPLOTS:\n retur... | <|body_start_0|>
if not SHOWPLOTS:
return
rad = 128
zn_m = calc_zernike([1, 2, 3, 4, 5, 6], rad, mask=True)
zn_unm = calc_zernike([1, 2, 3, 4, 5, 6], rad, mask=False)
mask = mk_rad_mask(2 * rad) <= 1
inter_imshow(zn_m, desc='Masked Zernike')
inter_imsh... | PlotZernikes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotZernikes:
def test0a_masking(self):
"""Plot masking"""
<|body_0|>
def test1_plot_basis(self):
"""Plot the first few Zernike basis functions, until the user quits"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not SHOWPLOTS:
retur... | stack_v2_sparse_classes_36k_train_021028 | 13,631 | permissive | [
{
"docstring": "Plot masking",
"name": "test0a_masking",
"signature": "def test0a_masking(self)"
},
{
"docstring": "Plot the first few Zernike basis functions, until the user quits",
"name": "test1_plot_basis",
"signature": "def test1_plot_basis(self)"
}
] | 2 | null | Implement the Python class `PlotZernikes` described below.
Class description:
Implement the PlotZernikes class.
Method signatures and docstrings:
- def test0a_masking(self): Plot masking
- def test1_plot_basis(self): Plot the first few Zernike basis functions, until the user quits | Implement the Python class `PlotZernikes` described below.
Class description:
Implement the PlotZernikes class.
Method signatures and docstrings:
- def test0a_masking(self): Plot masking
- def test1_plot_basis(self): Plot the first few Zernike basis functions, until the user quits
<|skeleton|>
class PlotZernikes:
... | 7dd9b4424f47e6d78db9fd6fcb5a3db788b062f7 | <|skeleton|>
class PlotZernikes:
def test0a_masking(self):
"""Plot masking"""
<|body_0|>
def test1_plot_basis(self):
"""Plot the first few Zernike basis functions, until the user quits"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlotZernikes:
def test0a_masking(self):
"""Plot masking"""
if not SHOWPLOTS:
return
rad = 128
zn_m = calc_zernike([1, 2, 3, 4, 5, 6], rad, mask=True)
zn_unm = calc_zernike([1, 2, 3, 4, 5, 6], rad, mask=False)
mask = mk_rad_mask(2 * rad) <= 1
... | the_stack_v2_python_sparse | ZERNIKE/test_zern.py | srio/shadow3-scripts | train | 1 | |
4f7f29a5462632656f04f8baa03e1e0f7085c275 | [
"if not isinstance(data, np.ndarray):\n raise TypeError('data must be a 2D numpy.ndarray')\nif len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nd, n = data.shape\nself.mean = np.mean(data, axis=1,... | <|body_start_0|>
if not isinstance(data, np.ndarray):
raise TypeError('data must be a 2D numpy.ndarray')
if len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data points'... | multiNormal | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""multiNormal"""
def __init__(self, data):
"""Multivariate Normal distribution Set the public instance"""
<|body_0|>
def pdf(self, x):
"""calculates the PDF at a data point"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not isi... | stack_v2_sparse_classes_36k_train_021029 | 1,419 | no_license | [
{
"docstring": "Multivariate Normal distribution Set the public instance",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "calculates the PDF at a data point",
"name": "pdf",
"signature": "def pdf(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012106 | Implement the Python class `MultiNormal` described below.
Class description:
multiNormal
Method signatures and docstrings:
- def __init__(self, data): Multivariate Normal distribution Set the public instance
- def pdf(self, x): calculates the PDF at a data point | Implement the Python class `MultiNormal` described below.
Class description:
multiNormal
Method signatures and docstrings:
- def __init__(self, data): Multivariate Normal distribution Set the public instance
- def pdf(self, x): calculates the PDF at a data point
<|skeleton|>
class MultiNormal:
"""multiNormal"""
... | 7dafc37d306fcf2ea0f5af5bd97dfd78d388100c | <|skeleton|>
class MultiNormal:
"""multiNormal"""
def __init__(self, data):
"""Multivariate Normal distribution Set the public instance"""
<|body_0|>
def pdf(self, x):
"""calculates the PDF at a data point"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiNormal:
"""multiNormal"""
def __init__(self, data):
"""Multivariate Normal distribution Set the public instance"""
if not isinstance(data, np.ndarray):
raise TypeError('data must be a 2D numpy.ndarray')
if len(data.shape) != 2:
raise TypeError('data mu... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | AndresSern/holbertonschool-machine_learning-1 | train | 0 |
770bb01d6ee5335eaa2b75cfdb1c11c8a3b5a55f | [
"if not isinstance(p_object, FeedbackSet):\n raise ValueError('Appended object must be instance of FeedbackSet')\nsuper(FeedbackSetList, self).append(p_object)",
"best = None\nfor feedbackset in self:\n if not best:\n best = feedbackset\n elif best.grading_points < feedbackset.grading_points:\n ... | <|body_start_0|>
if not isinstance(p_object, FeedbackSet):
raise ValueError('Appended object must be instance of FeedbackSet')
super(FeedbackSetList, self).append(p_object)
<|end_body_0|>
<|body_start_1|>
best = None
for feedbackset in self:
if not best:
... | FeedbackSetList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedbackSetList:
def append(self, p_object):
"""Args: p_object: Returns:"""
<|body_0|>
def get_feedbackset_with_most_points(self):
"""Get the :obj:`~.devilry.devilry_group.models.FeedbackSet` with the most points. Returns: :obj:`~.devilry.devilry_group.models.Feedbac... | stack_v2_sparse_classes_36k_train_021030 | 21,904 | permissive | [
{
"docstring": "Args: p_object: Returns:",
"name": "append",
"signature": "def append(self, p_object)"
},
{
"docstring": "Get the :obj:`~.devilry.devilry_group.models.FeedbackSet` with the most points. Returns: :obj:`~.devilry.devilry_group.models.FeedbackSet` or None.",
"name": "get_feedbac... | 2 | stack_v2_sparse_classes_30k_train_017625 | Implement the Python class `FeedbackSetList` described below.
Class description:
Implement the FeedbackSetList class.
Method signatures and docstrings:
- def append(self, p_object): Args: p_object: Returns:
- def get_feedbackset_with_most_points(self): Get the :obj:`~.devilry.devilry_group.models.FeedbackSet` with th... | Implement the Python class `FeedbackSetList` described below.
Class description:
Implement the FeedbackSetList class.
Method signatures and docstrings:
- def append(self, p_object): Args: p_object: Returns:
- def get_feedbackset_with_most_points(self): Get the :obj:`~.devilry.devilry_group.models.FeedbackSet` with th... | a3355fe78992466cfcae8b166128bf51ddbb26d0 | <|skeleton|>
class FeedbackSetList:
def append(self, p_object):
"""Args: p_object: Returns:"""
<|body_0|>
def get_feedbackset_with_most_points(self):
"""Get the :obj:`~.devilry.devilry_group.models.FeedbackSet` with the most points. Returns: :obj:`~.devilry.devilry_group.models.Feedbac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeedbackSetList:
def append(self, p_object):
"""Args: p_object: Returns:"""
if not isinstance(p_object, FeedbackSet):
raise ValueError('Appended object must be instance of FeedbackSet')
super(FeedbackSetList, self).append(p_object)
def get_feedbackset_with_most_points(... | the_stack_v2_python_sparse | devilry/devilry_qualifiesforexam/utils/groups_groupedby_relatedstudent_and_assignments.py | devilry/devilry-django | train | 42 | |
24899d2c6c6690d10c646497ef51726edc76a766 | [
"super(PageCrawler, self).__init__(*args, **kwargs)\nself.spider_id = spider_id if spider_id else PageCrawler.DEFAULT_SPIDER_ID\nself.urls_file = urls_file if urls_file else PageCrawler.DEFAULT_URLS_FILE\nself.url_validator = URLValidator()",
"for script in soup(['script', 'style']):\n script.extract()\nsoup =... | <|body_start_0|>
super(PageCrawler, self).__init__(*args, **kwargs)
self.spider_id = spider_id if spider_id else PageCrawler.DEFAULT_SPIDER_ID
self.urls_file = urls_file if urls_file else PageCrawler.DEFAULT_URLS_FILE
self.url_validator = URLValidator()
<|end_body_0|>
<|body_start_1|>
... | A generic crawler that scrapes text and other stuff from webpages | PageCrawler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PageCrawler:
"""A generic crawler that scrapes text and other stuff from webpages"""
def __init__(self, spider_id=None, urls_file=None, *args, **kwargs):
"""Initialize spider arguments"""
<|body_0|>
def get_text(self, soup):
"""Given soup object, do preliminary c... | stack_v2_sparse_classes_36k_train_021031 | 3,657 | no_license | [
{
"docstring": "Initialize spider arguments",
"name": "__init__",
"signature": "def __init__(self, spider_id=None, urls_file=None, *args, **kwargs)"
},
{
"docstring": "Given soup object, do preliminary cleans and return the text parsed",
"name": "get_text",
"signature": "def get_text(sel... | 5 | stack_v2_sparse_classes_30k_train_009045 | Implement the Python class `PageCrawler` described below.
Class description:
A generic crawler that scrapes text and other stuff from webpages
Method signatures and docstrings:
- def __init__(self, spider_id=None, urls_file=None, *args, **kwargs): Initialize spider arguments
- def get_text(self, soup): Given soup obj... | Implement the Python class `PageCrawler` described below.
Class description:
A generic crawler that scrapes text and other stuff from webpages
Method signatures and docstrings:
- def __init__(self, spider_id=None, urls_file=None, *args, **kwargs): Initialize spider arguments
- def get_text(self, soup): Given soup obj... | 0dfc67abdbc6a8684189f334a6a52a6df91cb211 | <|skeleton|>
class PageCrawler:
"""A generic crawler that scrapes text and other stuff from webpages"""
def __init__(self, spider_id=None, urls_file=None, *args, **kwargs):
"""Initialize spider arguments"""
<|body_0|>
def get_text(self, soup):
"""Given soup object, do preliminary c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PageCrawler:
"""A generic crawler that scrapes text and other stuff from webpages"""
def __init__(self, spider_id=None, urls_file=None, *args, **kwargs):
"""Initialize spider arguments"""
super(PageCrawler, self).__init__(*args, **kwargs)
self.spider_id = spider_id if spider_id el... | the_stack_v2_python_sparse | crawler/crawler/spiders/page_crawler.py | tomwuvip/social-news-bigdata | train | 0 |
511c16c70b9a87c43de2a28773d220f8c0e157ba | [
"if request.user.is_authenticated and hasattr(request.user, 'profile'):\n return True\nreturn False",
"if type(obj) == UserProfileModel:\n if obj.account == request.user:\n return True\n return False\nif obj.user.account == request.user:\n return True\nreturn False"
] | <|body_start_0|>
if request.user.is_authenticated and hasattr(request.user, 'profile'):
return True
return False
<|end_body_0|>
<|body_start_1|>
if type(obj) == UserProfileModel:
if obj.account == request.user:
return True
return False
... | The Permission class used by UserAddressView. | UserAddressPermissions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAddressPermissions:
"""The Permission class used by UserAddressView."""
def has_permission(self, request, view):
"""Checks if the user is authenticated and has a valid profile, because that account may be other type like a driver, shop or an admin."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_021032 | 1,859 | permissive | [
{
"docstring": "Checks if the user is authenticated and has a valid profile, because that account may be other type like a driver, shop or an admin.",
"name": "has_permission",
"signature": "def has_permission(self, request, view)"
},
{
"docstring": "Checks if the user has the permissions to see... | 2 | stack_v2_sparse_classes_30k_train_011229 | Implement the Python class `UserAddressPermissions` described below.
Class description:
The Permission class used by UserAddressView.
Method signatures and docstrings:
- def has_permission(self, request, view): Checks if the user is authenticated and has a valid profile, because that account may be other type like a ... | Implement the Python class `UserAddressPermissions` described below.
Class description:
The Permission class used by UserAddressView.
Method signatures and docstrings:
- def has_permission(self, request, view): Checks if the user is authenticated and has a valid profile, because that account may be other type like a ... | 7c361a31c5225c6ad649fcf92e323bdb10cc4c16 | <|skeleton|>
class UserAddressPermissions:
"""The Permission class used by UserAddressView."""
def has_permission(self, request, view):
"""Checks if the user is authenticated and has a valid profile, because that account may be other type like a driver, shop or an admin."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserAddressPermissions:
"""The Permission class used by UserAddressView."""
def has_permission(self, request, view):
"""Checks if the user is authenticated and has a valid profile, because that account may be other type like a driver, shop or an admin."""
if request.user.is_authenticated ... | the_stack_v2_python_sparse | users/permissions.py | ahmed-alllam/Koshkie-Server | train | 0 |
379ba69cae731f4d850c101a3b22b41efc830444 | [
"print('test_login1_normal is star test...')\npo = LoginPage(self.driver)\npo.Login_action('qiu98795', 456852)\nsleep(2)\nself.assertEqual(po.type_loginPass_hint(), '好友')\nfunction.insert_img(self.driver, 'warp_login1_normal.jpg')\nprint('test_login1_normal test end!')",
"print('test_login2_passwdError is start t... | <|body_start_0|>
print('test_login1_normal is star test...')
po = LoginPage(self.driver)
po.Login_action('qiu98795', 456852)
sleep(2)
self.assertEqual(po.type_loginPass_hint(), '好友')
function.insert_img(self.driver, 'warp_login1_normal.jpg')
print('test_login1_nor... | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
def test_login1_normal(self):
"""username and passwd isnormal"""
<|body_0|>
def test_login2_PasswdError(self):
"""username is ok,passwd is error"""
<|body_1|>
def test_login3_empty(self):
"""username and passwd is empty"""
<|bo... | stack_v2_sparse_classes_36k_train_021033 | 1,691 | no_license | [
{
"docstring": "username and passwd isnormal",
"name": "test_login1_normal",
"signature": "def test_login1_normal(self)"
},
{
"docstring": "username is ok,passwd is error",
"name": "test_login2_PasswdError",
"signature": "def test_login2_PasswdError(self)"
},
{
"docstring": "user... | 3 | stack_v2_sparse_classes_30k_train_020959 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login1_normal(self): username and passwd isnormal
- def test_login2_PasswdError(self): username is ok,passwd is error
- def test_login3_empty(self): username and passw... | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login1_normal(self): username and passwd isnormal
- def test_login2_PasswdError(self): username is ok,passwd is error
- def test_login3_empty(self): username and passw... | 39d01be679b75fc7488892f63a5ac114ccefc576 | <|skeleton|>
class TestLogin:
def test_login1_normal(self):
"""username and passwd isnormal"""
<|body_0|>
def test_login2_PasswdError(self):
"""username is ok,passwd is error"""
<|body_1|>
def test_login3_empty(self):
"""username and passwd is empty"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLogin:
def test_login1_normal(self):
"""username and passwd isnormal"""
print('test_login1_normal is star test...')
po = LoginPage(self.driver)
po.Login_action('qiu98795', 456852)
sleep(2)
self.assertEqual(po.type_loginPass_hint(), '好友')
function.ins... | the_stack_v2_python_sparse | AutoTest_project/Website/test_case/test_login.py | qiu98795/webdriver_find_element | train | 0 | |
d45662f4dd4be5a127e11579b8d510877b610a82 | [
"self.ss = ss\nself.n_step = n_step\nself.interval = step_interval\nself.step_time = step_time\nself.saw_time = saw_time",
"lB = self.interval[0]\nuB = self.interval[1]\nstep_vector = [round(uniform(lB, uB), 1) for _ in range(self.n_step)]\nstep_vector[0] = self.ss\nu = np.zeros(shape=dim)\nj = 0\nramp_Step = sel... | <|body_start_0|>
self.ss = ss
self.n_step = n_step
self.interval = step_interval
self.step_time = step_time
self.saw_time = saw_time
<|end_body_0|>
<|body_start_1|>
lB = self.interval[0]
uB = self.interval[1]
step_vector = [round(uniform(lB, uB), 1) for _... | SawRandStep | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SawRandStep:
def __init__(self, step_time, saw_time, step_interval=None, n_step=None, ss=None):
"""Settings for a random step sequence Args: step_interval (list): Probability interval <a, b> step_time: Time to perform step change n_step (int): Number of steps"""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_021034 | 8,036 | no_license | [
{
"docstring": "Settings for a random step sequence Args: step_interval (list): Probability interval <a, b> step_time: Time to perform step change n_step (int): Number of steps",
"name": "__init__",
"signature": "def __init__(self, step_time, saw_time, step_interval=None, n_step=None, ss=None)"
},
{... | 2 | stack_v2_sparse_classes_30k_train_001838 | Implement the Python class `SawRandStep` described below.
Class description:
Implement the SawRandStep class.
Method signatures and docstrings:
- def __init__(self, step_time, saw_time, step_interval=None, n_step=None, ss=None): Settings for a random step sequence Args: step_interval (list): Probability interval <a, ... | Implement the Python class `SawRandStep` described below.
Class description:
Implement the SawRandStep class.
Method signatures and docstrings:
- def __init__(self, step_time, saw_time, step_interval=None, n_step=None, ss=None): Settings for a random step sequence Args: step_interval (list): Probability interval <a, ... | cf548475295f25407ba968546c2fc85c26f9343c | <|skeleton|>
class SawRandStep:
def __init__(self, step_time, saw_time, step_interval=None, n_step=None, ss=None):
"""Settings for a random step sequence Args: step_interval (list): Probability interval <a, b> step_time: Time to perform step change n_step (int): Number of steps"""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SawRandStep:
def __init__(self, step_time, saw_time, step_interval=None, n_step=None, ss=None):
"""Settings for a random step sequence Args: step_interval (list): Probability interval <a, b> step_time: Time to perform step change n_step (int): Number of steps"""
self.ss = ss
self.n_ste... | the_stack_v2_python_sparse | SourceCode/simulation/signal.py | martin-bachorik/Master-Thesis-Project | train | 0 | |
457fa0ec1147db56e487366f757692e6eb6eb780 | [
"self.degree = degree\nself.include_bias = include_bias\nself.result = None",
"cols = X.size\nresList = []\nresList.clear()\nif self.include_bias == True:\n resList.append(1)\nfor j in range(1, self.degree + 1):\n for k in range(cols):\n resList.append(X[k] ** j)\nself.result = resList"
] | <|body_start_0|>
self.degree = degree
self.include_bias = include_bias
self.result = None
<|end_body_0|>
<|body_start_1|>
cols = X.size
resList = []
resList.clear()
if self.include_bias == True:
resList.append(1)
for j in range(1, self.degree ... | PolynomialFeatures | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolynomialFeatures:
def __init__(self, degree=2, include_bias=True):
"""Inputs: param degree : (int) max degree of polynomial features param include_bias : (boolean) specifies wheter to include bias term in returned feature array."""
<|body_0|>
def transform(self, X):
... | stack_v2_sparse_classes_36k_train_021035 | 1,617 | no_license | [
{
"docstring": "Inputs: param degree : (int) max degree of polynomial features param include_bias : (boolean) specifies wheter to include bias term in returned feature array.",
"name": "__init__",
"signature": "def __init__(self, degree=2, include_bias=True)"
},
{
"docstring": "Transform data to... | 2 | stack_v2_sparse_classes_30k_train_003323 | Implement the Python class `PolynomialFeatures` described below.
Class description:
Implement the PolynomialFeatures class.
Method signatures and docstrings:
- def __init__(self, degree=2, include_bias=True): Inputs: param degree : (int) max degree of polynomial features param include_bias : (boolean) specifies whete... | Implement the Python class `PolynomialFeatures` described below.
Class description:
Implement the PolynomialFeatures class.
Method signatures and docstrings:
- def __init__(self, degree=2, include_bias=True): Inputs: param degree : (int) max degree of polynomial features param include_bias : (boolean) specifies whete... | 18e4733e1bf7713502cce514e1cf7e587b35ca5c | <|skeleton|>
class PolynomialFeatures:
def __init__(self, degree=2, include_bias=True):
"""Inputs: param degree : (int) max degree of polynomial features param include_bias : (boolean) specifies wheter to include bias term in returned feature array."""
<|body_0|>
def transform(self, X):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PolynomialFeatures:
def __init__(self, degree=2, include_bias=True):
"""Inputs: param degree : (int) max degree of polynomial features param include_bias : (boolean) specifies wheter to include bias term in returned feature array."""
self.degree = degree
self.include_bias = include_bia... | the_stack_v2_python_sparse | assignment-3-jatinkumar762/preprocessing/polynomial_features.py | jatinkumar762/MachineLearning | train | 0 | |
4f7d40df40732475f956d652133c923cc6f580d5 | [
"self.request = kwargs.pop('request', None)\nself.instance_to_update = kwargs['instance'] if 'instance' in kwargs else None\nsuper(ProjectForm, self).__init__(*args, **kwargs)",
"title = self.cleaned_data.get('title')\nif self.request.user.projects.filter(title=title).exists():\n if not self.instance_to_update... | <|body_start_0|>
self.request = kwargs.pop('request', None)
self.instance_to_update = kwargs['instance'] if 'instance' in kwargs else None
super(ProjectForm, self).__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
title = self.cleaned_data.get('title')
if self.request.us... | A form responsible for creating a new Project-object | ProjectForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectForm:
"""A form responsible for creating a new Project-object"""
def __init__(self, *args, **kwargs):
"""Extend the objects argument by requiring the request object on initialization If we are updating we keep a copy of the instance in self. We do not use .pop there because el... | stack_v2_sparse_classes_36k_train_021036 | 8,614 | no_license | [
{
"docstring": "Extend the objects argument by requiring the request object on initialization If we are updating we keep a copy of the instance in self. We do not use .pop there because else we would lose the reference to the object being updated If we are not updating we are thus creating, so instance is None"... | 3 | stack_v2_sparse_classes_30k_train_001943 | Implement the Python class `ProjectForm` described below.
Class description:
A form responsible for creating a new Project-object
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Extend the objects argument by requiring the request object on initialization If we are updating we keep a copy of ... | Implement the Python class `ProjectForm` described below.
Class description:
A form responsible for creating a new Project-object
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Extend the objects argument by requiring the request object on initialization If we are updating we keep a copy of ... | a159cd5b705d461aa29866978e0ea2b64f81fc68 | <|skeleton|>
class ProjectForm:
"""A form responsible for creating a new Project-object"""
def __init__(self, *args, **kwargs):
"""Extend the objects argument by requiring the request object on initialization If we are updating we keep a copy of the instance in self. We do not use .pop there because el... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectForm:
"""A form responsible for creating a new Project-object"""
def __init__(self, *args, **kwargs):
"""Extend the objects argument by requiring the request object on initialization If we are updating we keep a copy of the instance in self. We do not use .pop there because else we would l... | the_stack_v2_python_sparse | uiApp/Anlzer_Project/anlzer/forms.py | epu-ntua/Anlzer | train | 1 |
22721e71a056c1825819d54e87f45495239d562b | [
"if not exactly_one(destination_table_name, destination_sql, destination_table_definition):\n raise ETLInputError('One of dest table name/schema or dest sql needed')\nif not exactly_one(source_sql, source_table_name, source_count_sql):\n raise ETLInputError('One of source table name or source sql ' + 'or sour... | <|body_start_0|>
if not exactly_one(destination_table_name, destination_sql, destination_table_definition):
raise ETLInputError('One of dest table name/schema or dest sql needed')
if not exactly_one(source_sql, source_table_name, source_count_sql):
raise ETLInputError('One of sou... | CountCheckStep class that compares the number of rows in the source select script with the number of rows in the destination table | CountCheckStep | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CountCheckStep:
"""CountCheckStep class that compares the number of rows in the source select script with the number of rows in the destination table"""
def __init__(self, id, source_host, source_sql=None, source_table_name=None, destination_table_name=None, destination_table_definition=None... | stack_v2_sparse_classes_36k_train_021037 | 4,123 | permissive | [
{
"docstring": "Constructor for the CountCheckStep class Args: source_sql(str): SQL select script from the source table destination_table_name(str): table name for the destination table **kwargs(optional): Keyword arguments directly passed to base class",
"name": "__init__",
"signature": "def __init__(s... | 3 | stack_v2_sparse_classes_30k_train_012288 | Implement the Python class `CountCheckStep` described below.
Class description:
CountCheckStep class that compares the number of rows in the source select script with the number of rows in the destination table
Method signatures and docstrings:
- def __init__(self, id, source_host, source_sql=None, source_table_name=... | Implement the Python class `CountCheckStep` described below.
Class description:
CountCheckStep class that compares the number of rows in the source select script with the number of rows in the destination table
Method signatures and docstrings:
- def __init__(self, id, source_host, source_sql=None, source_table_name=... | 797cb719e6c2abeda0751ada3339c72bfb19c8f2 | <|skeleton|>
class CountCheckStep:
"""CountCheckStep class that compares the number of rows in the source select script with the number of rows in the destination table"""
def __init__(self, id, source_host, source_sql=None, source_table_name=None, destination_table_name=None, destination_table_definition=None... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CountCheckStep:
"""CountCheckStep class that compares the number of rows in the source select script with the number of rows in the destination table"""
def __init__(self, id, source_host, source_sql=None, source_table_name=None, destination_table_name=None, destination_table_definition=None, destination... | the_stack_v2_python_sparse | dataduct/steps/count_check.py | EverFi/dataduct | train | 3 |
1d100a9a04e53c02a8eae3c4fc2f9a5309ab5c44 | [
"if s == '':\n return s\nans = ''\nfor i in range(len(s)):\n res1 = self.Expand(s, i, i)\n res2 = self.Expand(s, i, i + 1)\n temp = res1 if len(res1) > len(res2) else res2\n ans = temp if len(temp) > len(ans) else ans\nreturn ans",
"while p >= 0 and q < len(s):\n if s[p] == s[q]:\n p -= 1... | <|body_start_0|>
if s == '':
return s
ans = ''
for i in range(len(s)):
res1 = self.Expand(s, i, i)
res2 = self.Expand(s, i, i + 1)
temp = res1 if len(res1) > len(res2) else res2
ans = temp if len(temp) > len(ans) else ans
return... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def Expand(self, s, p, q):
"""s中p,g为起点,比较是否相同"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if s == '':
return s
ans = ''
for i in rang... | stack_v2_sparse_classes_36k_train_021038 | 5,236 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": "s中p,g为起点,比较是否相同",
"name": "Expand",
"signature": "def Expand(self, s, p, q)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019205 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def Expand(self, s, p, q): s中p,g为起点,比较是否相同 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def Expand(self, s, p, q): s中p,g为起点,比较是否相同
<|skeleton|>
class Solution:
def longestPalindrome(self, s):
"... | 6046d535ebd139d1348e0f2eafdb4135b4e3f52e | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def Expand(self, s, p, q):
"""s中p,g为起点,比较是否相同"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
if s == '':
return s
ans = ''
for i in range(len(s)):
res1 = self.Expand(s, i, i)
res2 = self.Expand(s, i, i + 1)
temp = res1 if len(res1) > len(res2) else r... | the_stack_v2_python_sparse | 005. Longest Palindromic Substring/solution.py | Neilqdddd/LeetCode | train | 1 | |
3833d58b1810ee5c18c50d0f5b777b05562feb7b | [
"self.cgd_vars = cgd_vars\ntry:\n self.cnx = mysql.connector.connect(user=creds[0], password=creds[1], host=creds[2], port=creds[3], database=creds[4])\n print('Connection successful')\nexcept mysql.connector.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n print('Something is wro... | <|body_start_0|>
self.cgd_vars = cgd_vars
try:
self.cnx = mysql.connector.connect(user=creds[0], password=creds[1], host=creds[2], port=creds[3], database=creds[4])
print('Connection successful')
except mysql.connector.Error as err:
if err.errno == errorcode.E... | NEEDS: dictionary {(chrom, pos, ref, alt): [HGMD pmid's]} CREATE: Updated version of input. {(chrom, pos, ref, alt): True or False whether new and old match} | MysqlRetrieve | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MysqlRetrieve:
"""NEEDS: dictionary {(chrom, pos, ref, alt): [HGMD pmid's]} CREATE: Updated version of input. {(chrom, pos, ref, alt): True or False whether new and old match}"""
def __init__(self, cgd_vars, creds):
"""Need from allmut and extrarefs tables."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_021039 | 6,229 | no_license | [
{
"docstring": "Need from allmut and extrarefs tables.",
"name": "__init__",
"signature": "def __init__(self, cgd_vars, creds)"
},
{
"docstring": "Get the new list of HGMD references. :return:",
"name": "_new_refs",
"signature": "def _new_refs(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019880 | Implement the Python class `MysqlRetrieve` described below.
Class description:
NEEDS: dictionary {(chrom, pos, ref, alt): [HGMD pmid's]} CREATE: Updated version of input. {(chrom, pos, ref, alt): True or False whether new and old match}
Method signatures and docstrings:
- def __init__(self, cgd_vars, creds): Need fro... | Implement the Python class `MysqlRetrieve` described below.
Class description:
NEEDS: dictionary {(chrom, pos, ref, alt): [HGMD pmid's]} CREATE: Updated version of input. {(chrom, pos, ref, alt): True or False whether new and old match}
Method signatures and docstrings:
- def __init__(self, cgd_vars, creds): Need fro... | 6162bc6d8ee37401de8dffec545935953028bed7 | <|skeleton|>
class MysqlRetrieve:
"""NEEDS: dictionary {(chrom, pos, ref, alt): [HGMD pmid's]} CREATE: Updated version of input. {(chrom, pos, ref, alt): True or False whether new and old match}"""
def __init__(self, cgd_vars, creds):
"""Need from allmut and extrarefs tables."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MysqlRetrieve:
"""NEEDS: dictionary {(chrom, pos, ref, alt): [HGMD pmid's]} CREATE: Updated version of input. {(chrom, pos, ref, alt): True or False whether new and old match}"""
def __init__(self, cgd_vars, creds):
"""Need from allmut and extrarefs tables."""
self.cgd_vars = cgd_vars
... | the_stack_v2_python_sparse | hgmd_ann/hgmd_ref_pull.py | ohsu-comp-bio/compbio-galaxy-wrappers | train | 6 |
14a658ae020a4c1e47488f09b298aa2c8097f9a8 | [
"self.establish_connection(vsphere)\ncluster = inventory.get_cluster(self.si_content, name=cluster_name)\naffinity_rule = self.find_affinity_rule(rule_name, cluster)\nvm_group, host_group = self.find_affinity_groups(cluster, affinity_rule.vmGroupName, affinity_rule.affineHostGroupName)\nconfig_spec = self.build_clu... | <|body_start_0|>
self.establish_connection(vsphere)
cluster = inventory.get_cluster(self.si_content, name=cluster_name)
affinity_rule = self.find_affinity_rule(rule_name, cluster)
vm_group, host_group = self.find_affinity_groups(cluster, affinity_rule.vmGroupName, affinity_rule.affineHos... | AffinityRuleDelete | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AffinityRuleDelete:
def run(self, rule_name, cluster_name, vsphere=None):
"""Main entry point for the StackStorm actions to execute the operation. :returns: boolean"""
<|body_0|>
def find_affinity_groups(self, cluster, vm_group_name, host_group_name):
"""Finds the ho... | stack_v2_sparse_classes_36k_train_021040 | 4,595 | permissive | [
{
"docstring": "Main entry point for the StackStorm actions to execute the operation. :returns: boolean",
"name": "run",
"signature": "def run(self, rule_name, cluster_name, vsphere=None)"
},
{
"docstring": "Finds the host and vm groups that would be associated with the affinity rule that we are... | 4 | stack_v2_sparse_classes_30k_train_009179 | Implement the Python class `AffinityRuleDelete` described below.
Class description:
Implement the AffinityRuleDelete class.
Method signatures and docstrings:
- def run(self, rule_name, cluster_name, vsphere=None): Main entry point for the StackStorm actions to execute the operation. :returns: boolean
- def find_affin... | Implement the Python class `AffinityRuleDelete` described below.
Class description:
Implement the AffinityRuleDelete class.
Method signatures and docstrings:
- def run(self, rule_name, cluster_name, vsphere=None): Main entry point for the StackStorm actions to execute the operation. :returns: boolean
- def find_affin... | 5977631a199f8853c5208d9acd5e403a7ea3ba53 | <|skeleton|>
class AffinityRuleDelete:
def run(self, rule_name, cluster_name, vsphere=None):
"""Main entry point for the StackStorm actions to execute the operation. :returns: boolean"""
<|body_0|>
def find_affinity_groups(self, cluster, vm_group_name, host_group_name):
"""Finds the ho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AffinityRuleDelete:
def run(self, rule_name, cluster_name, vsphere=None):
"""Main entry point for the StackStorm actions to execute the operation. :returns: boolean"""
self.establish_connection(vsphere)
cluster = inventory.get_cluster(self.si_content, name=cluster_name)
affinit... | the_stack_v2_python_sparse | actions/affinity_rule_delete.py | StackStorm-Exchange/stackstorm-vsphere | train | 11 | |
82a930f739e72f6da303b4cfa3f015d7718d3ce3 | [
"assert features.is_contiguous()\nassert indices.is_contiguous()\nassert weight.is_contiguous()\nB, c, m = features.size()\nn = indices.size(1)\nctx.three_interpolate_for_backward = (indices, weight, m)\noutput = features.new_empty(B, c, n)\next_module.three_interpolate_forward(features, indices, weight, output, b=... | <|body_start_0|>
assert features.is_contiguous()
assert indices.is_contiguous()
assert weight.is_contiguous()
B, c, m = features.size()
n = indices.size(1)
ctx.three_interpolate_for_backward = (indices, weight, m)
output = features.new_empty(B, c, n)
ext_m... | Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details. | ThreeInterpolate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreeInterpolate:
"""Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details."""
def forward(ctx: Any, features: torch.Tensor, indices: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
"""Arg... | stack_v2_sparse_classes_36k_train_021041 | 2,240 | permissive | [
{
"docstring": "Args: features (torch.Tensor): (B, C, M) Features descriptors to be interpolated. indices (torch.Tensor): (B, n, 3) indices of three nearest neighbor features for the target features. weight (torch.Tensor): (B, n, 3) weights of three nearest neighbor features for the target features. Returns: to... | 2 | stack_v2_sparse_classes_30k_train_008186 | Implement the Python class `ThreeInterpolate` described below.
Class description:
Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details.
Method signatures and docstrings:
- def forward(ctx: Any, features: torch.Tensor, indices:... | Implement the Python class `ThreeInterpolate` described below.
Class description:
Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details.
Method signatures and docstrings:
- def forward(ctx: Any, features: torch.Tensor, indices:... | 6e9ee26718b22961d5c34caca4108413b1b7b3af | <|skeleton|>
class ThreeInterpolate:
"""Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details."""
def forward(ctx: Any, features: torch.Tensor, indices: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
"""Arg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreeInterpolate:
"""Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details."""
def forward(ctx: Any, features: torch.Tensor, indices: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
"""Args: features (... | the_stack_v2_python_sparse | mmcv/ops/three_interpolate.py | open-mmlab/mmcv | train | 5,319 |
a1df7f85bd6b13c6860062c23fe64cdd97324d79 | [
"matrix = [row for row in matrix if row]\ncol_one = [row[0] for row in matrix]\nprint(col_one)\nrow_x = self.binSearch(col_one, target, 0, len(col_one) - 1)\nprint('row_x', row_x)\nif row_x is None:\n return False\nfor i in range(1 + row_x):\n m = self.binSearch(matrix[i], target, 0, len(matrix[i]) - 1)\n ... | <|body_start_0|>
matrix = [row for row in matrix if row]
col_one = [row[0] for row in matrix]
print(col_one)
row_x = self.binSearch(col_one, target, 0, len(col_one) - 1)
print('row_x', row_x)
if row_x is None:
return False
for i in range(1 + row_x):
... | Solution | [] | 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 binSearch(self, nums, target, s, e):
"""返回 <= target 的 index"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
matrix =... | stack_v2_sparse_classes_36k_train_021042 | 2,349 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": "返回 <= target 的 index",
"name": "binSearch",
"signature": "def binSearch(self, nums, target, s, e)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015959 | 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 binSearch(self, nums, target, s, e): 返回 <= target 的 index | 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 binSearch(self, nums, target, s, e): 返回 <= target 的 index
<|skeleton|>... | d2e8b2dca40fc955045eb62e576c776bad8ee5f1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def binSearch(self, nums, target, s, e):
"""返回 <= target 的 index"""
<|body_1|>
<|end_skeleton|> | 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"""
matrix = [row for row in matrix if row]
col_one = [row[0] for row in matrix]
print(col_one)
row_x = self.binSearch(col_one, target, 0, len(col_one) - 1)
... | the_stack_v2_python_sparse | search-a-2d-matrix/solution.py | childe/leetcode | train | 2 | |
dff14366abd8fb6fa0ae5f1baa8d0095699fb548 | [
"value_json = {'type': 'struct', 'ctype': str(self.value.type), 'address': self.address, 'fields': []}\nfor field in self.value.type.fields():\n if not field.is_base_class:\n field_json = {'field': field.name, 'value': None}\n field_printer = general_lookup_function(self.value[field.name], self.vis... | <|body_start_0|>
value_json = {'type': 'struct', 'ctype': str(self.value.type), 'address': self.address, 'fields': []}
for field in self.value.type.fields():
if not field.is_base_class:
field_json = {'field': field.name, 'value': None}
field_printer = general_... | A Printer for objects in C++. The current version won't extract the dynamic/actual type of objects, and the member variable of a parent/child class won't be printed. We expect to support this function later. | ObjectPrinter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectPrinter:
"""A Printer for objects in C++. The current version won't extract the dynamic/actual type of objects, and the member variable of a parent/child class won't be printed. We expect to support this function later."""
def to_json_without_expanding_base_class(self):
"""A he... | stack_v2_sparse_classes_36k_train_021043 | 14,814 | no_license | [
{
"docstring": "A helper function for the to_json method. It tries to extract all member variables of an object without casting it into base classes.",
"name": "to_json_without_expanding_base_class",
"signature": "def to_json_without_expanding_base_class(self)"
},
{
"docstring": "Output format: ... | 2 | stack_v2_sparse_classes_30k_train_021536 | Implement the Python class `ObjectPrinter` described below.
Class description:
A Printer for objects in C++. The current version won't extract the dynamic/actual type of objects, and the member variable of a parent/child class won't be printed. We expect to support this function later.
Method signatures and docstring... | Implement the Python class `ObjectPrinter` described below.
Class description:
A Printer for objects in C++. The current version won't extract the dynamic/actual type of objects, and the member variable of a parent/child class won't be printed. We expect to support this function later.
Method signatures and docstring... | 78a61ca023cbf1a0cecfef8b97df2b274ac3a988 | <|skeleton|>
class ObjectPrinter:
"""A Printer for objects in C++. The current version won't extract the dynamic/actual type of objects, and the member variable of a parent/child class won't be printed. We expect to support this function later."""
def to_json_without_expanding_base_class(self):
"""A he... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectPrinter:
"""A Printer for objects in C++. The current version won't extract the dynamic/actual type of objects, and the member variable of a parent/child class won't be printed. We expect to support this function later."""
def to_json_without_expanding_base_class(self):
"""A helper function... | the_stack_v2_python_sparse | tools/security/gdb/gdb_json_printer/gdb_json_printer/printers.py | ZYHGOD-1/Aosp11 | train | 0 |
32c1571a62386f6d4fb490056be5dc4bfd9763d7 | [
"super(MXNetGraphConverter, self).__init__(framework, base_path)\nprint('{} bmodel converter init'.format(model_name))\nself.model_name = model_name\nself.models_path = models_path\nself.weights_path = weights_path\nself.shapes = shapes\nself.dyns = dyns\nself.outdirs = outdirs\nself.nets_name = nets_name\nself.inp... | <|body_start_0|>
super(MXNetGraphConverter, self).__init__(framework, base_path)
print('{} bmodel converter init'.format(model_name))
self.model_name = model_name
self.models_path = models_path
self.weights_path = weights_path
self.shapes = shapes
self.dyns = dyns... | mxnet graph bmodel converter | MXNetGraphConverter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MXNetGraphConverter:
"""mxnet graph bmodel converter"""
def __init__(self, model_name, base_path, models_path, weights_path, shapes, dyns, outdirs, nets_name, input_names, framework, target):
"""Init mxnet graph bmodel converter"""
<|body_0|>
def converter(self):
... | stack_v2_sparse_classes_36k_train_021044 | 15,723 | permissive | [
{
"docstring": "Init mxnet graph bmodel converter",
"name": "__init__",
"signature": "def __init__(self, model_name, base_path, models_path, weights_path, shapes, dyns, outdirs, nets_name, input_names, framework, target)"
},
{
"docstring": "convert mxnet graph",
"name": "converter",
"sig... | 2 | stack_v2_sparse_classes_30k_train_001507 | Implement the Python class `MXNetGraphConverter` described below.
Class description:
mxnet graph bmodel converter
Method signatures and docstrings:
- def __init__(self, model_name, base_path, models_path, weights_path, shapes, dyns, outdirs, nets_name, input_names, framework, target): Init mxnet graph bmodel converte... | Implement the Python class `MXNetGraphConverter` described below.
Class description:
mxnet graph bmodel converter
Method signatures and docstrings:
- def __init__(self, model_name, base_path, models_path, weights_path, shapes, dyns, outdirs, nets_name, input_names, framework, target): Init mxnet graph bmodel converte... | c9fa07851da663dda4953dba72e1d3937299a4ea | <|skeleton|>
class MXNetGraphConverter:
"""mxnet graph bmodel converter"""
def __init__(self, model_name, base_path, models_path, weights_path, shapes, dyns, outdirs, nets_name, input_names, framework, target):
"""Init mxnet graph bmodel converter"""
<|body_0|>
def converter(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MXNetGraphConverter:
"""mxnet graph bmodel converter"""
def __init__(self, model_name, base_path, models_path, weights_path, shapes, dyns, outdirs, nets_name, input_names, framework, target):
"""Init mxnet graph bmodel converter"""
super(MXNetGraphConverter, self).__init__(framework, base... | the_stack_v2_python_sparse | modules/utils/bmodel_converter.py | sophon-ai-algo/sophon-inference | train | 32 |
07130a06525400e73a0131484358abd566402aca | [
"if work_load > 100:\n print('Workload: %d' % work_load)\n raise OverflowError('Workloads over 100 are not allowed')\nself.name = name\nself.work_load = work_load\nself.work_step = 0.5\nself.finished = False",
"self.work_load -= self.work_step\nif self.work_load <= 0:\n self.finished = True\nreturn self.... | <|body_start_0|>
if work_load > 100:
print('Workload: %d' % work_load)
raise OverflowError('Workloads over 100 are not allowed')
self.name = name
self.work_load = work_load
self.work_step = 0.5
self.finished = False
<|end_body_0|>
<|body_start_1|>
... | Tasks are received from the problem owner. A task has a name and a workload. The workload is the time in hours required to complete the task. Examples for typical workloads are: very low 10 low 30 medium 50 high 70 very high 90 extremly high 100 Workloads over 100 are rejected because programmers are smart people. | Task | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Task:
"""Tasks are received from the problem owner. A task has a name and a workload. The workload is the time in hours required to complete the task. Examples for typical workloads are: very low 10 low 30 medium 50 high 70 very high 90 extremly high 100 Workloads over 100 are rejected because pr... | stack_v2_sparse_classes_36k_train_021045 | 6,236 | no_license | [
{
"docstring": "Make a new task. Only tasks with a work load <= 100 are allowed.",
"name": "__init__",
"signature": "def __init__(self, name, work_load)"
},
{
"docstring": "Solve a task We just substract the work step. The skill level of the programmer is NOT considered.",
"name": "solve",
... | 2 | stack_v2_sparse_classes_30k_val_001027 | Implement the Python class `Task` described below.
Class description:
Tasks are received from the problem owner. A task has a name and a workload. The workload is the time in hours required to complete the task. Examples for typical workloads are: very low 10 low 30 medium 50 high 70 very high 90 extremly high 100 Wor... | Implement the Python class `Task` described below.
Class description:
Tasks are received from the problem owner. A task has a name and a workload. The workload is the time in hours required to complete the task. Examples for typical workloads are: very low 10 low 30 medium 50 high 70 very high 90 extremly high 100 Wor... | 0d1fac72150e9e7015b20124b6bb7cd57b821416 | <|skeleton|>
class Task:
"""Tasks are received from the problem owner. A task has a name and a workload. The workload is the time in hours required to complete the task. Examples for typical workloads are: very low 10 low 30 medium 50 high 70 very high 90 extremly high 100 Workloads over 100 are rejected because pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Task:
"""Tasks are received from the problem owner. A task has a name and a workload. The workload is the time in hours required to complete the task. Examples for typical workloads are: very low 10 low 30 medium 50 high 70 very high 90 extremly high 100 Workloads over 100 are rejected because programmers are... | the_stack_v2_python_sparse | programmersworld/programmers.py | qspin/python-course | train | 1 |
c69ea0d6d5329da813980e6b998a63602aac5867 | [
"url = f'{self.session.root_url}/summary/api/visual/?assessment_id={assessment_id}'\nresponse_json = self.session.get(url).json()\nreturn pd.DataFrame(response_json)",
"url = f'{self.session.root_url}/summary/api/data_pivot/?assessment_id={assessment_id}'\nresponse_json = self.session.get(url).json()\nreturn pd.D... | <|body_start_0|>
url = f'{self.session.root_url}/summary/api/visual/?assessment_id={assessment_id}'
response_json = self.session.get(url).json()
return pd.DataFrame(response_json)
<|end_body_0|>
<|body_start_1|>
url = f'{self.session.root_url}/summary/api/data_pivot/?assessment_id={asse... | Client class for summary requests. | SummaryClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SummaryClient:
"""Client class for summary requests."""
def visual_list(self, assessment_id: int) -> pd.DataFrame:
"""Retrieves a visual list for the given assessment. Args: assessment_id (int): Assessment ID Returns: pd.DataFrame: Visual list"""
<|body_0|>
def datapivot... | stack_v2_sparse_classes_36k_train_021046 | 1,519 | permissive | [
{
"docstring": "Retrieves a visual list for the given assessment. Args: assessment_id (int): Assessment ID Returns: pd.DataFrame: Visual list",
"name": "visual_list",
"signature": "def visual_list(self, assessment_id: int) -> pd.DataFrame"
},
{
"docstring": "Retrieves a data pivot list for the g... | 3 | null | Implement the Python class `SummaryClient` described below.
Class description:
Client class for summary requests.
Method signatures and docstrings:
- def visual_list(self, assessment_id: int) -> pd.DataFrame: Retrieves a visual list for the given assessment. Args: assessment_id (int): Assessment ID Returns: pd.DataFr... | Implement the Python class `SummaryClient` described below.
Class description:
Client class for summary requests.
Method signatures and docstrings:
- def visual_list(self, assessment_id: int) -> pd.DataFrame: Retrieves a visual list for the given assessment. Args: assessment_id (int): Assessment ID Returns: pd.DataFr... | 51177c6fb9354cd028f7099fc10d83b1051fd50d | <|skeleton|>
class SummaryClient:
"""Client class for summary requests."""
def visual_list(self, assessment_id: int) -> pd.DataFrame:
"""Retrieves a visual list for the given assessment. Args: assessment_id (int): Assessment ID Returns: pd.DataFrame: Visual list"""
<|body_0|>
def datapivot... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SummaryClient:
"""Client class for summary requests."""
def visual_list(self, assessment_id: int) -> pd.DataFrame:
"""Retrieves a visual list for the given assessment. Args: assessment_id (int): Assessment ID Returns: pd.DataFrame: Visual list"""
url = f'{self.session.root_url}/summary/ap... | the_stack_v2_python_sparse | client/hawc_client/summary.py | shapiromatron/hawc | train | 25 |
503c72178d8d2931ae0e3700e7ee3a0b5478a821 | [
"result = {'result': 'NG', 'content': []}\ndata = request.get_json(force=True)\nif data:\n res, msg = CtrlQuotations().update_one_quotation_info(quotation_id, data)\n if res:\n result['result'] = 'OK'\n result['content'] = msg\n else:\n result['content'] = msg\nreturn result",
"resul... | <|body_start_0|>
result = {'result': 'NG', 'content': []}
data = request.get_json(force=True)
if data:
res, msg = CtrlQuotations().update_one_quotation_info(quotation_id, data)
if res:
result['result'] = 'OK'
result['content'] = msg
... | ApiQuotations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiQuotations:
def put(self, quotation_id):
"""修改报价 :return:"""
<|body_0|>
def get(self, quotation_id):
"""查看报价 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = {'result': 'NG', 'content': []}
data = request.get_json(force=T... | stack_v2_sparse_classes_36k_train_021047 | 10,406 | no_license | [
{
"docstring": "修改报价 :return:",
"name": "put",
"signature": "def put(self, quotation_id)"
},
{
"docstring": "查看报价 :return:",
"name": "get",
"signature": "def get(self, quotation_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015718 | Implement the Python class `ApiQuotations` described below.
Class description:
Implement the ApiQuotations class.
Method signatures and docstrings:
- def put(self, quotation_id): 修改报价 :return:
- def get(self, quotation_id): 查看报价 :return: | Implement the Python class `ApiQuotations` described below.
Class description:
Implement the ApiQuotations class.
Method signatures and docstrings:
- def put(self, quotation_id): 修改报价 :return:
- def get(self, quotation_id): 查看报价 :return:
<|skeleton|>
class ApiQuotations:
def put(self, quotation_id):
"""... | 64b31e7bdfcb8a4c95f0a8a607f0bcff576cec11 | <|skeleton|>
class ApiQuotations:
def put(self, quotation_id):
"""修改报价 :return:"""
<|body_0|>
def get(self, quotation_id):
"""查看报价 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApiQuotations:
def put(self, quotation_id):
"""修改报价 :return:"""
result = {'result': 'NG', 'content': []}
data = request.get_json(force=True)
if data:
res, msg = CtrlQuotations().update_one_quotation_info(quotation_id, data)
if res:
result... | the_stack_v2_python_sparse | koala/koala_server/app/api_1_0/api_quotations.py | lsn1183/web_project | train | 0 | |
495ab6017d9190fdc4e604d4ee1cfa16f7bf5d67 | [
"if not username:\n raise ValueError('Users must have an username.')\nuser = self.model(username=username)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(username=username, password=password)\nuser.is_admin = True\nuser.save(using=self._db)\nreturn user"
] | <|body_start_0|>
if not username:
raise ValueError('Users must have an username.')
user = self.model(username=username)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.create_user(username=username... | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, username, password=None):
"""Creates and saves a User with the given username and password."""
<|body_0|>
def create_superuser(self, username, password):
"""Creates and saves a superuser with the given username and password."""
... | stack_v2_sparse_classes_36k_train_021048 | 5,720 | no_license | [
{
"docstring": "Creates and saves a User with the given username and password.",
"name": "create_user",
"signature": "def create_user(self, username, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given username and password.",
"name": "create_superuser",
"sign... | 2 | stack_v2_sparse_classes_30k_train_010665 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, username, password=None): Creates and saves a User with the given username and password.
- def create_superuser(self, username, password): Creates... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, username, password=None): Creates and saves a User with the given username and password.
- def create_superuser(self, username, password): Creates... | a92f30a77ad3ba9f97e916d2c0a355641c9397ba | <|skeleton|>
class MyUserManager:
def create_user(self, username, password=None):
"""Creates and saves a User with the given username and password."""
<|body_0|>
def create_superuser(self, username, password):
"""Creates and saves a superuser with the given username and password."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyUserManager:
def create_user(self, username, password=None):
"""Creates and saves a User with the given username and password."""
if not username:
raise ValueError('Users must have an username.')
user = self.model(username=username)
user.set_password(password)
... | the_stack_v2_python_sparse | app/models.py | nlattessi/inspt_tp_final_cpe | train | 0 | |
50c2974d7e18fdb0f8b7c577f03c79e9bcf642ad | [
"inferred_data = json.loads(self.request.body)\nraw_data = model.RRCInferenceRawData()\nraw_data.phone_id = util.HashDeviceId(str(inferred_data['phone_id']))\nraw_data.test_id = inferred_data['test_id']\nraw_data.network_type = inferred_data['network_type']\nraw_data.rtt_low = inferred_data['rtt_low']\nraw_data.rtt... | <|body_start_0|>
inferred_data = json.loads(self.request.body)
raw_data = model.RRCInferenceRawData()
raw_data.phone_id = util.HashDeviceId(str(inferred_data['phone_id']))
raw_data.test_id = inferred_data['test_id']
raw_data.network_type = inferred_data['network_type']
ra... | Interact with RRC-related data stored in the database | RRCStates | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RRCStates:
"""Interact with RRC-related data stored in the database"""
def uploadRRCInference(self, **unused_args):
"""Handler for uploadRRCInference request generated from client. Take the results of the RRC inference tasks and store them in the database. Note that this is the resul... | stack_v2_sparse_classes_36k_train_021049 | 4,420 | permissive | [
{
"docstring": "Handler for uploadRRCInference request generated from client. Take the results of the RRC inference tasks and store them in the database. Note that this is the result of *one* test, i.e. one sequence of three packets sent. A set of tests with varying inter-packet intervals can be identified by a... | 2 | stack_v2_sparse_classes_30k_train_005256 | Implement the Python class `RRCStates` described below.
Class description:
Interact with RRC-related data stored in the database
Method signatures and docstrings:
- def uploadRRCInference(self, **unused_args): Handler for uploadRRCInference request generated from client. Take the results of the RRC inference tasks an... | Implement the Python class `RRCStates` described below.
Class description:
Interact with RRC-related data stored in the database
Method signatures and docstrings:
- def uploadRRCInference(self, **unused_args): Handler for uploadRRCInference request generated from client. Take the results of the RRC inference tasks an... | 9277f9e0623eafe9a2f2cd387f3a2f0dfa9b94ba | <|skeleton|>
class RRCStates:
"""Interact with RRC-related data stored in the database"""
def uploadRRCInference(self, **unused_args):
"""Handler for uploadRRCInference request generated from client. Take the results of the RRC inference tasks and store them in the database. Note that this is the resul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RRCStates:
"""Interact with RRC-related data stored in the database"""
def uploadRRCInference(self, **unused_args):
"""Handler for uploadRRCInference request generated from client. Take the results of the RRC inference tasks and store them in the database. Note that this is the result of *one* te... | the_stack_v2_python_sparse | server/gspeedometer/controllers/RRCstates.py | Bugbustrs/bugb-mobiperf | train | 0 |
0c7ddf816c80eb43b1a2120ec0a275d2209629f3 | [
"self.capacity = capacity\nself.cache = deque()\nself.value = dict()",
"try:\n self.cache.remove(key)\nexcept ValueError:\n return -1\nself.cache.append(key)\nreturn self.value[key]",
"try:\n self.cache.remove(key)\nexcept ValueError:\n if len(self.cache) == self.capacity:\n self.cache.poplef... | <|body_start_0|>
self.capacity = capacity
self.cache = deque()
self.value = dict()
<|end_body_0|>
<|body_start_1|>
try:
self.cache.remove(key)
except ValueError:
return -1
self.cache.append(key)
return self.value[key]
<|end_body_1|>
<|bod... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_021050 | 965 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 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): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | 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): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | c59ebd4ccfa1a6aa4315581dd70055f423d46de1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.cache = deque()
self.value = dict()
def get(self, key):
""":rtype: int"""
try:
self.cache.remove(key)
except ValueError:
return -... | the_stack_v2_python_sparse | algorithms/LRU_cache.py | dsdshcym/LeetCode-Solutions | train | 1 | |
1f4780688b393b4658f4e0f3523ba672931c1a8a | [
"self.model = model\nself.data = data\nself.checkpoint_dir = checkpoint_dir\nif log_dir:\n self._summary_writer = summary_ops_v2.create_file_writer_v2(logdir=log_dir)\nelse:\n self._summary_writer = None\nself._iterations = variables.Variable(name='iterations', initial_value=_ITERATIONS_UNINITIALIZED, dtype=d... | <|body_start_0|>
self.model = model
self.data = data
self.checkpoint_dir = checkpoint_dir
if log_dir:
self._summary_writer = summary_ops_v2.create_file_writer_v2(logdir=log_dir)
else:
self._summary_writer = None
self._iterations = variables.Variabl... | A class designed for a dedicated evaluator task. `SidecarEvaluator` is expected to be run on a process in a separate machine from the training cluster. It continuously loads checkpoints saved periodically by that training counterpart, and performs evaluation using the model (with compiled metrics) provided at `__init__... | SidecarEvaluator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SidecarEvaluator:
"""A class designed for a dedicated evaluator task. `SidecarEvaluator` is expected to be run on a process in a separate machine from the training cluster. It continuously loads checkpoints saved periodically by that training counterpart, and performs evaluation using the model (... | stack_v2_sparse_classes_36k_train_021051 | 8,189 | permissive | [
{
"docstring": "Initializes an `SidecarEvaluator` object. Args: model: Model to use for evaluation. The model object used here should be a `tf.keras.Model`, and should be the same as the one that is used in training, where `tf.keras.Model`s are checkpointed. The model should have one or more metrics compiled be... | 2 | null | Implement the Python class `SidecarEvaluator` described below.
Class description:
A class designed for a dedicated evaluator task. `SidecarEvaluator` is expected to be run on a process in a separate machine from the training cluster. It continuously loads checkpoints saved periodically by that training counterpart, an... | Implement the Python class `SidecarEvaluator` described below.
Class description:
A class designed for a dedicated evaluator task. `SidecarEvaluator` is expected to be run on a process in a separate machine from the training cluster. It continuously loads checkpoints saved periodically by that training counterpart, an... | 1b6f13331f4d8e7fccc66bfeb0b066e77a2b7206 | <|skeleton|>
class SidecarEvaluator:
"""A class designed for a dedicated evaluator task. `SidecarEvaluator` is expected to be run on a process in a separate machine from the training cluster. It continuously loads checkpoints saved periodically by that training counterpart, and performs evaluation using the model (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SidecarEvaluator:
"""A class designed for a dedicated evaluator task. `SidecarEvaluator` is expected to be run on a process in a separate machine from the training cluster. It continuously loads checkpoints saved periodically by that training counterpart, and performs evaluation using the model (with compiled... | the_stack_v2_python_sparse | tensorflow/python/keras/distribute/sidecar_evaluator.py | galeone/tensorflow | train | 21 |
7bf94723357d75790a5614d990d0a1c7e3b1b865 | [
"kwargs['default'] = default\nkwargs['types'] = (Gradient, Palette, str, tuple, list)\nsuper().__init__(**kwargs)",
"if isinstance(value, Gradient):\n return value\nvalue = super().parse(value)\nif value is UNDEF or value is None:\n return value\nif callable(value):\n return value\nreturn Gradient.create... | <|body_start_0|>
kwargs['default'] = default
kwargs['types'] = (Gradient, Palette, str, tuple, list)
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
if isinstance(value, Gradient):
return value
value = super().parse(value)
if value is UNDEF or valu... | Defines a color gradient property, which simplifies a gradient definition by automatically creating a pero.Gradient instance from various input options such as a list of supported pero.Color definitions, pero.Palette or registered palette or gradient name. | GradientProperty | [
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientProperty:
"""Defines a color gradient property, which simplifies a gradient definition by automatically creating a pero.Gradient instance from various input options such as a list of supported pero.Color definitions, pero.Palette or registered palette or gradient name."""
def __init_... | stack_v2_sparse_classes_36k_train_021052 | 4,576 | permissive | [
{
"docstring": "Initializes a new instance of GradientProperty.",
"name": "__init__",
"signature": "def __init__(self, default=UNDEF, **kwargs)"
},
{
"docstring": "Validates and converts given value.",
"name": "parse",
"signature": "def parse(self, value)"
}
] | 2 | null | Implement the Python class `GradientProperty` described below.
Class description:
Defines a color gradient property, which simplifies a gradient definition by automatically creating a pero.Gradient instance from various input options such as a list of supported pero.Color definitions, pero.Palette or registered palett... | Implement the Python class `GradientProperty` described below.
Class description:
Defines a color gradient property, which simplifies a gradient definition by automatically creating a pero.Gradient instance from various input options such as a list of supported pero.Color definitions, pero.Palette or registered palett... | d59b1bc056f3037b7b7ab635b6deb41120612965 | <|skeleton|>
class GradientProperty:
"""Defines a color gradient property, which simplifies a gradient definition by automatically creating a pero.Gradient instance from various input options such as a list of supported pero.Color definitions, pero.Palette or registered palette or gradient name."""
def __init_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradientProperty:
"""Defines a color gradient property, which simplifies a gradient definition by automatically creating a pero.Gradient instance from various input options such as a list of supported pero.Color definitions, pero.Palette or registered palette or gradient name."""
def __init__(self, defau... | the_stack_v2_python_sparse | pero/properties/special.py | xxao/pero | train | 31 |
3366cdec7d755a4e7561abdab73899e58ad0b0ea | [
"from dials.algorithms.background.gmodel import Creator\nmodel = global_model_cache.get(model)\nself._create = Creator(model=model, robust=robust, min_pixels=min_pixels)",
"if image_volume is None:\n success = self._create(reflections)\n reflections['background.mean'] = reflections['shoebox'].mean_modelled_... | <|body_start_0|>
from dials.algorithms.background.gmodel import Creator
model = global_model_cache.get(model)
self._create = Creator(model=model, robust=robust, min_pixels=min_pixels)
<|end_body_0|>
<|body_start_1|>
if image_volume is None:
success = self._create(reflections... | Class to do background subtraction. | BackgroundAlgorithm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackgroundAlgorithm:
"""Class to do background subtraction."""
def __init__(self, experiments, model=None, robust=False, tuning_constant=1.345, min_pixels=10):
"""Initialise the algorithm. :param experiments: The list of experiments :param model: The background model :param robust: U... | stack_v2_sparse_classes_36k_train_021053 | 2,824 | permissive | [
{
"docstring": "Initialise the algorithm. :param experiments: The list of experiments :param model: The background model :param robust: Use the robust background algorithm :param tuning_constant: The robust tuning constant",
"name": "__init__",
"signature": "def __init__(self, experiments, model=None, r... | 2 | stack_v2_sparse_classes_30k_train_008977 | Implement the Python class `BackgroundAlgorithm` described below.
Class description:
Class to do background subtraction.
Method signatures and docstrings:
- def __init__(self, experiments, model=None, robust=False, tuning_constant=1.345, min_pixels=10): Initialise the algorithm. :param experiments: The list of experi... | Implement the Python class `BackgroundAlgorithm` described below.
Class description:
Class to do background subtraction.
Method signatures and docstrings:
- def __init__(self, experiments, model=None, robust=False, tuning_constant=1.345, min_pixels=10): Initialise the algorithm. :param experiments: The list of experi... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class BackgroundAlgorithm:
"""Class to do background subtraction."""
def __init__(self, experiments, model=None, robust=False, tuning_constant=1.345, min_pixels=10):
"""Initialise the algorithm. :param experiments: The list of experiments :param model: The background model :param robust: U... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BackgroundAlgorithm:
"""Class to do background subtraction."""
def __init__(self, experiments, model=None, robust=False, tuning_constant=1.345, min_pixels=10):
"""Initialise the algorithm. :param experiments: The list of experiments :param model: The background model :param robust: Use the robust... | the_stack_v2_python_sparse | src/dials/algorithms/background/gmodel/algorithm.py | dials/dials | train | 71 |
31a31b770b0cda07b483ceef0f662d8be41e10b1 | [
"m, n = np.shape(A)\nself.bas_size = m\nself.nonbas_size = n\nif np.any(b < 0):\n raise ValueError('The Problem is Not Feasible at the Origin')\nself.c = c\nself.A = A\nself.b = b\nself.var = np.hstack((np.arange(n, n + m), np.arange(n)))\nc_hat = np.hstack((c, np.zeros(m)))\nA_hat = np.hstack((A, np.eye(m)))\nT... | <|body_start_0|>
m, n = np.shape(A)
self.bas_size = m
self.nonbas_size = n
if np.any(b < 0):
raise ValueError('The Problem is Not Feasible at the Origin')
self.c = c
self.A = A
self.b = b
self.var = np.hstack((np.arange(n, n + m), np.arange(n))... | Class for solving the standard linear optimization problem maximize c^Tx subject to Ax <= b x >= 0 via the Simplex algorithm. | SimplexSolver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimplexSolver:
"""Class for solving the standard linear optimization problem maximize c^Tx subject to Ax <= b x >= 0 via the Simplex algorithm."""
def __init__(self, c, A, b):
"""Check for feasibility and initialize the tableau. Parameters: c ((n,) ndarray): The coefficients of the o... | stack_v2_sparse_classes_36k_train_021054 | 7,025 | no_license | [
{
"docstring": "Check for feasibility and initialize the tableau. Parameters: c ((n,) ndarray): The coefficients of the objective function. A ((m,n) ndarray): The constraint coefficients matrix. b ((m,) ndarray): The constraint vector. Raises: ValueError: if the given system is infeasible at the origin.",
"... | 4 | stack_v2_sparse_classes_30k_train_014421 | Implement the Python class `SimplexSolver` described below.
Class description:
Class for solving the standard linear optimization problem maximize c^Tx subject to Ax <= b x >= 0 via the Simplex algorithm.
Method signatures and docstrings:
- def __init__(self, c, A, b): Check for feasibility and initialize the tableau... | Implement the Python class `SimplexSolver` described below.
Class description:
Class for solving the standard linear optimization problem maximize c^Tx subject to Ax <= b x >= 0 via the Simplex algorithm.
Method signatures and docstrings:
- def __init__(self, c, A, b): Check for feasibility and initialize the tableau... | 9e0cc823f63868da93fbb6f56133da2b85c9094a | <|skeleton|>
class SimplexSolver:
"""Class for solving the standard linear optimization problem maximize c^Tx subject to Ax <= b x >= 0 via the Simplex algorithm."""
def __init__(self, c, A, b):
"""Check for feasibility and initialize the tableau. Parameters: c ((n,) ndarray): The coefficients of the o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimplexSolver:
"""Class for solving the standard linear optimization problem maximize c^Tx subject to Ax <= b x >= 0 via the Simplex algorithm."""
def __init__(self, c, A, b):
"""Check for feasibility and initialize the tableau. Parameters: c ((n,) ndarray): The coefficients of the objective func... | the_stack_v2_python_sparse | Mathematical_Coding/Simplex/simplex.py | mgrose2/Coding_Projects | train | 0 |
6efa6c275d8c110a5c176c2ef483c601bc164466 | [
"try:\n registry = oai_registry_api.get_by_id(registry_id)\n serializer = serializers.RegistrySerializer(registry)\n return Response(serializer.data, status=status.HTTP_200_OK)\nexcept exceptions.DoesNotExist:\n content = OaiPmhMessage.get_message_labelled('No registry found with the given id.')\n re... | <|body_start_0|>
try:
registry = oai_registry_api.get_by_id(registry_id)
serializer = serializers.RegistrySerializer(registry)
return Response(serializer.data, status=status.HTTP_200_OK)
except exceptions.DoesNotExist:
content = OaiPmhMessage.get_message_l... | RegistryDetail | [
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistryDetail:
def get(self, request, registry_id):
"""Retrieve a Registry (Data provider) Args: request: HTTP request registry_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 content: Internal server error"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_021055 | 16,118 | permissive | [
{
"docstring": "Retrieve a Registry (Data provider) Args: request: HTTP request registry_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 content: Internal server error",
"name": "get",
"signature": "def get(self, request, registry_id)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_016480 | Implement the Python class `RegistryDetail` described below.
Class description:
Implement the RegistryDetail class.
Method signatures and docstrings:
- def get(self, request, registry_id): Retrieve a Registry (Data provider) Args: request: HTTP request registry_id: ObjectId Returns: - code: 200 content: Registry - co... | Implement the Python class `RegistryDetail` described below.
Class description:
Implement the RegistryDetail class.
Method signatures and docstrings:
- def get(self, request, registry_id): Retrieve a Registry (Data provider) Args: request: HTTP request registry_id: ObjectId Returns: - code: 200 content: Registry - co... | e41fd9c5a75b51dc626995e753a5840f238a557d | <|skeleton|>
class RegistryDetail:
def get(self, request, registry_id):
"""Retrieve a Registry (Data provider) Args: request: HTTP request registry_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 content: Internal server error"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistryDetail:
def get(self, request, registry_id):
"""Retrieve a Registry (Data provider) Args: request: HTTP request registry_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 content: Internal server error"""
try:
registry... | the_stack_v2_python_sparse | core_oaipmh_harvester_app/rest/oai_registry/views.py | faical-yannick-congo/core_oaipmh_harvester_app | train | 0 | |
6315e87ad725948c6e3299ee34916634276d9e83 | [
"curs.execute('DROP TABLE IF EXISTS jotd')\nconn.commit()\ncurs.execute(TBLDEF)\nconn.commit()\nself.starttime = datetime.datetime.today()\nday = self.starttime\nself.daycount = 50\nself.jokeDB = []\nself.datelist = []\nself.recipients = (('bill', 'bill@ourcompany.com'), ('teresa', 'teresa@ourcompany.com'))\nfor j ... | <|body_start_0|>
curs.execute('DROP TABLE IF EXISTS jotd')
conn.commit()
curs.execute(TBLDEF)
conn.commit()
self.starttime = datetime.datetime.today()
day = self.starttime
self.daycount = 50
self.jokeDB = []
self.datelist = []
self.recipien... | testEmailJoker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class testEmailJoker:
def setUp(self):
"""This method sets up a jotd table for each test; it uses only 2 mail recipients and a DAYCOUNT of 50. Also, the jokes are a single word with a numeric suffix for easy comparison"""
<|body_0|>
def test_numOfDates(self):
"""This metho... | stack_v2_sparse_classes_36k_train_021056 | 4,301 | no_license | [
{
"docstring": "This method sets up a jotd table for each test; it uses only 2 mail recipients and a DAYCOUNT of 50. Also, the jokes are a single word with a numeric suffix for easy comparison",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "This method tests the number of un... | 5 | null | Implement the Python class `testEmailJoker` described below.
Class description:
Implement the testEmailJoker class.
Method signatures and docstrings:
- def setUp(self): This method sets up a jotd table for each test; it uses only 2 mail recipients and a DAYCOUNT of 50. Also, the jokes are a single word with a numeric... | Implement the Python class `testEmailJoker` described below.
Class description:
Implement the testEmailJoker class.
Method signatures and docstrings:
- def setUp(self): This method sets up a jotd table for each test; it uses only 2 mail recipients and a DAYCOUNT of 50. Also, the jokes are a single word with a numeric... | b32f83aa1b705a5ad384b73c618f04f7d2622753 | <|skeleton|>
class testEmailJoker:
def setUp(self):
"""This method sets up a jotd table for each test; it uses only 2 mail recipients and a DAYCOUNT of 50. Also, the jokes are a single word with a numeric suffix for easy comparison"""
<|body_0|>
def test_numOfDates(self):
"""This metho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class testEmailJoker:
def setUp(self):
"""This method sets up a jotd table for each test; it uses only 2 mail recipients and a DAYCOUNT of 50. Also, the jokes are a single word with a numeric suffix for easy comparison"""
curs.execute('DROP TABLE IF EXISTS jotd')
conn.commit()
curs.e... | the_stack_v2_python_sparse | ostPython2/testEmailJoker.py | deepbsd/OST_Python | train | 1 | |
68a3466f487f7256f9992c5d8cbc949f9f73579c | [
"langs = ['ar', 'fa', 'de', 'es', 'fr', 'it', 'ja', 'pt', 'ru', 'zh']\nfor l in langs:\n p = dict()\n p['language'] = l\n taskqueue.add(url='/wwl/localize', params=p, queue_name='translations')",
"language = self.request.get('language')\nTextTranslations.update(language)\nself.response.out.write('ok')"
] | <|body_start_0|>
langs = ['ar', 'fa', 'de', 'es', 'fr', 'it', 'ja', 'pt', 'ru', 'zh']
for l in langs:
p = dict()
p['language'] = l
taskqueue.add(url='/wwl/localize', params=p, queue_name='translations')
<|end_body_0|>
<|body_start_1|>
language = self.request.... | LocalizeHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalizeHandler:
def get(self):
"""/wwl/localize cron job"""
<|body_0|>
def post(self):
"""/wwl/localize worker task"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
langs = ['ar', 'fa', 'de', 'es', 'fr', 'it', 'ja', 'pt', 'ru', 'zh']
for l i... | stack_v2_sparse_classes_36k_train_021057 | 6,503 | no_license | [
{
"docstring": "/wwl/localize cron job",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "/wwl/localize worker task",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021185 | Implement the Python class `LocalizeHandler` described below.
Class description:
Implement the LocalizeHandler class.
Method signatures and docstrings:
- def get(self): /wwl/localize cron job
- def post(self): /wwl/localize worker task | Implement the Python class `LocalizeHandler` described below.
Class description:
Implement the LocalizeHandler class.
Method signatures and docstrings:
- def get(self): /wwl/localize cron job
- def post(self): /wwl/localize worker task
<|skeleton|>
class LocalizeHandler:
def get(self):
"""/wwl/localize ... | 06f65ff465c4dc742e71c9d17ec04268762bc9f3 | <|skeleton|>
class LocalizeHandler:
def get(self):
"""/wwl/localize cron job"""
<|body_0|>
def post(self):
"""/wwl/localize worker task"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalizeHandler:
def get(self):
"""/wwl/localize cron job"""
langs = ['ar', 'fa', 'de', 'es', 'fr', 'it', 'ja', 'pt', 'ru', 'zh']
for l in langs:
p = dict()
p['language'] = l
taskqueue.add(url='/wwl/localize', params=p, queue_name='translations')
... | the_stack_v2_python_sparse | worldwidelexicon/widgets/wwlproxy/ui.py | thiur/worldwidelexicon | train | 0 | |
e61ac1b1912fe71dfc63b443b8d8f6c4abed2c39 | [
"super(TaylorActivation, self).__init__()\nself.beta = torch.nn.Parameter(torch.Tensor([beta]))\nif alphas:\n self.alphas = torch.nn.Parameter(torch.Tensor(alphas))\nelse:\n self.alphas = torch.nn.Parameter(torch.normal(0.0, 0.1, size=(degree + 1,)))\nself.clip_min = clip_min\nself.clip_max = clip_max\nself.a... | <|body_start_0|>
super(TaylorActivation, self).__init__()
self.beta = torch.nn.Parameter(torch.Tensor([beta]))
if alphas:
self.alphas = torch.nn.Parameter(torch.Tensor(alphas))
else:
self.alphas = torch.nn.Parameter(torch.normal(0.0, 0.1, size=(degree + 1,)))
... | Implementation of taylor polynomial activation function Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input Parameters: - degree: - degree of polynomial (2 is ax^2 + bx + c) - alphas - coefficients of polynomial - beta - centering polynomial around point | TaylorActivation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaylorActivation:
"""Implementation of taylor polynomial activation function Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input Parameters: - degree: - degree of polynomial (2 is ax^2 + bx + c) - alphas - coefficients of polynomial ... | stack_v2_sparse_classes_36k_train_021058 | 2,547 | no_license | [
{
"docstring": "Initialization. INPUT: - alphas: trainable parameter - beta: trainable parameter - degree: degree of polynomial alpha is initialized with 1 value by default beta is initialized with 0 value by default",
"name": "__init__",
"signature": "def __init__(self, degree=4, alphas=None, beta=0.0,... | 2 | stack_v2_sparse_classes_30k_train_006535 | Implement the Python class `TaylorActivation` described below.
Class description:
Implementation of taylor polynomial activation function Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input Parameters: - degree: - degree of polynomial (2 is ax^2 + bx + c)... | Implement the Python class `TaylorActivation` described below.
Class description:
Implementation of taylor polynomial activation function Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input Parameters: - degree: - degree of polynomial (2 is ax^2 + bx + c)... | 821712ec5cf976c1e1ea8a28fac649778d7c48c5 | <|skeleton|>
class TaylorActivation:
"""Implementation of taylor polynomial activation function Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input Parameters: - degree: - degree of polynomial (2 is ax^2 + bx + c) - alphas - coefficients of polynomial ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaylorActivation:
"""Implementation of taylor polynomial activation function Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input Parameters: - degree: - degree of polynomial (2 is ax^2 + bx + c) - alphas - coefficients of polynomial - beta - cent... | the_stack_v2_python_sparse | taylor_activation.py | shamoons/pytorch-lstm-audio | train | 2 |
ab13cad3d494677b33821e9473c61a533631d073 | [
"if not root:\n return '[]'\nqueue = [root]\nres = []\nwhile queue:\n root = queue.pop(0)\n if root:\n res.append(str(root.val))\n queue.append(root.left)\n queue.append(root.right)\n else:\n res.append('#')\nreturn '[' + ','.join(res) + ']'",
"if data == '[]':\n return\... | <|body_start_0|>
if not root:
return '[]'
queue = [root]
res = []
while queue:
root = queue.pop(0)
if root:
res.append(str(root.val))
queue.append(root.left)
queue.append(root.right)
else:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_021059 | 4,279 | 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 | stack_v2_sparse_classes_30k_train_018349 | 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:... | 7ffdb772ad7252f3d4b9aa2689a92cb1f10c8f37 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
queue = [root]
res = []
while queue:
root = queue.pop(0)
if root:
res.append(str(root... | the_stack_v2_python_sparse | 二叉树/297-二叉树的序列化和反序列化.py | zhengsizuo/leetcode-zhs | train | 0 | |
43734b78b5aa22cb8e7882f19a78f3dc93fbfaf1 | [
"A.sort()\nfor i, a in enumerate(A):\n if a >= 0 or K <= 0:\n break\n A[i] = -a\n K -= 1\nif K % 2:\n return sum(A) - 2 * min(A)\nreturn sum(A)",
"heapq.heapify(A)\nwhile K:\n min_ = heapq.heappop(A)\n heapq.heappush(A, -min_)\n K -= 1\nreturn sum(A)"
] | <|body_start_0|>
A.sort()
for i, a in enumerate(A):
if a >= 0 or K <= 0:
break
A[i] = -a
K -= 1
if K % 2:
return sum(A) - 2 * min(A)
return sum(A)
<|end_body_0|>
<|body_start_1|>
heapq.heapify(A)
while K:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestSumAfterKNegations1(self, A: List[int], K: int) -> int:
"""执行用时 :68 ms, 在所有 Python3 提交中击败了61.61%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了20.00%的用户 :param A: :param K: :return:"""
<|body_0|>
def largestSumAfterKNegations2(self, A: List[int], K: int) -> int:
... | stack_v2_sparse_classes_36k_train_021060 | 2,143 | no_license | [
{
"docstring": "执行用时 :68 ms, 在所有 Python3 提交中击败了61.61%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了20.00%的用户 :param A: :param K: :return:",
"name": "largestSumAfterKNegations1",
"signature": "def largestSumAfterKNegations1(self, A: List[int], K: int) -> int"
},
{
"docstring": "思路:每次修改堆顶元素 @param A: @para... | 2 | stack_v2_sparse_classes_30k_train_018286 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestSumAfterKNegations1(self, A: List[int], K: int) -> int: 执行用时 :68 ms, 在所有 Python3 提交中击败了61.61%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了20.00%的用户 :param A: :param K: :return... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestSumAfterKNegations1(self, A: List[int], K: int) -> int: 执行用时 :68 ms, 在所有 Python3 提交中击败了61.61%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了20.00%的用户 :param A: :param K: :return... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def largestSumAfterKNegations1(self, A: List[int], K: int) -> int:
"""执行用时 :68 ms, 在所有 Python3 提交中击败了61.61%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了20.00%的用户 :param A: :param K: :return:"""
<|body_0|>
def largestSumAfterKNegations2(self, A: List[int], K: int) -> int:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestSumAfterKNegations1(self, A: List[int], K: int) -> int:
"""执行用时 :68 ms, 在所有 Python3 提交中击败了61.61%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了20.00%的用户 :param A: :param K: :return:"""
A.sort()
for i, a in enumerate(A):
if a >= 0 or K <= 0:
break
... | the_stack_v2_python_sparse | LeetCode/贪心算法/1005. Maximize Sum Of Array After K Negations.py | yiming1012/MyLeetCode | train | 2 | |
d6be00ccf47290fe8b6f57d81fb98c1c525a0dcf | [
"_sum = sum(weights)\nprob = [w * 1.0 / _sum for w in weights]\nself.range, curr_sum = ([], 0)\nfor i in range(len(prob)):\n self.range.append((curr_sum, curr_sum + prob[i]))\n curr_sum += prob[i]",
"num = random.uniform(0, 1)\nleft, right = (0, len(self.range) - 1)\nwhile right > left:\n mid = left + (r... | <|body_start_0|>
_sum = sum(weights)
prob = [w * 1.0 / _sum for w in weights]
self.range, curr_sum = ([], 0)
for i in range(len(prob)):
self.range.append((curr_sum, curr_sum + prob[i]))
curr_sum += prob[i]
<|end_body_0|>
<|body_start_1|>
num = random.unif... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, weights):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
_sum = sum(weights)
prob = [w * 1.0 / _sum for w in weights]
self.range, c... | stack_v2_sparse_classes_36k_train_021061 | 1,068 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, weights)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, weights): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, weights): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, weights):
""":type w: List[int]""... | ee79d3437cf47b26a4bca0ec798dc54d7b623453 | <|skeleton|>
class Solution:
def __init__(self, weights):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, weights):
""":type w: List[int]"""
_sum = sum(weights)
prob = [w * 1.0 / _sum for w in weights]
self.range, curr_sum = ([], 0)
for i in range(len(prob)):
self.range.append((curr_sum, curr_sum + prob[i]))
curr_sum += p... | the_stack_v2_python_sparse | Algorithm/Python/528.random-pick-with-weight.py | WuLC/LeetCode | train | 29 | |
5533738cfe772ea3bb4f6f84500b97841a7e4725 | [
"if self.field:\n return 'Date field summary aggregations for \"{0:s}\"'.format(self.field)\nreturn 'Date field summary aggregations for an unknown field.'",
"self.field = field\nself.field_query_string = field_query_string\nformatted_field_name = self.format_field_by_type(field)\nif field_query_string == '*':... | <|body_start_0|>
if self.field:
return 'Date field summary aggregations for "{0:s}"'.format(self.field)
return 'Date field summary aggregations for an unknown field.'
<|end_body_0|>
<|body_start_1|>
self.field = field
self.field_query_string = field_query_string
form... | Date-based Summary Aggregations. | DateSummaryAggregator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DateSummaryAggregator:
"""Date-based Summary Aggregations."""
def chart_title(self):
"""Returns a title for the chart."""
<|body_0|>
def run(self, field, field_query_string='*', start_time='', end_time='', date_interval='year'):
"""Runs the SummaryAggregation agg... | stack_v2_sparse_classes_36k_train_021062 | 13,136 | permissive | [
{
"docstring": "Returns a title for the chart.",
"name": "chart_title",
"signature": "def chart_title(self)"
},
{
"docstring": "Runs the SummaryAggregation aggregator. Args: field: What field to aggregate on. field_query_string: The field value(s) to aggregate on. supported_charts: The chart typ... | 2 | stack_v2_sparse_classes_30k_val_000648 | Implement the Python class `DateSummaryAggregator` described below.
Class description:
Date-based Summary Aggregations.
Method signatures and docstrings:
- def chart_title(self): Returns a title for the chart.
- def run(self, field, field_query_string='*', start_time='', end_time='', date_interval='year'): Runs the S... | Implement the Python class `DateSummaryAggregator` described below.
Class description:
Date-based Summary Aggregations.
Method signatures and docstrings:
- def chart_title(self): Returns a title for the chart.
- def run(self, field, field_query_string='*', start_time='', end_time='', date_interval='year'): Runs the S... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class DateSummaryAggregator:
"""Date-based Summary Aggregations."""
def chart_title(self):
"""Returns a title for the chart."""
<|body_0|>
def run(self, field, field_query_string='*', start_time='', end_time='', date_interval='year'):
"""Runs the SummaryAggregation agg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DateSummaryAggregator:
"""Date-based Summary Aggregations."""
def chart_title(self):
"""Returns a title for the chart."""
if self.field:
return 'Date field summary aggregations for "{0:s}"'.format(self.field)
return 'Date field summary aggregations for an unknown field... | the_stack_v2_python_sparse | timesketch/lib/aggregators/summary.py | google/timesketch | train | 2,263 |
fbbab8098e59f8c03536b89b41017fd4539f2dd5 | [
"with plt.style.context(self._config['STYLE_SHEET']):\n title = f'Residual Plot - {self._model_name}'\n y_pred = self._model.predict(self._test_x)\n return plot_residuals(self._test_y, y_pred, title, **kwargs)",
"with plt.style.context(self._config['STYLE_SHEET']):\n title = f'Prediction Error - {self... | <|body_start_0|>
with plt.style.context(self._config['STYLE_SHEET']):
title = f'Residual Plot - {self._model_name}'
y_pred = self._model.predict(self._test_x)
return plot_residuals(self._test_y, y_pred, title, **kwargs)
<|end_body_0|>
<|body_start_1|>
with plt.style.... | Visualization class for Regression models | RegressionVisualize | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegressionVisualize:
"""Visualization class for Regression models"""
def residuals(self, **kwargs):
"""Visualizes residuals of a regression model :return: matplotlib.Axes"""
<|body_0|>
def prediction_error(self, **kwargs):
"""Visualizes prediction error of a regr... | stack_v2_sparse_classes_36k_train_021063 | 10,271 | permissive | [
{
"docstring": "Visualizes residuals of a regression model :return: matplotlib.Axes",
"name": "residuals",
"signature": "def residuals(self, **kwargs)"
},
{
"docstring": "Visualizes prediction error of a regression model :return: matplotlib.Axes",
"name": "prediction_error",
"signature":... | 2 | stack_v2_sparse_classes_30k_test_000305 | Implement the Python class `RegressionVisualize` described below.
Class description:
Visualization class for Regression models
Method signatures and docstrings:
- def residuals(self, **kwargs): Visualizes residuals of a regression model :return: matplotlib.Axes
- def prediction_error(self, **kwargs): Visualizes predi... | Implement the Python class `RegressionVisualize` described below.
Class description:
Visualization class for Regression models
Method signatures and docstrings:
- def residuals(self, **kwargs): Visualizes residuals of a regression model :return: matplotlib.Axes
- def prediction_error(self, **kwargs): Visualizes predi... | c0f651bc63f2b49198e15814b891c9306b9f743b | <|skeleton|>
class RegressionVisualize:
"""Visualization class for Regression models"""
def residuals(self, **kwargs):
"""Visualizes residuals of a regression model :return: matplotlib.Axes"""
<|body_0|>
def prediction_error(self, **kwargs):
"""Visualizes prediction error of a regr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegressionVisualize:
"""Visualization class for Regression models"""
def residuals(self, **kwargs):
"""Visualizes residuals of a regression model :return: matplotlib.Axes"""
with plt.style.context(self._config['STYLE_SHEET']):
title = f'Residual Plot - {self._model_name}'
... | the_stack_v2_python_sparse | src/ml_utils/visualizations/visualizations.py | clausvestergaard/ml_utils | train | 0 |
26240c80712af3d109187846a61c46457617e11c | [
"sr = tmdb.search('fight club')[0]\nmovie = tmdb.getMovieInfo(sr['id'])\nself.assertEquals(sr['name'], movie['name'])",
"mid = tmdb.search('Inglourious Basterds')[0]['id']\nmovie = tmdb.getMovieInfo(mid)\nself.assertTrue(len(movie['cast']['director']) == 1)\nself.assertEquals(movie['cast']['director'][0]['name'],... | <|body_start_0|>
sr = tmdb.search('fight club')[0]
movie = tmdb.getMovieInfo(sr['id'])
self.assertEquals(sr['name'], movie['name'])
<|end_body_0|>
<|body_start_1|>
mid = tmdb.search('Inglourious Basterds')[0]['id']
movie = tmdb.getMovieInfo(mid)
self.assertTrue(len(movie... | test_getmovieinfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_getmovieinfo:
def test_search_to_info(self):
"""Gets a movie ID via search, then calls getMovieInfo using this"""
<|body_0|>
def test_get_director(self):
"""Checks you can get the director of a film"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_021064 | 3,403 | permissive | [
{
"docstring": "Gets a movie ID via search, then calls getMovieInfo using this",
"name": "test_search_to_info",
"signature": "def test_search_to_info(self)"
},
{
"docstring": "Checks you can get the director of a film",
"name": "test_get_director",
"signature": "def test_get_director(sel... | 2 | null | Implement the Python class `test_getmovieinfo` described below.
Class description:
Implement the test_getmovieinfo class.
Method signatures and docstrings:
- def test_search_to_info(self): Gets a movie ID via search, then calls getMovieInfo using this
- def test_get_director(self): Checks you can get the director of ... | Implement the Python class `test_getmovieinfo` described below.
Class description:
Implement the test_getmovieinfo class.
Method signatures and docstrings:
- def test_search_to_info(self): Gets a movie ID via search, then calls getMovieInfo using this
- def test_get_director(self): Checks you can get the director of ... | a883598248ad6f5273eb3be498e3b04a1fab6510 | <|skeleton|>
class test_getmovieinfo:
def test_search_to_info(self):
"""Gets a movie ID via search, then calls getMovieInfo using this"""
<|body_0|>
def test_get_director(self):
"""Checks you can get the director of a film"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_getmovieinfo:
def test_search_to_info(self):
"""Gets a movie ID via search, then calls getMovieInfo using this"""
sr = tmdb.search('fight club')[0]
movie = tmdb.getMovieInfo(sr['id'])
self.assertEquals(sr['name'], movie['name'])
def test_get_director(self):
""... | the_stack_v2_python_sparse | resources/lib/themoviedb/test_tmdb.py | GetSomeBlocks/ServerStatus | train | 0 | |
0bb08454bae8a940362ff26669f559e5697bb62d | [
"headers = super().request_headers(stream_state, **kwargs)\nheaders.update({'X-RestLi-Protocol-Version': '2.0.0'} if self.accounts else {})\nreturn headers",
"params = super().request_params(stream_state, stream_slice, next_page_token)\nif self.accounts:\n params['search'] = f'(id:(values:List({self.accounts})... | <|body_start_0|>
headers = super().request_headers(stream_state, **kwargs)
headers.update({'X-RestLi-Protocol-Version': '2.0.0'} if self.accounts else {})
return headers
<|end_body_0|>
<|body_start_1|>
params = super().request_params(stream_state, stream_slice, next_page_token)
... | Get Accounts data. More info about LinkedIn Ads / Accounts: https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads/account-structure/create-and-manage-accounts?tabs=http&view=li-lms-2023-05#search-for-accounts | Accounts | [
"MIT",
"LicenseRef-scancode-free-unknown",
"Elastic-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Accounts:
"""Get Accounts data. More info about LinkedIn Ads / Accounts: https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads/account-structure/create-and-manage-accounts?tabs=http&view=li-lms-2023-05#search-for-accounts"""
def request_headers(self, stream_state: Mapping[str... | stack_v2_sparse_classes_36k_train_021065 | 22,426 | permissive | [
{
"docstring": "If account_ids are specified as user's input from configuration, we must use MODIFIED header: {'X-RestLi-Protocol-Version': '2.0.0'}",
"name": "request_headers",
"signature": "def request_headers(self, stream_state: Mapping[str, Any], **kwargs) -> Mapping[str, Any]"
},
{
"docstri... | 2 | stack_v2_sparse_classes_30k_train_000775 | Implement the Python class `Accounts` described below.
Class description:
Get Accounts data. More info about LinkedIn Ads / Accounts: https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads/account-structure/create-and-manage-accounts?tabs=http&view=li-lms-2023-05#search-for-accounts
Method signatures a... | Implement the Python class `Accounts` described below.
Class description:
Get Accounts data. More info about LinkedIn Ads / Accounts: https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads/account-structure/create-and-manage-accounts?tabs=http&view=li-lms-2023-05#search-for-accounts
Method signatures a... | 258a8eb683634a9f9b7821c9a92d1b70c5389a10 | <|skeleton|>
class Accounts:
"""Get Accounts data. More info about LinkedIn Ads / Accounts: https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads/account-structure/create-and-manage-accounts?tabs=http&view=li-lms-2023-05#search-for-accounts"""
def request_headers(self, stream_state: Mapping[str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Accounts:
"""Get Accounts data. More info about LinkedIn Ads / Accounts: https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads/account-structure/create-and-manage-accounts?tabs=http&view=li-lms-2023-05#search-for-accounts"""
def request_headers(self, stream_state: Mapping[str, Any], **kwa... | the_stack_v2_python_sparse | airbyte-integrations/connectors/source-linkedin-ads/source_linkedin_ads/streams.py | thomas-vl/airbyte | train | 1 |
80450931af747cb592c68ba744d56bfdf30578d1 | [
"super(GAPConv1x1, self).__init__()\nif '0.2' in torch.__version__:\n self.globalpool = nn.AvgPool2d(14)\nself.conv1x1 = conv_bn_relu(C_in, C_out, 1, stride=1, padding=0)",
"size = x.size()[2:]\nif '0.2' in torch.__version__:\n out = self.globalpool(x)\nelse:\n out = x.mean(2, keepdim=True).mean(3, keepd... | <|body_start_0|>
super(GAPConv1x1, self).__init__()
if '0.2' in torch.__version__:
self.globalpool = nn.AvgPool2d(14)
self.conv1x1 = conv_bn_relu(C_in, C_out, 1, stride=1, padding=0)
<|end_body_0|>
<|body_start_1|>
size = x.size()[2:]
if '0.2' in torch.__version__:
... | Global Average Pooling + conv1x1. | GAPConv1x1 | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GAPConv1x1:
"""Global Average Pooling + conv1x1."""
def __init__(self, C_in, C_out):
"""Construct GAPConv1x1 class. :param C_in: input channel :param C_out: output channel"""
<|body_0|>
def forward(self, x):
"""Do an inference on GAPConv1x1. :param x: input tenso... | stack_v2_sparse_classes_36k_train_021066 | 27,877 | permissive | [
{
"docstring": "Construct GAPConv1x1 class. :param C_in: input channel :param C_out: output channel",
"name": "__init__",
"signature": "def __init__(self, C_in, C_out)"
},
{
"docstring": "Do an inference on GAPConv1x1. :param x: input tensor :return: output tensor",
"name": "forward",
"s... | 2 | null | Implement the Python class `GAPConv1x1` described below.
Class description:
Global Average Pooling + conv1x1.
Method signatures and docstrings:
- def __init__(self, C_in, C_out): Construct GAPConv1x1 class. :param C_in: input channel :param C_out: output channel
- def forward(self, x): Do an inference on GAPConv1x1. ... | Implement the Python class `GAPConv1x1` described below.
Class description:
Global Average Pooling + conv1x1.
Method signatures and docstrings:
- def __init__(self, C_in, C_out): Construct GAPConv1x1 class. :param C_in: input channel :param C_out: output channel
- def forward(self, x): Do an inference on GAPConv1x1. ... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class GAPConv1x1:
"""Global Average Pooling + conv1x1."""
def __init__(self, C_in, C_out):
"""Construct GAPConv1x1 class. :param C_in: input channel :param C_out: output channel"""
<|body_0|>
def forward(self, x):
"""Do an inference on GAPConv1x1. :param x: input tenso... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GAPConv1x1:
"""Global Average Pooling + conv1x1."""
def __init__(self, C_in, C_out):
"""Construct GAPConv1x1 class. :param C_in: input channel :param C_out: output channel"""
super(GAPConv1x1, self).__init__()
if '0.2' in torch.__version__:
self.globalpool = nn.AvgPool... | the_stack_v2_python_sparse | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/search_space/networks/pytorch/operator/op.py | Huawei-Ascend/modelzoo | train | 1 |
a7cdde2e13270dbc0dd227e9999540334cdd5141 | [
"self.threshold = threshold\nself.max_depth = max_depth\nself.eta = eta\nself.gamma = gamma\nself.silent = silent\nself.min_child_weight = min_child_weight\nself.subsample = subsample\nself.colsample_bytree = colsample_bytree\nself.booster = booster\nself.objective = objective\nself.eval_metric = eval_metric",
"t... | <|body_start_0|>
self.threshold = threshold
self.max_depth = max_depth
self.eta = eta
self.gamma = gamma
self.silent = silent
self.min_child_weight = min_child_weight
self.subsample = subsample
self.colsample_bytree = colsample_bytree
self.booster ... | XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many data science problems in a fast and a... | XGBoosting | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XGBoosting:
"""XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many... | stack_v2_sparse_classes_36k_train_021067 | 7,445 | permissive | [
{
"docstring": ":param threshold: The critical point of normal. :param max_depth: Maximum tree depth for base learners. :param eta: Value means model more robust to overfitting but slower to compute. :param gamma: Minimum loss reduction required to make a further partition on a leaf node of the tree. :param sil... | 5 | stack_v2_sparse_classes_30k_train_009659 | Implement the Python class `XGBoosting` described below.
Class description:
XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting (a... | Implement the Python class `XGBoosting` described below.
Class description:
XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting (a... | ce10eae41cb15ee3d1f07692d5c92491a3fca9bf | <|skeleton|>
class XGBoosting:
"""XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XGBoosting:
"""XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many data science... | the_stack_v2_python_sparse | time_series_detector/algorithm/xgboosting.py | edwinjiang703/ruiqi_aiops | train | 0 |
8ef52891f3f331ea09aadfefe9381c54a9587837 | [
"if n == 0:\n return 1.0\nif n < 0:\n return 1.0 / self.myPow(x, -n)\nif n % 2 == 1:\n return self.myPow(x * x, n / 2) * x\nelse:\n return self.myPow(x * x, n / 2)",
"if n == 0:\n return 1.0\nif n < 0:\n return 1.0 / self.myPow2(x, -n)\nres = 1.0\nwhile n > 0:\n if n % 2 == 1:\n res *=... | <|body_start_0|>
if n == 0:
return 1.0
if n < 0:
return 1.0 / self.myPow(x, -n)
if n % 2 == 1:
return self.myPow(x * x, n / 2) * x
else:
return self.myPow(x * x, n / 2)
<|end_body_0|>
<|body_start_1|>
if n == 0:
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myPow(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_0|>
def myPow2(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0:
return 1.0
... | stack_v2_sparse_classes_36k_train_021068 | 790 | no_license | [
{
"docstring": ":type x: float :type n: int :rtype: float",
"name": "myPow",
"signature": "def myPow(self, x, n)"
},
{
"docstring": ":type x: float :type n: int :rtype: float",
"name": "myPow2",
"signature": "def myPow2(self, x, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow(self, x, n): :type x: float :type n: int :rtype: float
- def myPow2(self, x, n): :type x: float :type n: int :rtype: float | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow(self, x, n): :type x: float :type n: int :rtype: float
- def myPow2(self, x, n): :type x: float :type n: int :rtype: float
<|skeleton|>
class Solution:
def myPow(... | 31b2b4dc1e5c3b1c53b333fe30b98ed04b0bdacc | <|skeleton|>
class Solution:
def myPow(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_0|>
def myPow2(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def myPow(self, x, n):
""":type x: float :type n: int :rtype: float"""
if n == 0:
return 1.0
if n < 0:
return 1.0 / self.myPow(x, -n)
if n % 2 == 1:
return self.myPow(x * x, n / 2) * x
else:
return self.myPow(x *... | the_stack_v2_python_sparse | prob050_powxn.py | Hu-Wenchao/leetcode | train | 0 | |
ec2e8bb86780652c84ce52f715e90ccd603b9533 | [
"self.p = Pipeline()\nfor FH in filesToResample:\n dirForOutput = self.getOutputDirectory(FH)\n currentRes = volumeFromFile(FH.getLastBasevol()).separations\n if not abs(abs(currentRes[0]) - abs(resolution)) < 0.01:\n crop = ma.autocrop(resolution, FH, defaultDir=dirForOutput)\n self.p.addSta... | <|body_start_0|>
self.p = Pipeline()
for FH in filesToResample:
dirForOutput = self.getOutputDirectory(FH)
currentRes = volumeFromFile(FH.getLastBasevol()).separations
if not abs(abs(currentRes[0]) - abs(resolution)) < 0.01:
crop = ma.autocrop(resoluti... | SetResolution | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetResolution:
def __init__(self, filesToResample, resolution):
"""During initialization make sure all files are resampled at resolution we'd like to use for each pipeline stage"""
<|body_0|>
def getOutputDirectory(self, FH):
"""Sets output directory based on whether... | stack_v2_sparse_classes_36k_train_021069 | 26,892 | permissive | [
{
"docstring": "During initialization make sure all files are resampled at resolution we'd like to use for each pipeline stage",
"name": "__init__",
"signature": "def __init__(self, filesToResample, resolution)"
},
{
"docstring": "Sets output directory based on whether or not we have a full Regi... | 2 | stack_v2_sparse_classes_30k_train_006835 | Implement the Python class `SetResolution` described below.
Class description:
Implement the SetResolution class.
Method signatures and docstrings:
- def __init__(self, filesToResample, resolution): During initialization make sure all files are resampled at resolution we'd like to use for each pipeline stage
- def ge... | Implement the Python class `SetResolution` described below.
Class description:
Implement the SetResolution class.
Method signatures and docstrings:
- def __init__(self, filesToResample, resolution): During initialization make sure all files are resampled at resolution we'd like to use for each pipeline stage
- def ge... | 1989e6d750c44f0e3e3599d8e080e30a46c7ab81 | <|skeleton|>
class SetResolution:
def __init__(self, filesToResample, resolution):
"""During initialization make sure all files are resampled at resolution we'd like to use for each pipeline stage"""
<|body_0|>
def getOutputDirectory(self, FH):
"""Sets output directory based on whether... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SetResolution:
def __init__(self, filesToResample, resolution):
"""During initialization make sure all files are resampled at resolution we'd like to use for each pipeline stage"""
self.p = Pipeline()
for FH in filesToResample:
dirForOutput = self.getOutputDirectory(FH)
... | the_stack_v2_python_sparse | atoms_and_modules/minc_modules.py | edeguzman/pydpiper | train | 0 | |
90a8560e68210f05645872a3614e8aeea3b75853 | [
"try:\n response = EmailTemplateHandler.get_email_templates(user_id)\n if response:\n return (response, 200)\n return ({'Message': 'Not Found'}, 400)\nexcept Exception as e:\n logger.exception(repr(e), extra=request_as_log_dict(request))\n return ('error occurred', 400)",
"try:\n data = E... | <|body_start_0|>
try:
response = EmailTemplateHandler.get_email_templates(user_id)
if response:
return (response, 200)
return ({'Message': 'Not Found'}, 400)
except Exception as e:
logger.exception(repr(e), extra=request_as_log_dict(request... | EmailTemplates | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailTemplates:
def get(self, user_id):
"""This GET request will fetch the saved templates of the user. @param user_id: User requesting the templates @return: Dict containing templates"""
<|body_0|>
def post(self, user_id):
"""This POST request saves template of the ... | stack_v2_sparse_classes_36k_train_021070 | 7,627 | no_license | [
{
"docstring": "This GET request will fetch the saved templates of the user. @param user_id: User requesting the templates @return: Dict containing templates",
"name": "get",
"signature": "def get(self, user_id)"
},
{
"docstring": "This POST request saves template of the user to the database. @p... | 2 | null | Implement the Python class `EmailTemplates` described below.
Class description:
Implement the EmailTemplates class.
Method signatures and docstrings:
- def get(self, user_id): This GET request will fetch the saved templates of the user. @param user_id: User requesting the templates @return: Dict containing templates
... | Implement the Python class `EmailTemplates` described below.
Class description:
Implement the EmailTemplates class.
Method signatures and docstrings:
- def get(self, user_id): This GET request will fetch the saved templates of the user. @param user_id: User requesting the templates @return: Dict containing templates
... | 17b93889c6945db15ed8b57147def2ae89a07de5 | <|skeleton|>
class EmailTemplates:
def get(self, user_id):
"""This GET request will fetch the saved templates of the user. @param user_id: User requesting the templates @return: Dict containing templates"""
<|body_0|>
def post(self, user_id):
"""This POST request saves template of the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailTemplates:
def get(self, user_id):
"""This GET request will fetch the saved templates of the user. @param user_id: User requesting the templates @return: Dict containing templates"""
try:
response = EmailTemplateHandler.get_email_templates(user_id)
if response:
... | the_stack_v2_python_sparse | FiledInfluencer/Api/routers.py | jssellars/aniket_filed | train | 0 | |
461c2b83c79a39c373c4ce305d6767e0e62d19a8 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Allows clients to observe the status of their submissions. Commands may be submitted via the Command Submission Service. The on-ledger effects of their submissions are disclosed by the Transaction Service. Commands may fail in 2 distinct manners: 1. Failure communicated synchronously in the gRPC error of the submission... | CommandCompletionServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandCompletionServiceServicer:
"""Allows clients to observe the status of their submissions. Commands may be submitted via the Command Submission Service. The on-ledger effects of their submissions are disclosed by the Transaction Service. Commands may fail in 2 distinct manners: 1. Failure co... | stack_v2_sparse_classes_36k_train_021071 | 7,734 | permissive | [
{
"docstring": "Subscribe to command completion events.",
"name": "CompletionStream",
"signature": "def CompletionStream(self, request, context)"
},
{
"docstring": "Returns the offset after the latest completion.",
"name": "CompletionEnd",
"signature": "def CompletionEnd(self, request, c... | 2 | null | Implement the Python class `CommandCompletionServiceServicer` described below.
Class description:
Allows clients to observe the status of their submissions. Commands may be submitted via the Command Submission Service. The on-ledger effects of their submissions are disclosed by the Transaction Service. Commands may fa... | Implement the Python class `CommandCompletionServiceServicer` described below.
Class description:
Allows clients to observe the status of their submissions. Commands may be submitted via the Command Submission Service. The on-ledger effects of their submissions are disclosed by the Transaction Service. Commands may fa... | efdbb00e54614c0af650d7440faaffbde92ad1f4 | <|skeleton|>
class CommandCompletionServiceServicer:
"""Allows clients to observe the status of their submissions. Commands may be submitted via the Command Submission Service. The on-ledger effects of their submissions are disclosed by the Transaction Service. Commands may fail in 2 distinct manners: 1. Failure co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommandCompletionServiceServicer:
"""Allows clients to observe the status of their submissions. Commands may be submitted via the Command Submission Service. The on-ledger effects of their submissions are disclosed by the Transaction Service. Commands may fail in 2 distinct manners: 1. Failure communicated sy... | the_stack_v2_python_sparse | python/dazl/_gen/com/daml/ledger/api/v1/command_completion_service_pb2_grpc.py | digital-asset/dazl-client | train | 12 |
898a7797e23923b5e2e23e22eb768bc8b01dc940 | [
"Component.__init__(self)\nself.name = 'Grid_default_name'\nself.input_max = 800000000\nself.bus_in = None\nself.set_parameters(params)\nself.commodity_costs = self.get_costs_and_art_costs()",
"sink = solph.Sink(label=self.name, inputs={busses[self.bus_in]: solph.Flow(variable_costs=self.commodity_costs, nominal_... | <|body_start_0|>
Component.__init__(self)
self.name = 'Grid_default_name'
self.input_max = 800000000
self.bus_in = None
self.set_parameters(params)
self.commodity_costs = self.get_costs_and_art_costs()
<|end_body_0|>
<|body_start_1|>
sink = solph.Sink(label=self.... | :param name: unique name given to the sink component :type name: str :param input_max: maximum input per timestep of commodity e.g. for excess electricity [Wh], heat [Wh], hydrogen [kg] :type input_max: numerical :param bus_in: input bus of the sink component e.g. the electricity bus :type bus_in: str :param set_parame... | Sink | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sink:
""":param name: unique name given to the sink component :type name: str :param input_max: maximum input per timestep of commodity e.g. for excess electricity [Wh], heat [Wh], hydrogen [kg] :type input_max: numerical :param bus_in: input bus of the sink component e.g. the electricity bus :ty... | stack_v2_sparse_classes_36k_train_021072 | 2,520 | permissive | [
{
"docstring": "Constructor method",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Creates an oemof Sink component from the information given in the Sink class, to be used in the oemof model. :param busses: virtual buses used in the energy system :type busses: ... | 2 | stack_v2_sparse_classes_30k_train_008985 | Implement the Python class `Sink` described below.
Class description:
:param name: unique name given to the sink component :type name: str :param input_max: maximum input per timestep of commodity e.g. for excess electricity [Wh], heat [Wh], hydrogen [kg] :type input_max: numerical :param bus_in: input bus of the sink... | Implement the Python class `Sink` described below.
Class description:
:param name: unique name given to the sink component :type name: str :param input_max: maximum input per timestep of commodity e.g. for excess electricity [Wh], heat [Wh], hydrogen [kg] :type input_max: numerical :param bus_in: input bus of the sink... | 0d4d55d587c18d9e05258f85c1bb41c0b5fdaee7 | <|skeleton|>
class Sink:
""":param name: unique name given to the sink component :type name: str :param input_max: maximum input per timestep of commodity e.g. for excess electricity [Wh], heat [Wh], hydrogen [kg] :type input_max: numerical :param bus_in: input bus of the sink component e.g. the electricity bus :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Sink:
""":param name: unique name given to the sink component :type name: str :param input_max: maximum input per timestep of commodity e.g. for excess electricity [Wh], heat [Wh], hydrogen [kg] :type input_max: numerical :param bus_in: input bus of the sink component e.g. the electricity bus :type bus_in: st... | the_stack_v2_python_sparse | smooth/components/component_sink.py | rl-institut/smooth | train | 7 |
1000e9e0fa0f2ee82e0decf81625afbbd627d0d0 | [
"workflow = context['workflow']\nfilter_data = validated_data.pop('filter', None)\nconditions_data = validated_data.pop('conditions', [])\nattachments_data = validated_data.pop('attachments', [])\ncolumn_condition_data = validated_data.pop('column_condition_pair', [])\nrubric_cells_data = validated_data.pop('rubric... | <|body_start_0|>
workflow = context['workflow']
filter_data = validated_data.pop('filter', None)
conditions_data = validated_data.pop('conditions', [])
attachments_data = validated_data.pop('attachments', [])
column_condition_data = validated_data.pop('column_condition_pair', [])... | Action serializer. The serializer does not create any columns and assumes they exist. | ActionSerializer | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionSerializer:
"""Action serializer. The serializer does not create any columns and assumes they exist."""
def create_action(validated_data, context: Dict) -> models.Action:
"""Create an action with the validated data and context. :param validated_data: Dictionary with the basic d... | stack_v2_sparse_classes_36k_train_021073 | 11,560 | permissive | [
{
"docstring": "Create an action with the validated data and context. :param validated_data: Dictionary with the basic data :param context: Dictionary with context information :return: New action",
"name": "create_action",
"signature": "def create_action(validated_data, context: Dict) -> models.Action"
... | 2 | null | Implement the Python class `ActionSerializer` described below.
Class description:
Action serializer. The serializer does not create any columns and assumes they exist.
Method signatures and docstrings:
- def create_action(validated_data, context: Dict) -> models.Action: Create an action with the validated data and co... | Implement the Python class `ActionSerializer` described below.
Class description:
Action serializer. The serializer does not create any columns and assumes they exist.
Method signatures and docstrings:
- def create_action(validated_data, context: Dict) -> models.Action: Create an action with the validated data and co... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class ActionSerializer:
"""Action serializer. The serializer does not create any columns and assumes they exist."""
def create_action(validated_data, context: Dict) -> models.Action:
"""Create an action with the validated data and context. :param validated_data: Dictionary with the basic d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionSerializer:
"""Action serializer. The serializer does not create any columns and assumes they exist."""
def create_action(validated_data, context: Dict) -> models.Action:
"""Create an action with the validated data and context. :param validated_data: Dictionary with the basic data :param co... | the_stack_v2_python_sparse | ontask/action/serializers/basic.py | abelardopardo/ontask_b | train | 43 |
299ccb59472e277027d7c4d4c412351dba047d0c | [
"self.thischar = ''\nself.child = {}\nself.leaf = False",
"if len(word) == 0:\n self.leaf = True\n return\nfc = word[0]\nrw = word[1:]\nif word[0] in self.child:\n tr = self.child[fc]\nelse:\n tr = Trie()\n tr.thischar = fc\n self.child[fc] = tr\ntr.insert(rw)"
] | <|body_start_0|>
self.thischar = ''
self.child = {}
self.leaf = False
<|end_body_0|>
<|body_start_1|>
if len(word) == 0:
self.leaf = True
return
fc = word[0]
rw = word[1:]
if word[0] in self.child:
tr = self.child[fc]
e... | Trie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.thischar = ''
self.child = {}
... | stack_v2_sparse_classes_36k_train_021074 | 1,568 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a word into the trie.",
"name": "insert",
"signature": "def insert(self, word: str) -> None"
}
] | 2 | null | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie. | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
<|skeleton|>
class Trie:
def __init__(self):
"... | afc5a08cd538c45e075fc6c479c255b3596d7ac5 | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trie:
def __init__(self):
"""Initialize your data structure here."""
self.thischar = ''
self.child = {}
self.leaf = False
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
if len(word) == 0:
self.leaf = True
re... | the_stack_v2_python_sparse | wordbreak2.py | gauravaror/programming | train | 0 | |
358b9fc7008e0fd736df204b022c6b2b48ccf631 | [
"self.dict = collections.defaultdict(set)\nfor word in dictionary:\n if word:\n self.dict[word[0] + str(len(word) - 2) + word[-1]].add(word)",
"if not word:\n return True\nkey = word[0] + str(len(word) - 2) + word[-1]\nif word in self.dict[key]:\n return len(self.dict[key]) == 1\nelse:\n return... | <|body_start_0|>
self.dict = collections.defaultdict(set)
for word in dictionary:
if word:
self.dict[word[0] + str(len(word) - 2) + word[-1]].add(word)
<|end_body_0|>
<|body_start_1|>
if not word:
return True
key = word[0] + str(len(word) - 2) + w... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dict = collections.defaultdict(set)
fo... | stack_v2_sparse_classes_36k_train_021075 | 751 | no_license | [
{
"docstring": ":type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": ":type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011587 | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool
<|skeleton|>
class ValidWordAbbr:
def __init_... | 5b14b6f42baf59b04cbcc8e115df4272029b64c8 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
self.dict = collections.defaultdict(set)
for word in dictionary:
if word:
self.dict[word[0] + str(len(word) - 2) + word[-1]].add(word)
def isUnique(self, word):
"""... | the_stack_v2_python_sparse | LeetCode/0288.Unique-Word-Abbreviation/Unique-Word-Abbreviation.py | htingwang/HandsOnAlgoDS | train | 12 | |
753af290990432673e7b9818afc1a23dbc678347 | [
"hash_input = set_up_variable_cube(np.zeros((3, 3)).astype(np.float32))\nresult = create_coordinate_hash(hash_input)\nexpected = '54812a6fed0f92fe75d180d63a6bd6c916407ea1e7e5fd32a5f20f86ea997fac'\nself.assertIsInstance(result, str)\nself.assertEqual(result, expected)",
"hash_input1 = set_up_variable_cube(np.zeros... | <|body_start_0|>
hash_input = set_up_variable_cube(np.zeros((3, 3)).astype(np.float32))
result = create_coordinate_hash(hash_input)
expected = '54812a6fed0f92fe75d180d63a6bd6c916407ea1e7e5fd32a5f20f86ea997fac'
self.assertIsInstance(result, str)
self.assertEqual(result, expected)
... | Test wrapper to hash generation to return a hash based on the x and y coordinates of a given cube. | Test_create_coordinate_hash | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_create_coordinate_hash:
"""Test wrapper to hash generation to return a hash based on the x and y coordinates of a given cube."""
def test_basic(self):
"""Test the expected hash is returned for a given cube."""
<|body_0|>
def test_variation(self):
"""Test tha... | stack_v2_sparse_classes_36k_train_021076 | 16,545 | permissive | [
{
"docstring": "Test the expected hash is returned for a given cube.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test that two cubes with slightly different coordinates return different hashes.",
"name": "test_variation",
"signature": "def test_variatio... | 2 | null | Implement the Python class `Test_create_coordinate_hash` described below.
Class description:
Test wrapper to hash generation to return a hash based on the x and y coordinates of a given cube.
Method signatures and docstrings:
- def test_basic(self): Test the expected hash is returned for a given cube.
- def test_vari... | Implement the Python class `Test_create_coordinate_hash` described below.
Class description:
Test wrapper to hash generation to return a hash based on the x and y coordinates of a given cube.
Method signatures and docstrings:
- def test_basic(self): Test the expected hash is returned for a given cube.
- def test_vari... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_create_coordinate_hash:
"""Test wrapper to hash generation to return a hash based on the x and y coordinates of a given cube."""
def test_basic(self):
"""Test the expected hash is returned for a given cube."""
<|body_0|>
def test_variation(self):
"""Test tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_create_coordinate_hash:
"""Test wrapper to hash generation to return a hash based on the x and y coordinates of a given cube."""
def test_basic(self):
"""Test the expected hash is returned for a given cube."""
hash_input = set_up_variable_cube(np.zeros((3, 3)).astype(np.float32))
... | the_stack_v2_python_sparse | improver_tests/metadata/test_utilities.py | metoppv/improver | train | 101 |
f2ac4125e7c71b835d6881fe4a11b54c47df276b | [
"try:\n if not is_pushed(review_request):\n return (False, 'Manually uploaded requests cannot be approved.')\n if not review_request.public:\n return (False, 'The review request is not public.')\n if is_parent(review_request):\n return self.is_approved_parent(review_request)\n retur... | <|body_start_0|>
try:
if not is_pushed(review_request):
return (False, 'Manually uploaded requests cannot be approved.')
if not review_request.public:
return (False, 'The review request is not public.')
if is_parent(review_request):
... | Calculates landing approval for review requests. This hook allows us to control the `approved` and `approval_failure` fields on review request model instances, and Web API results associated with them. By calculating landing approval and returning it here we have a nice way to distribute this decision throughout Review... | MozReviewApprovalHook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MozReviewApprovalHook:
"""Calculates landing approval for review requests. This hook allows us to control the `approved` and `approval_failure` fields on review request model instances, and Web API results associated with them. By calculating landing approval and returning it here we have a nice ... | stack_v2_sparse_classes_36k_train_021077 | 6,231 | permissive | [
{
"docstring": "Check if a review request is approved to land We will completely override the checks done by Review Board and provide our own (to keep approval simpler and explicit). If True is returned by this function it will indicate that review request may be autolanded - care should be taken when modifying... | 3 | null | Implement the Python class `MozReviewApprovalHook` described below.
Class description:
Calculates landing approval for review requests. This hook allows us to control the `approved` and `approval_failure` fields on review request model instances, and Web API results associated with them. By calculating landing approva... | Implement the Python class `MozReviewApprovalHook` described below.
Class description:
Calculates landing approval for review requests. This hook allows us to control the `approved` and `approval_failure` fields on review request model instances, and Web API results associated with them. By calculating landing approva... | 8ef71a98892473434dbd903647a11b6903b3c92a | <|skeleton|>
class MozReviewApprovalHook:
"""Calculates landing approval for review requests. This hook allows us to control the `approved` and `approval_failure` fields on review request model instances, and Web API results associated with them. By calculating landing approval and returning it here we have a nice ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MozReviewApprovalHook:
"""Calculates landing approval for review requests. This hook allows us to control the `approved` and `approval_failure` fields on review request model instances, and Web API results associated with them. By calculating landing approval and returning it here we have a nice way to distri... | the_stack_v2_python_sparse | pylib/mozreview/mozreview/hooks.py | mjzffr/version-control-tools | train | 1 |
18d77dd3863b9e011dbbbf4f0089361ed26993ba | [
"super(Blank, self).__init__()\nself.__keywords = sorted(kw.keys())\nfor k, v in kw.iteritems():\n setattr(self, k, v)\nself.__isfrozen = True",
"if self.__isfrozen and (not hasattr(self, name)):\n raise AttributeError(\"Trying to set invalid attribute '%s'. Valid attributes are: %s.\" % (name, ', '.join(se... | <|body_start_0|>
super(Blank, self).__init__()
self.__keywords = sorted(kw.keys())
for k, v in kw.iteritems():
setattr(self, k, v)
self.__isfrozen = True
<|end_body_0|>
<|body_start_1|>
if self.__isfrozen and (not hasattr(self, name)):
raise AttributeErro... | Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use of arbitrary descriptors similar to dictionaries, but with simpler access... | Blank | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Blank:
"""Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use of arbitrary descriptors similar to dict... | stack_v2_sparse_classes_36k_train_021078 | 4,466 | permissive | [
{
"docstring": "Initializes the attributes given in keyword arguments. No new attribute is allowed after this.",
"name": "__init__",
"signature": "def __init__(self, **kw)"
},
{
"docstring": "Sets an attribute. If the attribute name was given during initialization, it's set to value. Raises an e... | 4 | stack_v2_sparse_classes_30k_train_013240 | Implement the Python class `Blank` described below.
Class description:
Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use o... | Implement the Python class `Blank` described below.
Class description:
Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use o... | c1bcca66a5ef1ff0ebd6373e3820e72dee6b0b70 | <|skeleton|>
class Blank:
"""Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use of arbitrary descriptors similar to dict... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Blank:
"""Class with arbitrary but fixed attributes. During its creation, a dictionary in form of keyword arguments is used to define which attributes will be available. After initialization, we block creation of new attributes. The idea is to ease the use of arbitrary descriptors similar to dictionaries, but... | the_stack_v2_python_sparse | mir3/data/blank.py | pymir3/pymir3 | train | 13 |
e5101eb2823b74724e422188dda13b0345cf4723 | [
"threading.Thread.__init__(self)\nself.daemon = True\nself.bot = botClass()\nself.commandsQueue = commandsQueue",
"self.bot._Print('Thread started')\nwhile not self.commandsQueue.empty():\n command = self.commandsQueue.get()\n SocialBotCommand(self.bot, command).Execute()\n self.commandsQueue.task_done()... | <|body_start_0|>
threading.Thread.__init__(self)
self.daemon = True
self.bot = botClass()
self.commandsQueue = commandsQueue
<|end_body_0|>
<|body_start_1|>
self.bot._Print('Thread started')
while not self.commandsQueue.empty():
command = self.commandsQueue.g... | Ботом заданного класса выполняем набор команд в отдельном потоке | SocialBotThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SocialBotThread:
"""Ботом заданного класса выполняем набор команд в отдельном потоке"""
def __init__(self, botClass, commandsQueue):
"""Инициализация"""
<|body_0|>
def run(self):
"""Главный метод"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
t... | stack_v2_sparse_classes_36k_train_021079 | 7,553 | no_license | [
{
"docstring": "Инициализация",
"name": "__init__",
"signature": "def __init__(self, botClass, commandsQueue)"
},
{
"docstring": "Главный метод",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `SocialBotThread` described below.
Class description:
Ботом заданного класса выполняем набор команд в отдельном потоке
Method signatures and docstrings:
- def __init__(self, botClass, commandsQueue): Инициализация
- def run(self): Главный метод | Implement the Python class `SocialBotThread` described below.
Class description:
Ботом заданного класса выполняем набор команд в отдельном потоке
Method signatures and docstrings:
- def __init__(self, botClass, commandsQueue): Инициализация
- def run(self): Главный метод
<|skeleton|>
class SocialBotThread:
"""Бо... | d2771bf04aa187dda6d468883a5a167237589369 | <|skeleton|>
class SocialBotThread:
"""Ботом заданного класса выполняем набор команд в отдельном потоке"""
def __init__(self, botClass, commandsQueue):
"""Инициализация"""
<|body_0|>
def run(self):
"""Главный метод"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SocialBotThread:
"""Ботом заданного класса выполняем набор команд в отдельном потоке"""
def __init__(self, botClass, commandsQueue):
"""Инициализация"""
threading.Thread.__init__(self)
self.daemon = True
self.bot = botClass()
self.commandsQueue = commandsQueue
... | the_stack_v2_python_sparse | stumbleupon/botlaunch.py | cash2one/doorscenter | train | 0 |
00463ef5bf7a318bfe7bcf4ddaf69cb8dac74afb | [
"if SuperUserPermission().can():\n pre_oci_model.mark_organization_for_deletion(name)\n return ('', 204)\nraise Unauthorized()",
"if SuperUserPermission().can():\n org_data = request.get_json()\n new_name = org_data['name'] if 'name' in org_data else None\n authed_user = get_authenticated_user()\n ... | <|body_start_0|>
if SuperUserPermission().can():
pre_oci_model.mark_organization_for_deletion(name)
return ('', 204)
raise Unauthorized()
<|end_body_0|>
<|body_start_1|>
if SuperUserPermission().can():
org_data = request.get_json()
new_name = org_... | Resource for managing organizations in the system. | SuperUserOrganizationManagement | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperUserOrganizationManagement:
"""Resource for managing organizations in the system."""
def delete(self, name):
"""Deletes the specified organization."""
<|body_0|>
def put(self, name):
"""Updates information about the specified user."""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_021080 | 40,556 | permissive | [
{
"docstring": "Deletes the specified organization.",
"name": "delete",
"signature": "def delete(self, name)"
},
{
"docstring": "Updates information about the specified user.",
"name": "put",
"signature": "def put(self, name)"
}
] | 2 | null | Implement the Python class `SuperUserOrganizationManagement` described below.
Class description:
Resource for managing organizations in the system.
Method signatures and docstrings:
- def delete(self, name): Deletes the specified organization.
- def put(self, name): Updates information about the specified user. | Implement the Python class `SuperUserOrganizationManagement` described below.
Class description:
Resource for managing organizations in the system.
Method signatures and docstrings:
- def delete(self, name): Deletes the specified organization.
- def put(self, name): Updates information about the specified user.
<|sk... | e400a0c22c5f89dd35d571654b13d262b1f6e3b3 | <|skeleton|>
class SuperUserOrganizationManagement:
"""Resource for managing organizations in the system."""
def delete(self, name):
"""Deletes the specified organization."""
<|body_0|>
def put(self, name):
"""Updates information about the specified user."""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuperUserOrganizationManagement:
"""Resource for managing organizations in the system."""
def delete(self, name):
"""Deletes the specified organization."""
if SuperUserPermission().can():
pre_oci_model.mark_organization_for_deletion(name)
return ('', 204)
r... | the_stack_v2_python_sparse | endpoints/api/superuser.py | quay/quay | train | 2,363 |
941242456a627032f5e0d32e5e734e3e245ac655 | [
"vis = {(0, 0)}\nfor i in range(m):\n for j in range(n):\n if ((i - 1, j) in vis or (i, j - 1) in vis) and digit_sum(i) + digit_sum(j) <= k:\n vis.add((i, j))\nreturn len(vis)",
"from queue import Queue\nq = Queue()\nq.put((0, 0))\ns = set()\nwhile not q.empty():\n x, y = q.get()\n if (... | <|body_start_0|>
vis = {(0, 0)}
for i in range(m):
for j in range(n):
if ((i - 1, j) in vis or (i, j - 1) in vis) and digit_sum(i) + digit_sum(j) <= k:
vis.add((i, j))
return len(vis)
<|end_body_0|>
<|body_start_1|>
from queue import Queue... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
"""递推法 这里需要注意,所有的可能题解都是联通的,只需要考虑向右或者向下的情况。"""
<|body_0|>
def movingCount_2(self, m: int, n: int, k: int) -> int:
"""广度优先法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
vis = {(0, 0)}
... | stack_v2_sparse_classes_36k_train_021081 | 1,810 | no_license | [
{
"docstring": "递推法 这里需要注意,所有的可能题解都是联通的,只需要考虑向右或者向下的情况。",
"name": "movingCount",
"signature": "def movingCount(self, m: int, n: int, k: int) -> int"
},
{
"docstring": "广度优先法",
"name": "movingCount_2",
"signature": "def movingCount_2(self, m: int, n: int, k: int) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def movingCount(self, m: int, n: int, k: int) -> int: 递推法 这里需要注意,所有的可能题解都是联通的,只需要考虑向右或者向下的情况。
- def movingCount_2(self, m: int, n: int, k: int) -> int: 广度优先法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def movingCount(self, m: int, n: int, k: int) -> int: 递推法 这里需要注意,所有的可能题解都是联通的,只需要考虑向右或者向下的情况。
- def movingCount_2(self, m: int, n: int, k: int) -> int: 广度优先法
<|skeleton|>
class ... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
"""递推法 这里需要注意,所有的可能题解都是联通的,只需要考虑向右或者向下的情况。"""
<|body_0|>
def movingCount_2(self, m: int, n: int, k: int) -> int:
"""广度优先法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
"""递推法 这里需要注意,所有的可能题解都是联通的,只需要考虑向右或者向下的情况。"""
vis = {(0, 0)}
for i in range(m):
for j in range(n):
if ((i - 1, j) in vis or (i, j - 1) in vis) and digit_sum(i) + digit_sum(j) <= k:
... | the_stack_v2_python_sparse | SwordOffer/SwordOffer_13.py | EachenKuang/LeetCode | train | 28 | |
64a9dddd8ed4ca582312c8245726f95378e9db5b | [
"a = Ligne(self.coords[:4]).perimetre()\nb = Ligne(self.coords[2:]).perimetre()\nc = Ligne(self.coords[:2] + self.coords[-2:]).perimetre()\nreturn a + b + c",
"a = Ligne(self.coords[:4]).perimetre()\nb = Ligne(self.coords[2:]).perimetre()\nc = Ligne(self.coords[:2] + self.coords[-2:]).perimetre()\nds = (a + b + c... | <|body_start_0|>
a = Ligne(self.coords[:4]).perimetre()
b = Ligne(self.coords[2:]).perimetre()
c = Ligne(self.coords[:2] + self.coords[-2:]).perimetre()
return a + b + c
<|end_body_0|>
<|body_start_1|>
a = Ligne(self.coords[:4]).perimetre()
b = Ligne(self.coords[2:]).per... | Definition d'une Forme à 3 points coords : Liste des coordonnées des points de la forme (x, y) def aire() -> float def perimetre() -> float | Triangle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Triangle:
"""Definition d'une Forme à 3 points coords : Liste des coordonnées des points de la forme (x, y) def aire() -> float def perimetre() -> float"""
def perimetre(self):
"""Calcul du périmètre d'un rectangle (a + b + c)"""
<|body_0|>
def aire(self):
"""Cal... | stack_v2_sparse_classes_36k_train_021082 | 4,984 | no_license | [
{
"docstring": "Calcul du périmètre d'un rectangle (a + b + c)",
"name": "perimetre",
"signature": "def perimetre(self)"
},
{
"docstring": "Calcul de l'aire d'un rectangle s = (a + b + c) / 2 A = sqrt(s.(s-a).(s-b).(s-c))",
"name": "aire",
"signature": "def aire(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018457 | Implement the Python class `Triangle` described below.
Class description:
Definition d'une Forme à 3 points coords : Liste des coordonnées des points de la forme (x, y) def aire() -> float def perimetre() -> float
Method signatures and docstrings:
- def perimetre(self): Calcul du périmètre d'un rectangle (a + b + c)
... | Implement the Python class `Triangle` described below.
Class description:
Definition d'une Forme à 3 points coords : Liste des coordonnées des points de la forme (x, y) def aire() -> float def perimetre() -> float
Method signatures and docstrings:
- def perimetre(self): Calcul du périmètre d'un rectangle (a + b + c)
... | 80ad880298bf9f6a2f32f87ec90e43068380c7a5 | <|skeleton|>
class Triangle:
"""Definition d'une Forme à 3 points coords : Liste des coordonnées des points de la forme (x, y) def aire() -> float def perimetre() -> float"""
def perimetre(self):
"""Calcul du périmètre d'un rectangle (a + b + c)"""
<|body_0|>
def aire(self):
"""Cal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Triangle:
"""Definition d'une Forme à 3 points coords : Liste des coordonnées des points de la forme (x, y) def aire() -> float def perimetre() -> float"""
def perimetre(self):
"""Calcul du périmètre d'un rectangle (a + b + c)"""
a = Ligne(self.coords[:4]).perimetre()
b = Ligne(se... | the_stack_v2_python_sparse | formes.py | christophejacques/examples | train | 0 |
685d7cd9dd7ef5f752e1939a656ef41079cb5063 | [
"self.aws_credentials = aws_credentials\nself.azure_credentials = azure_credentials\nself.endpoint = endpoint\nself.environment = environment\nself.force_register = force_register\nself.gcp_credentials = gcp_credentials\nself.host_type = host_type\nself.nas_mount_credentials = nas_mount_credentials\nself.netapp_typ... | <|body_start_0|>
self.aws_credentials = aws_credentials
self.azure_credentials = azure_credentials
self.endpoint = endpoint
self.environment = environment
self.force_register = force_register
self.gcp_credentials = gcp_credentials
self.host_type = host_type
... | Implementation of the 'Register Protection Source Parameters.' model. Specifies the parameters required to register a Protection Source. Attributes: aws_credentials (AWSSourceCredentials): Specifies the credentials to authenticate with AWS Cloud Platform. azure_credentials (AzureSourceCredentials): Specifies the creden... | RegisterProtectionSourceParameters | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterProtectionSourceParameters:
"""Implementation of the 'Register Protection Source Parameters.' model. Specifies the parameters required to register a Protection Source. Attributes: aws_credentials (AWSSourceCredentials): Specifies the credentials to authenticate with AWS Cloud Platform. az... | stack_v2_sparse_classes_36k_train_021083 | 15,762 | permissive | [
{
"docstring": "Constructor for the RegisterProtectionSourceParameters class",
"name": "__init__",
"signature": "def __init__(self, aws_credentials=None, azure_credentials=None, endpoint=None, environment=None, force_register=None, gcp_credentials=None, host_type=None, nas_mount_credentials=None, netapp... | 2 | stack_v2_sparse_classes_30k_train_013936 | Implement the Python class `RegisterProtectionSourceParameters` described below.
Class description:
Implementation of the 'Register Protection Source Parameters.' model. Specifies the parameters required to register a Protection Source. Attributes: aws_credentials (AWSSourceCredentials): Specifies the credentials to a... | Implement the Python class `RegisterProtectionSourceParameters` described below.
Class description:
Implementation of the 'Register Protection Source Parameters.' model. Specifies the parameters required to register a Protection Source. Attributes: aws_credentials (AWSSourceCredentials): Specifies the credentials to a... | 07c5adee58810979780679065250d82b4b2cdaab | <|skeleton|>
class RegisterProtectionSourceParameters:
"""Implementation of the 'Register Protection Source Parameters.' model. Specifies the parameters required to register a Protection Source. Attributes: aws_credentials (AWSSourceCredentials): Specifies the credentials to authenticate with AWS Cloud Platform. az... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterProtectionSourceParameters:
"""Implementation of the 'Register Protection Source Parameters.' model. Specifies the parameters required to register a Protection Source. Attributes: aws_credentials (AWSSourceCredentials): Specifies the credentials to authenticate with AWS Cloud Platform. azure_credentia... | the_stack_v2_python_sparse | cohesity_management_sdk/models/register_protection_source_parameters.py | hemanshu-cohesity/management-sdk-python | train | 0 |
497a0b3a4a940f4cc816c6e49e8670020e4990f2 | [
"self.sensor = Sensor('http://127.0.0.1', '8000')\nself.pump = Pump('http://127.0.0.1', '8000')\nself.decider = Decider(50, 0.025)\nself.controller = Controller(self.sensor, self.pump, self.decider)\nself.actions = {'PUMP_IN': self.pump.PUMP_IN, 'PUMP_OUT': self.pump.PUMP_OUT, 'PUMP_OFF': self.pump.PUMP_OFF}",
"s... | <|body_start_0|>
self.sensor = Sensor('http://127.0.0.1', '8000')
self.pump = Pump('http://127.0.0.1', '8000')
self.decider = Decider(50, 0.025)
self.controller = Controller(self.sensor, self.pump, self.decider)
self.actions = {'PUMP_IN': self.pump.PUMP_IN, 'PUMP_OUT': self.pump.... | Unit tests for the Controller class. | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class."""
def setUp(self):
"""setUp() method is executed before test methods run for Controller."""
<|body_0|>
def test_controller_init(self):
"""Test the constructor for creating a new instance."""
<|body... | stack_v2_sparse_classes_36k_train_021084 | 6,467 | no_license | [
{
"docstring": "setUp() method is executed before test methods run for Controller.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the constructor for creating a new instance.",
"name": "test_controller_init",
"signature": "def test_controller_init(self)"
},
... | 4 | null | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class.
Method signatures and docstrings:
- def setUp(self): setUp() method is executed before test methods run for Controller.
- def test_controller_init(self): Test the constructor for creating a new instan... | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class.
Method signatures and docstrings:
- def setUp(self): setUp() method is executed before test methods run for Controller.
- def test_controller_init(self): Test the constructor for creating a new instan... | 263685ca90110609bfd05d621516727f8cd0028f | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class."""
def setUp(self):
"""setUp() method is executed before test methods run for Controller."""
<|body_0|>
def test_controller_init(self):
"""Test the constructor for creating a new instance."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControllerTests:
"""Unit tests for the Controller class."""
def setUp(self):
"""setUp() method is executed before test methods run for Controller."""
self.sensor = Sensor('http://127.0.0.1', '8000')
self.pump = Pump('http://127.0.0.1', '8000')
self.decider = Decider(50, 0.... | the_stack_v2_python_sparse | students/daniel_grubbs/lesson06/water-regulation/waterregulation/test.py | aurel1212/Sp2018-Online | train | 0 |
6c8aa1e28e3d4be5742fc2e108c6419469d9850d | [
"self.set_current_monitor = set_current_monitor\nself.last_monitor = None\nself.data = None\nself.widget = None",
"lock = threading.Lock()\nwith lock:\n self.data = data\n if data is None:\n self.widget.options = []\n return\n monitor_names = []\n for data in self.data:\n original... | <|body_start_0|>
self.set_current_monitor = set_current_monitor
self.last_monitor = None
self.data = None
self.widget = None
<|end_body_0|>
<|body_start_1|>
lock = threading.Lock()
with lock:
self.data = data
if data is None:
self.... | Class for creating monitor dropdown menu | MonitorDropdown | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonitorDropdown:
"""Class for creating monitor dropdown menu"""
def __init__(self, set_current_monitor):
"""Sets up MonitorDropdown menu with given update function Parameters ---------- update_plot: function function called to update plot"""
<|body_0|>
def set_data(self,... | stack_v2_sparse_classes_36k_train_021085 | 16,391 | permissive | [
{
"docstring": "Sets up MonitorDropdown menu with given update function Parameters ---------- update_plot: function function called to update plot",
"name": "__init__",
"signature": "def __init__(self, set_current_monitor)"
},
{
"docstring": "Updates the menu options given new data Parameters --... | 4 | null | Implement the Python class `MonitorDropdown` described below.
Class description:
Class for creating monitor dropdown menu
Method signatures and docstrings:
- def __init__(self, set_current_monitor): Sets up MonitorDropdown menu with given update function Parameters ---------- update_plot: function function called to ... | Implement the Python class `MonitorDropdown` described below.
Class description:
Class for creating monitor dropdown menu
Method signatures and docstrings:
- def __init__(self, set_current_monitor): Sets up MonitorDropdown menu with given update function Parameters ---------- update_plot: function function called to ... | f8e17f34377cecf11914e23cb6fb7231baeae304 | <|skeleton|>
class MonitorDropdown:
"""Class for creating monitor dropdown menu"""
def __init__(self, set_current_monitor):
"""Sets up MonitorDropdown menu with given update function Parameters ---------- update_plot: function function called to update plot"""
<|body_0|>
def set_data(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MonitorDropdown:
"""Class for creating monitor dropdown menu"""
def __init__(self, set_current_monitor):
"""Sets up MonitorDropdown menu with given update function Parameters ---------- update_plot: function function called to update plot"""
self.set_current_monitor = set_current_monitor
... | the_stack_v2_python_sparse | mcstasscript/jb_interface/plot_interface.py | PaNOSC-ViNYL/McStasScript | train | 8 |
257ebe84ec1b6ef1e5815858fde1fdf29237cd99 | [
"count = dict(Counter(arr))\nval = list(count.values())\nval.sort()\ntmp = list(set(val))\ntmp.sort()\nreturn tmp == val",
"tmp = {}\nfor i in range(len(arr)):\n if arr[i] not in tmp:\n tmp[arr[i]] = 1\n else:\n tmp[arr[i]] += 1\ntmp2 = {}\nfor i in tmp:\n if tmp[i] in tmp2:\n return... | <|body_start_0|>
count = dict(Counter(arr))
val = list(count.values())
val.sort()
tmp = list(set(val))
tmp.sort()
return tmp == val
<|end_body_0|>
<|body_start_1|>
tmp = {}
for i in range(len(arr)):
if arr[i] not in tmp:
tmp[ar... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
"""先统计个数,然后去重,看剩下的是否还与原个数一样 :param arr: :return:"""
<|body_0|>
def uniqueOccurrences2(self, arr: List[int]) -> bool:
"""两个hash。 :param arr: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_021086 | 1,094 | no_license | [
{
"docstring": "先统计个数,然后去重,看剩下的是否还与原个数一样 :param arr: :return:",
"name": "uniqueOccurrences",
"signature": "def uniqueOccurrences(self, arr: List[int]) -> bool"
},
{
"docstring": "两个hash。 :param arr: :return:",
"name": "uniqueOccurrences2",
"signature": "def uniqueOccurrences2(self, arr: ... | 2 | stack_v2_sparse_classes_30k_train_010333 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniqueOccurrences(self, arr: List[int]) -> bool: 先统计个数,然后去重,看剩下的是否还与原个数一样 :param arr: :return:
- def uniqueOccurrences2(self, arr: List[int]) -> bool: 两个hash。 :param arr: :re... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniqueOccurrences(self, arr: List[int]) -> bool: 先统计个数,然后去重,看剩下的是否还与原个数一样 :param arr: :return:
- def uniqueOccurrences2(self, arr: List[int]) -> bool: 两个hash。 :param arr: :re... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
"""先统计个数,然后去重,看剩下的是否还与原个数一样 :param arr: :return:"""
<|body_0|>
def uniqueOccurrences2(self, arr: List[int]) -> bool:
"""两个hash。 :param arr: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
"""先统计个数,然后去重,看剩下的是否还与原个数一样 :param arr: :return:"""
count = dict(Counter(arr))
val = list(count.values())
val.sort()
tmp = list(set(val))
tmp.sort()
return tmp == val
def uniqueOccurrenc... | the_stack_v2_python_sparse | 独一无二的出现次数.py | cjrzs/MyLeetCode | train | 8 | |
f79227895895befb9d6477caac884e53171e7c28 | [
"super().__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)\nself.parent = parent\nself.rfc = rfc\nself.tel = tel\nself.email = email\nself.name = name\nself.use = use\nself.initUi()",
"style = '\\n QLineEdit {\\n border-radius: 20%;\\n padding-... | <|body_start_0|>
super().__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
self.parent = parent
self.rfc = rfc
self.tel = tel
self.email = email
self.name = name
self.use = use
self.initUi()
<|end_body_0|>
<|body_start_1|>
style =... | Dialog to capture the customer data for the invoice. | InvoiceData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvoiceData:
"""Dialog to capture the customer data for the invoice."""
def __init__(self, rfc, tel, email, name, use, parent):
"""Init."""
<|body_0|>
def initUi(self):
"""Ui Setup."""
<|body_1|>
def verify(self):
"""Verify all fields are fil... | stack_v2_sparse_classes_36k_train_021087 | 27,111 | no_license | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, rfc, tel, email, name, use, parent)"
},
{
"docstring": "Ui Setup.",
"name": "initUi",
"signature": "def initUi(self)"
},
{
"docstring": "Verify all fields are filled.",
"name": "verify",
"signatu... | 5 | stack_v2_sparse_classes_30k_train_011597 | Implement the Python class `InvoiceData` described below.
Class description:
Dialog to capture the customer data for the invoice.
Method signatures and docstrings:
- def __init__(self, rfc, tel, email, name, use, parent): Init.
- def initUi(self): Ui Setup.
- def verify(self): Verify all fields are filled.
- def acce... | Implement the Python class `InvoiceData` described below.
Class description:
Dialog to capture the customer data for the invoice.
Method signatures and docstrings:
- def __init__(self, rfc, tel, email, name, use, parent): Init.
- def initUi(self): Ui Setup.
- def verify(self): Verify all fields are filled.
- def acce... | a5d18593e689123cac34af552628ed2818ca5d59 | <|skeleton|>
class InvoiceData:
"""Dialog to capture the customer data for the invoice."""
def __init__(self, rfc, tel, email, name, use, parent):
"""Init."""
<|body_0|>
def initUi(self):
"""Ui Setup."""
<|body_1|>
def verify(self):
"""Verify all fields are fil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InvoiceData:
"""Dialog to capture the customer data for the invoice."""
def __init__(self, rfc, tel, email, name, use, parent):
"""Init."""
super().__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
self.parent = parent
self.rfc = rfc
self.tel = tel... | the_stack_v2_python_sparse | Dialogs.py | edgary777/lonchepos | train | 0 |
fd8a67104292882707866ad56953ed0f4d195b49 | [
"super(RNNEncoder, self).__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)",
"initializer = tf.keras.initializers.Zeros()\nvalues ... | <|body_start_0|>
super(RNNEncoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
<|end_bod... | Class to encode for machine translation: | RNNEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""Class to encode for machine translation:"""
def __init__(self, vocab, embedding, units, batch):
"""vocab is an integer representing the size of the input vocabulary embedding integer representing the dimensionality of the vector units integer representing the number of... | stack_v2_sparse_classes_36k_train_021088 | 2,095 | no_license | [
{
"docstring": "vocab is an integer representing the size of the input vocabulary embedding integer representing the dimensionality of the vector units integer representing the number of hidden units in the RNN cell batch is an integer representing the batch size",
"name": "__init__",
"signature": "def ... | 3 | null | Implement the Python class `RNNEncoder` described below.
Class description:
Class to encode for machine translation:
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): vocab is an integer representing the size of the input vocabulary embedding integer representing the dimensionali... | Implement the Python class `RNNEncoder` described below.
Class description:
Class to encode for machine translation:
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): vocab is an integer representing the size of the input vocabulary embedding integer representing the dimensionali... | d3802fc2e552447cd5b17d1ed593aee46a8ae929 | <|skeleton|>
class RNNEncoder:
"""Class to encode for machine translation:"""
def __init__(self, vocab, embedding, units, batch):
"""vocab is an integer representing the size of the input vocabulary embedding integer representing the dimensionality of the vector units integer representing the number of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNEncoder:
"""Class to encode for machine translation:"""
def __init__(self, vocab, embedding, units, batch):
"""vocab is an integer representing the size of the input vocabulary embedding integer representing the dimensionality of the vector units integer representing the number of hidden units... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/0-rnn_encoder.py | RodrigoSierraV/holbertonschool-machine_learning | train | 0 |
e82e5be82db3255870ebe29969a056d3c8011a59 | [
"self.c2s_access_portal = c2s_access_portal\nself.ca_trusted_certificate = ca_trusted_certificate\nself.client_certificate = client_certificate\nself.client_private_key = client_private_key",
"if dictionary is None:\n return None\nc2s_access_portal = cohesity_management_sdk.models.c2s_access_portal.C2SAccessPo... | <|body_start_0|>
self.c2s_access_portal = c2s_access_portal
self.ca_trusted_certificate = ca_trusted_certificate
self.client_certificate = client_certificate
self.client_private_key = client_private_key
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return No... | Implementation of the 'C2SServerInfo' model. C2S Server Info. Specifies information required to connect to CAP to get AWS credentials. C2SAccessPortal(CAP) is AWS commercial cloud service access portal. Attributes: c2s_access_portal (C2SAccessPortal): Specifies the C2S Access Portal (CAP) which is used to get the aws c... | C2SServerInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class C2SServerInfo:
"""Implementation of the 'C2SServerInfo' model. C2S Server Info. Specifies information required to connect to CAP to get AWS credentials. C2SAccessPortal(CAP) is AWS commercial cloud service access portal. Attributes: c2s_access_portal (C2SAccessPortal): Specifies the C2S Access Po... | stack_v2_sparse_classes_36k_train_021089 | 2,925 | permissive | [
{
"docstring": "Constructor for the C2SServerInfo class",
"name": "__init__",
"signature": "def __init__(self, c2s_access_portal=None, ca_trusted_certificate=None, client_certificate=None, client_private_key=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dict... | 2 | stack_v2_sparse_classes_30k_train_010034 | Implement the Python class `C2SServerInfo` described below.
Class description:
Implementation of the 'C2SServerInfo' model. C2S Server Info. Specifies information required to connect to CAP to get AWS credentials. C2SAccessPortal(CAP) is AWS commercial cloud service access portal. Attributes: c2s_access_portal (C2SAcc... | Implement the Python class `C2SServerInfo` described below.
Class description:
Implementation of the 'C2SServerInfo' model. C2S Server Info. Specifies information required to connect to CAP to get AWS credentials. C2SAccessPortal(CAP) is AWS commercial cloud service access portal. Attributes: c2s_access_portal (C2SAcc... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class C2SServerInfo:
"""Implementation of the 'C2SServerInfo' model. C2S Server Info. Specifies information required to connect to CAP to get AWS credentials. C2SAccessPortal(CAP) is AWS commercial cloud service access portal. Attributes: c2s_access_portal (C2SAccessPortal): Specifies the C2S Access Po... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class C2SServerInfo:
"""Implementation of the 'C2SServerInfo' model. C2S Server Info. Specifies information required to connect to CAP to get AWS credentials. C2SAccessPortal(CAP) is AWS commercial cloud service access portal. Attributes: c2s_access_portal (C2SAccessPortal): Specifies the C2S Access Portal (CAP) wh... | the_stack_v2_python_sparse | cohesity_management_sdk/models/c2s_server_info.py | cohesity/management-sdk-python | train | 24 |
ffb3cf02866e62a4049bf20ebb9ce694f9be6adb | [
"deprecation('`PlayPlot` is marked as deprecated and will be removed in the near future.')\nself.data_callback = callback\nself.horizon_timesteps = horizon_timesteps\nself.plot_names = plot_names\nif plt is None:\n raise DependencyNotInstalled('matplotlib is not installed, run `pip install gym[other]`')\nnum_plo... | <|body_start_0|>
deprecation('`PlayPlot` is marked as deprecated and will be removed in the near future.')
self.data_callback = callback
self.horizon_timesteps = horizon_timesteps
self.plot_names = plot_names
if plt is None:
raise DependencyNotInstalled('matplotlib is... | Provides a callback to create live plots of arbitrary metrics when using :func:`play`. This class is instantiated with a function that accepts information about a single environment transition: - obs_t: observation before performing action - obs_tp1: observation after performing action - action: action that was execute... | PlayPlot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayPlot:
"""Provides a callback to create live plots of arbitrary metrics when using :func:`play`. This class is instantiated with a function that accepts information about a single environment transition: - obs_t: observation before performing action - obs_tp1: observation after performing acti... | stack_v2_sparse_classes_36k_train_021090 | 15,289 | permissive | [
{
"docstring": "Constructor of :class:`PlayPlot`. The function ``callback`` that is passed to this constructor should return a list of metrics that is of length ``len(plot_names)``. Args: callback: Function that computes metrics from environment transitions horizon_timesteps: The time horizon used for the live ... | 2 | stack_v2_sparse_classes_30k_train_004750 | Implement the Python class `PlayPlot` described below.
Class description:
Provides a callback to create live plots of arbitrary metrics when using :func:`play`. This class is instantiated with a function that accepts information about a single environment transition: - obs_t: observation before performing action - obs... | Implement the Python class `PlayPlot` described below.
Class description:
Provides a callback to create live plots of arbitrary metrics when using :func:`play`. This class is instantiated with a function that accepts information about a single environment transition: - obs_t: observation before performing action - obs... | 53d784eafed28d31ec41c36ebd9eee14b0dc6d41 | <|skeleton|>
class PlayPlot:
"""Provides a callback to create live plots of arbitrary metrics when using :func:`play`. This class is instantiated with a function that accepts information about a single environment transition: - obs_t: observation before performing action - obs_tp1: observation after performing acti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlayPlot:
"""Provides a callback to create live plots of arbitrary metrics when using :func:`play`. This class is instantiated with a function that accepts information about a single environment transition: - obs_t: observation before performing action - obs_tp1: observation after performing action - action: ... | the_stack_v2_python_sparse | gym/utils/play.py | thomascherickal/gym | train | 2 |
c1a7ec53d5d78103be18b6683a8c104e4bd2dcb1 | [
"try:\n import StringIO\n class_StringIO = StringIO.StringIO\nexcept Exception:\n import io\n class_StringIO = io.StringIO\nsio = class_StringIO('<foo> <bar> </foo>\\n')\ntry:\n ET.parse(sio)\nexcept Exception:\n self.ET_exc_class = sys.exc_info()[0]\nelse:\n self.ET_exc_class = Exception",
"... | <|body_start_0|>
try:
import StringIO
class_StringIO = StringIO.StringIO
except Exception:
import io
class_StringIO = io.StringIO
sio = class_StringIO('<foo> <bar> </foo>\n')
try:
ET.parse(sio)
except Exception:
... | Construct an XmlDocReader, call its readDoc(filename) method, then access the resulting DOM structure using XmlNode methods. If more than one document must be parsed, it is slightly faster to repeatedly call the readDoc method rather than constructing a new XmlDocReader each time. | XmlDocReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XmlDocReader:
"""Construct an XmlDocReader, call its readDoc(filename) method, then access the resulting DOM structure using XmlNode methods. If more than one document must be parsed, it is slightly faster to repeatedly call the readDoc method rather than constructing a new XmlDocReader each time... | stack_v2_sparse_classes_36k_train_021091 | 8,265 | no_license | [
{
"docstring": "The constructor determines the error class used by ElementTree.parse().",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Open the XML file and read its contents into a tree of XmlNode objects. XML errors raise an XmlError exception.",
"name": "readDo... | 2 | stack_v2_sparse_classes_30k_train_012150 | Implement the Python class `XmlDocReader` described below.
Class description:
Construct an XmlDocReader, call its readDoc(filename) method, then access the resulting DOM structure using XmlNode methods. If more than one document must be parsed, it is slightly faster to repeatedly call the readDoc method rather than co... | Implement the Python class `XmlDocReader` described below.
Class description:
Construct an XmlDocReader, call its readDoc(filename) method, then access the resulting DOM structure using XmlNode methods. If more than one document must be parsed, it is slightly faster to repeatedly call the readDoc method rather than co... | 2d07558737127077f97e9347d84e6ca46885b0bc | <|skeleton|>
class XmlDocReader:
"""Construct an XmlDocReader, call its readDoc(filename) method, then access the resulting DOM structure using XmlNode methods. If more than one document must be parsed, it is slightly faster to repeatedly call the readDoc method rather than constructing a new XmlDocReader each time... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XmlDocReader:
"""Construct an XmlDocReader, call its readDoc(filename) method, then access the resulting DOM structure using XmlNode methods. If more than one document must be parsed, it is slightly faster to repeatedly call the readDoc method rather than constructing a new XmlDocReader each time."""
def... | the_stack_v2_python_sparse | vvt/libvvtest/xmlwrapper.py | rrdrake/vvtools | train | 5 |
bd6afedc1074725d2f7ced87041e895aeb78ce30 | [
"if not root:\n return ''\nqueue = [root]\nres = []\nwhile queue:\n node = queue.pop(0)\n if node:\n queue.append(node.left)\n queue.append(node.right)\n res.append(str(node.val) if node else '#')\nreturn ','.join(res)",
"if not data:\n return None\nnodes = data.split(',')\nroot = Tre... | <|body_start_0|>
if not root:
return ''
queue = [root]
res = []
while queue:
node = queue.pop(0)
if node:
queue.append(node.left)
queue.append(node.right)
res.append(str(node.val) if node else '#')
re... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_021092 | 3,469 | 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 | stack_v2_sparse_classes_30k_train_009948 | 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:... | 0a34a19bb0979d58b511822782098f62cd86b25e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
queue = [root]
res = []
while queue:
node = queue.pop(0)
if node:
queue.append(node.lef... | the_stack_v2_python_sparse | Tree/L297_Serialize_Deserialize_Binary_Tree_latest.py | SimonFans/LeetCode | train | 1 | |
4674d8f45aa15b975aafc585bdbdc28224470ad6 | [
"self.socket = socket.socket()\naddress = (self.host, self.port)\nself.socket.bind(address)\nself.socket.listen(5)\nreturn Connection.setup(self)",
"assert self.poll and self.socket\nevents = True\nconnections = []\nwhile events:\n events = self.poll.poll(0)\n for fileno, event in events:\n if not fi... | <|body_start_0|>
self.socket = socket.socket()
address = (self.host, self.port)
self.socket.bind(address)
self.socket.listen(5)
return Connection.setup(self)
<|end_body_0|>
<|body_start_1|>
assert self.poll and self.socket
events = True
connections = []
... | Host | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Host:
def setup(self):
"""Create a socket that is listening to the address given previously. The host can only listen on a single port at a time."""
<|body_0|>
def accept(self):
"""If a client is trying to connect, accept the connection and return an object that can ... | stack_v2_sparse_classes_36k_train_021093 | 5,772 | no_license | [
{
"docstring": "Create a socket that is listening to the address given previously. The host can only listen on a single port at a time.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "If a client is trying to connect, accept the connection and return an object that can be us... | 2 | stack_v2_sparse_classes_30k_train_015465 | Implement the Python class `Host` described below.
Class description:
Implement the Host class.
Method signatures and docstrings:
- def setup(self): Create a socket that is listening to the address given previously. The host can only listen on a single port at a time.
- def accept(self): If a client is trying to conn... | Implement the Python class `Host` described below.
Class description:
Implement the Host class.
Method signatures and docstrings:
- def setup(self): Create a socket that is listening to the address given previously. The host can only listen on a single port at a time.
- def accept(self): If a client is trying to conn... | 4a7485044b35c73bb4ecd0c6499fe1060d338c54 | <|skeleton|>
class Host:
def setup(self):
"""Create a socket that is listening to the address given previously. The host can only listen on a single port at a time."""
<|body_0|>
def accept(self):
"""If a client is trying to connect, accept the connection and return an object that can ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Host:
def setup(self):
"""Create a socket that is listening to the address given previously. The host can only listen on a single port at a time."""
self.socket = socket.socket()
address = (self.host, self.port)
self.socket.bind(address)
self.socket.listen(5)
re... | the_stack_v2_python_sparse | network.py | kxgames/ClayPygeons | train | 0 | |
68b7e1d666c8e12f2128e3e382243f1bafa60ee0 | [
"super().__init__(dat, frame, box_size, centre, arrow_width=arrow_width, arrow_head_width=arrow_head_width, arrow_head_length=arrow_head_length)\nself.displacements = dat.getDisplacements(frame, frame + dt, *self.particles, jump=jump)\nself.vmin, self.vmax = amplogwidth(self.displacements)\ntry:\n self.vmin = np... | <|body_start_0|>
super().__init__(dat, frame, box_size, centre, arrow_width=arrow_width, arrow_head_width=arrow_head_width, arrow_head_length=arrow_head_length)
self.displacements = dat.getDisplacements(frame, frame + dt, *self.particles, jump=jump)
self.vmin, self.vmax = amplogwidth(self.displa... | Plotting class specific to 'displacement' mode. | Displacement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Displacement:
"""Plotting class specific to 'displacement' mode."""
def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_colormap_label_pad, dt=1, jump=1, label=False, **kwargs):
"""I... | stack_v2_sparse_classes_36k_train_021094 | 24,676 | permissive | [
{
"docstring": "Initialises and plots figure. Parameters ---------- dat : active_work.read.Dat Data object. frame : int Frame to render. box_size : float Length of the square box to render. centre : 2-uple like Centre of the box to render. arrow_width : float Width of the arrows. arrow_head_width : float Width ... | 2 | stack_v2_sparse_classes_30k_train_008613 | Implement the Python class `Displacement` described below.
Class description:
Plotting class specific to 'displacement' mode.
Method signatures and docstrings:
- def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_co... | Implement the Python class `Displacement` described below.
Class description:
Plotting class specific to 'displacement' mode.
Method signatures and docstrings:
- def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_co... | 99107a0d4935296b673f67469c1e2bd258954b9b | <|skeleton|>
class Displacement:
"""Plotting class specific to 'displacement' mode."""
def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_colormap_label_pad, dt=1, jump=1, label=False, **kwargs):
"""I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Displacement:
"""Plotting class specific to 'displacement' mode."""
def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_colormap_label_pad, dt=1, jump=1, label=False, **kwargs):
"""Initialises an... | the_stack_v2_python_sparse | frame.py | yketa/active_work | train | 1 |
deba7689ebafb286e71c5653f37a4f806d9bc973 | [
"if topic_prefix is None:\n topic_prefix = 'gnss'\nsuper(Gnss, self).__init__(carla_actor=carla_actor, parent=parent, topic_prefix=topic_prefix, append_role_name_topic_postfix=append_role_name_topic_postfix)",
"navsatfix_msg = NavSatFix()\nnavsatfix_msg.header = self.get_msg_header(use_parent_frame=False)\nnav... | <|body_start_0|>
if topic_prefix is None:
topic_prefix = 'gnss'
super(Gnss, self).__init__(carla_actor=carla_actor, parent=parent, topic_prefix=topic_prefix, append_role_name_topic_postfix=append_role_name_topic_postfix)
<|end_body_0|>
<|body_start_1|>
navsatfix_msg = NavSatFix()
... | Actor implementation details for gnss sensor | Gnss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gnss:
"""Actor implementation details for gnss sensor"""
def __init__(self, carla_actor, parent, topic_prefix=None, append_role_name_topic_postfix=True):
"""Constructor :param carla_actor: carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type paren... | stack_v2_sparse_classes_36k_train_021095 | 1,999 | permissive | [
{
"docstring": "Constructor :param carla_actor: carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type parent: carla_ros_bridge.Parent :param topic_prefix: the topic prefix to be used for this actor :type topic_prefix: string :param append_role_name_topic_postfix: if this flag... | 2 | null | Implement the Python class `Gnss` described below.
Class description:
Actor implementation details for gnss sensor
Method signatures and docstrings:
- def __init__(self, carla_actor, parent, topic_prefix=None, append_role_name_topic_postfix=True): Constructor :param carla_actor: carla actor object :type carla_actor: ... | Implement the Python class `Gnss` described below.
Class description:
Actor implementation details for gnss sensor
Method signatures and docstrings:
- def __init__(self, carla_actor, parent, topic_prefix=None, append_role_name_topic_postfix=True): Constructor :param carla_actor: carla actor object :type carla_actor: ... | d00602f0fc89bbfc712c1a6c9b9e11adf6ced7db | <|skeleton|>
class Gnss:
"""Actor implementation details for gnss sensor"""
def __init__(self, carla_actor, parent, topic_prefix=None, append_role_name_topic_postfix=True):
"""Constructor :param carla_actor: carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type paren... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Gnss:
"""Actor implementation details for gnss sensor"""
def __init__(self, carla_actor, parent, topic_prefix=None, append_role_name_topic_postfix=True):
"""Constructor :param carla_actor: carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type parent: carla_ros_... | the_stack_v2_python_sparse | delta_carla_ros_bridge/carla_ros_bridge/src/carla_ros_bridge/gnss.py | pparmesh/Delta-Autonomy | train | 1 |
18096e1ec1bb808a09074865108d770918b4d172 | [
"self.n = n\npath, result = ([], [])\nself.dfs(0, [], [], [], path, result)\nreturn result",
"if n == self.n:\n result.append(path)\n return\nfor j in range(self.n):\n if j not in col and n + j not in diag1 and (n - j not in diag2):\n self.dfs(n + 1, col + [j], diag1 + [n + j], diag2 + [n - j], pa... | <|body_start_0|>
self.n = n
path, result = ([], [])
self.dfs(0, [], [], [], path, result)
return result
<|end_body_0|>
<|body_start_1|>
if n == self.n:
result.append(path)
return
for j in range(self.n):
if j not in col and n + j not in... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
"""思路: dfs 每层放入一个 Q,向下递归,直到最后一层,每层都判断是否合法 col, diag1, diag2 分别用来判断 列,两个对角线是否能被攻击到 - 对角线驱去重方案: "dale diagonals": row - column = constant "hill diagonals": row + column = constant 时间复杂度:O(n!) 空间复杂度 O(n)"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_021096 | 2,281 | no_license | [
{
"docstring": "思路: dfs 每层放入一个 Q,向下递归,直到最后一层,每层都判断是否合法 col, diag1, diag2 分别用来判断 列,两个对角线是否能被攻击到 - 对角线驱去重方案: \"dale diagonals\": row - column = constant \"hill diagonals\": row + column = constant 时间复杂度:O(n!) 空间复杂度 O(n)",
"name": "solveNQueens",
"signature": "def solveNQueens(self, n: int) -> List[List[st... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solveNQueens(self, n: int) -> List[List[str]]: 思路: dfs 每层放入一个 Q,向下递归,直到最后一层,每层都判断是否合法 col, diag1, diag2 分别用来判断 列,两个对角线是否能被攻击到 - 对角线驱去重方案: "dale diagonals": row - column = con... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solveNQueens(self, n: int) -> List[List[str]]: 思路: dfs 每层放入一个 Q,向下递归,直到最后一层,每层都判断是否合法 col, diag1, diag2 分别用来判断 列,两个对角线是否能被攻击到 - 对角线驱去重方案: "dale diagonals": row - column = con... | 4994b8b19abcdbcc0bda2944350e325242fadfd1 | <|skeleton|>
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
"""思路: dfs 每层放入一个 Q,向下递归,直到最后一层,每层都判断是否合法 col, diag1, diag2 分别用来判断 列,两个对角线是否能被攻击到 - 对角线驱去重方案: "dale diagonals": row - column = constant "hill diagonals": row + column = constant 时间复杂度:O(n!) 空间复杂度 O(n)"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
"""思路: dfs 每层放入一个 Q,向下递归,直到最后一层,每层都判断是否合法 col, diag1, diag2 分别用来判断 列,两个对角线是否能被攻击到 - 对角线驱去重方案: "dale diagonals": row - column = constant "hill diagonals": row + column = constant 时间复杂度:O(n!) 空间复杂度 O(n)"""
self.n = n
path, resu... | the_stack_v2_python_sparse | Week_03/solveNQueens.py | NanZhang715/AlgorithmCHUNZHAO | train | 0 | |
dc82a425212f18d613471d911a372313e39f1d3e | [
"self.locLogFile = dataLocLogs + locLogFile\nself.framesPath = data2022 + framesFolder\nself.outputFileName = outputFileName + '.txt'\nself.outputFilePath = '/Users/beabautista/Desktop/dump/MAC/RoboticsResearch/catkin_ws/src/match_seeker/res/classifier2022Data/' + self.outputFileName\nself.logData = {}\nself.frameT... | <|body_start_0|>
self.locLogFile = dataLocLogs + locLogFile
self.framesPath = data2022 + framesFolder
self.outputFileName = outputFileName + '.txt'
self.outputFilePath = '/Users/beabautista/Desktop/dump/MAC/RoboticsResearch/catkin_ws/src/match_seeker/res/classifier2022Data/' + self.outpu... | DataLabeller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataLabeller:
def __init__(self, locLogFile, framesFolder, outputFileName):
""":param locLogFile: Name of the text file from a single data collection run created by walkAndTimestamp2022.py :param framesFolder: Name of the frames folder from a single data collection run created by collect... | stack_v2_sparse_classes_36k_train_021097 | 7,712 | no_license | [
{
"docstring": ":param locLogFile: Name of the text file from a single data collection run created by walkAndTimestamp2022.py :param framesFolder: Name of the frames folder from a single data collection run created by collectData2022.py :param outputFileName: Name of the outputted text file that labels each fra... | 6 | null | Implement the Python class `DataLabeller` described below.
Class description:
Implement the DataLabeller class.
Method signatures and docstrings:
- def __init__(self, locLogFile, framesFolder, outputFileName): :param locLogFile: Name of the text file from a single data collection run created by walkAndTimestamp2022.p... | Implement the Python class `DataLabeller` described below.
Class description:
Implement the DataLabeller class.
Method signatures and docstrings:
- def __init__(self, locLogFile, framesFolder, outputFileName): :param locLogFile: Name of the text file from a single data collection run created by walkAndTimestamp2022.p... | 97bb378a325b1639110de06b88d6e237dffc7330 | <|skeleton|>
class DataLabeller:
def __init__(self, locLogFile, framesFolder, outputFileName):
""":param locLogFile: Name of the text file from a single data collection run created by walkAndTimestamp2022.py :param framesFolder: Name of the frames folder from a single data collection run created by collect... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataLabeller:
def __init__(self, locLogFile, framesFolder, outputFileName):
""":param locLogFile: Name of the text file from a single data collection run created by walkAndTimestamp2022.py :param framesFolder: Name of the frames folder from a single data collection run created by collectData2022.py :p... | the_stack_v2_python_sparse | src/match_seeker/scripts/olri_classifier/DataLabelling2022.py | FoxRobotLab/catkin_ws | train | 6 | |
8f628d9883f132531e7589e207ab2ae7091bff3e | [
"referenced_value = value.referenced_value()\nExplorer.explore_expr(expr, referenced_value, is_child)\nreturn False",
"target_type = datatype.target()\nExplorer.explore_type(name, target_type, is_child)\nreturn False"
] | <|body_start_0|>
referenced_value = value.referenced_value()
Explorer.explore_expr(expr, referenced_value, is_child)
return False
<|end_body_0|>
<|body_start_1|>
target_type = datatype.target()
Explorer.explore_type(name, target_type, is_child)
return False
<|end_body_1|... | Internal class used to explore reference (TYPE_CODE_REF) values. | ReferenceExplorer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReferenceExplorer:
"""Internal class used to explore reference (TYPE_CODE_REF) values."""
def explore_expr(expr, value, is_child):
"""Function to explore array values. See Explorer.explore_expr for more information."""
<|body_0|>
def explore_type(name, datatype, is_child... | stack_v2_sparse_classes_36k_train_021098 | 26,692 | permissive | [
{
"docstring": "Function to explore array values. See Explorer.explore_expr for more information.",
"name": "explore_expr",
"signature": "def explore_expr(expr, value, is_child)"
},
{
"docstring": "Function to explore pointer types. See Explorer.explore_type for more information.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_021554 | Implement the Python class `ReferenceExplorer` described below.
Class description:
Internal class used to explore reference (TYPE_CODE_REF) values.
Method signatures and docstrings:
- def explore_expr(expr, value, is_child): Function to explore array values. See Explorer.explore_expr for more information.
- def explo... | Implement the Python class `ReferenceExplorer` described below.
Class description:
Internal class used to explore reference (TYPE_CODE_REF) values.
Method signatures and docstrings:
- def explore_expr(expr, value, is_child): Function to explore array values. See Explorer.explore_expr for more information.
- def explo... | b90664de0bd4c1897a9f1f5d9e360a9631d38b34 | <|skeleton|>
class ReferenceExplorer:
"""Internal class used to explore reference (TYPE_CODE_REF) values."""
def explore_expr(expr, value, is_child):
"""Function to explore array values. See Explorer.explore_expr for more information."""
<|body_0|>
def explore_type(name, datatype, is_child... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReferenceExplorer:
"""Internal class used to explore reference (TYPE_CODE_REF) values."""
def explore_expr(expr, value, is_child):
"""Function to explore array values. See Explorer.explore_expr for more information."""
referenced_value = value.referenced_value()
Explorer.explore_e... | the_stack_v2_python_sparse | toolchain/riscv/Linux/share/gdb/python/gdb/command/explore.py | bouffalolab/bl_iot_sdk | train | 244 |
9a6fa7c5100e41174a26548a9a962b1e82c30ae2 | [
"try:\n return configparser.RawConfigParser.options(self, section)\nexcept configparser.NoSectionError:\n if default is not _UNSET:\n return default\n raise",
"if section is _UNSET:\n return super().items()\ntry:\n return configparser.RawConfigParser.items(self, section)\nexcept configparser... | <|body_start_0|>
try:
return configparser.RawConfigParser.options(self, section)
except configparser.NoSectionError:
if default is not _UNSET:
return default
raise
<|end_body_0|>
<|body_start_1|>
if section is _UNSET:
return super(... | Like RawConfigParser but with some default helpers. | RawConfigParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawConfigParser:
"""Like RawConfigParser but with some default helpers."""
def options(self, section, default=_UNSET):
"""Return the options in |section|. Args: section: The section to look up. default: What to return if |section| does not exist."""
<|body_0|>
def items(... | stack_v2_sparse_classes_36k_train_021099 | 11,838 | no_license | [
{
"docstring": "Return the options in |section|. Args: section: The section to look up. default: What to return if |section| does not exist.",
"name": "options",
"signature": "def options(self, section, default=_UNSET)"
},
{
"docstring": "Return a list of (key, value) tuples for the options in |... | 2 | null | Implement the Python class `RawConfigParser` described below.
Class description:
Like RawConfigParser but with some default helpers.
Method signatures and docstrings:
- def options(self, section, default=_UNSET): Return the options in |section|. Args: section: The section to look up. default: What to return if |secti... | Implement the Python class `RawConfigParser` described below.
Class description:
Like RawConfigParser but with some default helpers.
Method signatures and docstrings:
- def options(self, section, default=_UNSET): Return the options in |section|. Args: section: The section to look up. default: What to return if |secti... | 78a61ca023cbf1a0cecfef8b97df2b274ac3a988 | <|skeleton|>
class RawConfigParser:
"""Like RawConfigParser but with some default helpers."""
def options(self, section, default=_UNSET):
"""Return the options in |section|. Args: section: The section to look up. default: What to return if |section| does not exist."""
<|body_0|>
def items(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RawConfigParser:
"""Like RawConfigParser but with some default helpers."""
def options(self, section, default=_UNSET):
"""Return the options in |section|. Args: section: The section to look up. default: What to return if |section| does not exist."""
try:
return configparser.Ra... | the_stack_v2_python_sparse | tools/repohooks/rh/config.py | ZYHGOD-1/Aosp11 | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.