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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
93f1bc4e33aad80a1f910406ec2063699ecfc4c1 | [
"self.v = [v1, v2]\nself.vLen = [len(self.v[i]) for i in range(len(self.v))]\nself.totalLen = sum(self.vLen)\nself.groupPointer = 0\nself.nPointer = 0\nself.vPointer = [0] * len(self.v)",
"while True:\n try:\n res = self.v[self.groupPointer][self.vPointer[self.groupPointer]]\n self.vPointer[self.... | <|body_start_0|>
self.v = [v1, v2]
self.vLen = [len(self.v[i]) for i in range(len(self.v))]
self.totalLen = sum(self.vLen)
self.groupPointer = 0
self.nPointer = 0
self.vPointer = [0] * len(self.v)
<|end_body_0|>
<|body_start_1|>
while True:
try:
... | ZigzagIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_36k_train_008800 | 2,383 | no_license | [
{
"docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]",
"name": "__init__",
"signature": "def __init__(self, v1, v2)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name"... | 3 | null | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | 58d5384155f481b1d1b0a7ca69566245dd779554 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
self.v = [v1, v2]
self.vLen = [len(self.v[i]) for i in range(len(self.v))]
self.totalLen = sum(self.vLen)
self.groupPointer = 0
self.nP... | the_stack_v2_python_sparse | 1-100/L281.py | k8godzilla/-Leetcode | train | 0 | |
6f1ca5c9b6bac3fe918823fe50bfc7bcecf30773 | [
"self.codec = container.yaml_codec\nself.mapper = container.mapper\nself.container = container",
"contents = copy.deepcopy(metadata)\ncontents = dict(contents)\ncontents = self.mapper.to_cloud(contents)\ncontents = self.codec.serialize(contents)\nwith self.container.create_cloud_storage() as storage:\n storage... | <|body_start_0|>
self.codec = container.yaml_codec
self.mapper = container.mapper
self.container = container
<|end_body_0|>
<|body_start_1|>
contents = copy.deepcopy(metadata)
contents = dict(contents)
contents = self.mapper.to_cloud(contents)
contents = self.cod... | CloudPortal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudPortal:
def __init__(self, container):
"""Args: container(shelf.metadata.container.Container)"""
<|body_0|>
def update(self, cloud_identifier, metadata):
"""Updates the metadata in the cloud which is the source of truth. Args: cloud_identifier(basestring): Somet... | stack_v2_sparse_classes_36k_train_008801 | 1,963 | permissive | [
{
"docstring": "Args: container(shelf.metadata.container.Container)",
"name": "__init__",
"signature": "def __init__(self, container)"
},
{
"docstring": "Updates the metadata in the cloud which is the source of truth. Args: cloud_identifier(basestring): Something that can identify the file in th... | 3 | stack_v2_sparse_classes_30k_train_012279 | Implement the Python class `CloudPortal` described below.
Class description:
Implement the CloudPortal class.
Method signatures and docstrings:
- def __init__(self, container): Args: container(shelf.metadata.container.Container)
- def update(self, cloud_identifier, metadata): Updates the metadata in the cloud which i... | Implement the Python class `CloudPortal` described below.
Class description:
Implement the CloudPortal class.
Method signatures and docstrings:
- def __init__(self, container): Args: container(shelf.metadata.container.Container)
- def update(self, cloud_identifier, metadata): Updates the metadata in the cloud which i... | ea59703082402ad3b6454482f0487418295fbd19 | <|skeleton|>
class CloudPortal:
def __init__(self, container):
"""Args: container(shelf.metadata.container.Container)"""
<|body_0|>
def update(self, cloud_identifier, metadata):
"""Updates the metadata in the cloud which is the source of truth. Args: cloud_identifier(basestring): Somet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloudPortal:
def __init__(self, container):
"""Args: container(shelf.metadata.container.Container)"""
self.codec = container.yaml_codec
self.mapper = container.mapper
self.container = container
def update(self, cloud_identifier, metadata):
"""Updates the metadata i... | the_stack_v2_python_sparse | shelf/metadata/cloud_portal.py | bfilipov/shelf | train | 0 | |
0c4852538043852e9c5432e29ec5190745eee6ec | [
"auth_token = cache.get(CSS_AUTH_TOKEN)\nif auth_token is not None:\n return auth_token\nurl = Config.CSS_TOKEN_URL\ndata = {'grant_type': 'client_credentials'}\nauth = (Config.CSS_CLIENT_ID, Config.CSS_CLIENT_SECRET)\nresp = requests.post(url, data=data, auth=auth)\ntry:\n resp_data = resp.json()\nexcept Val... | <|body_start_0|>
auth_token = cache.get(CSS_AUTH_TOKEN)
if auth_token is not None:
return auth_token
url = Config.CSS_TOKEN_URL
data = {'grant_type': 'client_credentials'}
auth = (Config.CSS_CLIENT_ID, Config.CSS_CLIENT_SECRET)
resp = requests.post(url, data=d... | Service wrapper for CSS Keycloak Gold SSO API documentation: https://api.loginproxy.gov.bc.ca/openapi/swagger#/ Manage: https://bcgov.github.io/sso-requests/ | CSSService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSSService:
"""Service wrapper for CSS Keycloak Gold SSO API documentation: https://api.loginproxy.gov.bc.ca/openapi/swagger#/ Manage: https://bcgov.github.io/sso-requests/"""
def get_css_auth_token():
"""Gets access token required for all requests"""
<|body_0|>
def get_... | stack_v2_sparse_classes_36k_train_008802 | 2,854 | permissive | [
{
"docstring": "Gets access token required for all requests",
"name": "get_css_auth_token",
"signature": "def get_css_auth_token()"
},
{
"docstring": "Get a list of emails belonging to all kc users with given rolename in core :param rolename: The keycloak role name (str) :return: list",
"nam... | 2 | null | Implement the Python class `CSSService` described below.
Class description:
Service wrapper for CSS Keycloak Gold SSO API documentation: https://api.loginproxy.gov.bc.ca/openapi/swagger#/ Manage: https://bcgov.github.io/sso-requests/
Method signatures and docstrings:
- def get_css_auth_token(): Gets access token requ... | Implement the Python class `CSSService` described below.
Class description:
Service wrapper for CSS Keycloak Gold SSO API documentation: https://api.loginproxy.gov.bc.ca/openapi/swagger#/ Manage: https://bcgov.github.io/sso-requests/
Method signatures and docstrings:
- def get_css_auth_token(): Gets access token requ... | 60277f4d71f77857e40587307a2b2adb11575850 | <|skeleton|>
class CSSService:
"""Service wrapper for CSS Keycloak Gold SSO API documentation: https://api.loginproxy.gov.bc.ca/openapi/swagger#/ Manage: https://bcgov.github.io/sso-requests/"""
def get_css_auth_token():
"""Gets access token required for all requests"""
<|body_0|>
def get_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CSSService:
"""Service wrapper for CSS Keycloak Gold SSO API documentation: https://api.loginproxy.gov.bc.ca/openapi/swagger#/ Manage: https://bcgov.github.io/sso-requests/"""
def get_css_auth_token():
"""Gets access token required for all requests"""
auth_token = cache.get(CSS_AUTH_TOKEN... | the_stack_v2_python_sparse | services/core-api/app/api/services/css_sso_service.py | bcgov/mds | train | 29 |
fc44948c5ca5a5c4f6eaa43a61800feef89146df | [
"[self.X, self.Y] = np.meshgrid(np.linspace(-1, 1, image_size), np.linspace(-1, 1, image_size))\nself.proj_domain = np.linspace(-1, 1, sample_size)\nself.f_scale = abs(np.fft.fftshift(np.linspace(-1, 1, sample_size + 1)[0:-1]))",
"filtered_data = np.fft.ifft(np.fft.fft(data) * self.f_scale).real\nresult = np.inte... | <|body_start_0|>
[self.X, self.Y] = np.meshgrid(np.linspace(-1, 1, image_size), np.linspace(-1, 1, image_size))
self.proj_domain = np.linspace(-1, 1, sample_size)
self.f_scale = abs(np.fft.fftshift(np.linspace(-1, 1, sample_size + 1)[0:-1]))
<|end_body_0|>
<|body_start_1|>
filtered_data... | A class to transform a line of attenuated data into a back-projected image. Construct on the number of data points in a line of data and the number of pixels in the resulting square image. This precomputes the back-projection operator. Once constructed, call the transform method on a line of attenuated data and the ang... | data_transformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class data_transformer:
"""A class to transform a line of attenuated data into a back-projected image. Construct on the number of data points in a line of data and the number of pixels in the resulting square image. This precomputes the back-projection operator. Once constructed, call the transform met... | stack_v2_sparse_classes_36k_train_008803 | 1,795 | no_license | [
{
"docstring": "Perform the required precomputation for the back-projection step.",
"name": "__init__",
"signature": "def __init__(self, sample_size, image_size)"
},
{
"docstring": "Transform a data line taken at an angle phi to its back-projected image. Input: data, an array of sample_size valu... | 2 | null | Implement the Python class `data_transformer` described below.
Class description:
A class to transform a line of attenuated data into a back-projected image. Construct on the number of data points in a line of data and the number of pixels in the resulting square image. This precomputes the back-projection operator. O... | Implement the Python class `data_transformer` described below.
Class description:
A class to transform a line of attenuated data into a back-projected image. Construct on the number of data points in a line of data and the number of pixels in the resulting square image. This precomputes the back-projection operator. O... | e9b97cdaa2917f42922610006b6e43073b4ae996 | <|skeleton|>
class data_transformer:
"""A class to transform a line of attenuated data into a back-projected image. Construct on the number of data points in a line of data and the number of pixels in the resulting square image. This precomputes the back-projection operator. Once constructed, call the transform met... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class data_transformer:
"""A class to transform a line of attenuated data into a back-projected image. Construct on the number of data points in a line of data and the number of pixels in the resulting square image. This precomputes the back-projection operator. Once constructed, call the transform method on a line... | the_stack_v2_python_sparse | Big Data/P2serial.py | anupamurali/Homework- | train | 0 |
aa4167cac8f72de6457d8e864e9428eb1228c3c1 | [
"self.times = times\nself.winners = []\nbest = 0\nvotes = Counter()\nwinner = 0\nfor p in persons:\n votes[p] += 1\n if votes[p] >= best:\n best = votes[p]\n winner = p\n self.winners.append(winner)",
"a = 0\nb = len(self.winners)\nwhile a + 1 < b:\n c = (a + b) // 2\n if self.times[c... | <|body_start_0|>
self.times = times
self.winners = []
best = 0
votes = Counter()
winner = 0
for p in persons:
votes[p] += 1
if votes[p] >= best:
best = votes[p]
winner = p
self.winners.append(winner)
<|en... | TopVotedCandidate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.times = times
self.winne... | stack_v2_sparse_classes_36k_train_008804 | 903 | no_license | [
{
"docstring": ":type persons: List[int] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, persons, times)"
},
{
"docstring": ":type t: int :rtype: int",
"name": "q",
"signature": "def q(self, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014523 | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int
<|skeleton|>
class TopVotedCandi... | 5ba5ea8ae375a116faef385bf6f31c75baad9c57 | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
self.times = times
self.winners = []
best = 0
votes = Counter()
winner = 0
for p in persons:
votes[p] += 1
if votes[p] >=... | the_stack_v2_python_sparse | 103-4 在线选举/836ms.py | jimzh580/Leetcode-Weekly-Contest | train | 0 | |
bc0904f0f7c6f8dbd4f3e3050d676123aa63fec8 | [
"group = Group.objects.get(name='个人权限')\ncls._assign_group_permissions(group, user, instance)\nrelated_department = user.department\nwhile related_department:\n name_prefix = f'{related_department.name}-{related_department.raw_department_id}-'\n for group in Group.objects.filter(name__startswith=name_prefix):... | <|body_start_0|>
group = Group.objects.get(name='个人权限')
cls._assign_group_permissions(group, user, instance)
related_department = user.department
while related_department:
name_prefix = f'{related_department.name}-{related_department.raw_department_id}-'
for group... | Provide services for Permissons. | PermissionService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermissionService:
"""Provide services for Permissons."""
def assign_object_permissions(cls, user=None, instance=None):
"""The function is used to provide permissions for releated user when an object is created (a teacher create a tranning record for exmaple). Parameters ---------- u... | stack_v2_sparse_classes_36k_train_008805 | 5,697 | no_license | [
{
"docstring": "The function is used to provide permissions for releated user when an object is created (a teacher create a tranning record for exmaple). Parameters ---------- user: User the current user who create the object. instance: Model a model instance Returns ------- None",
"name": "assign_object_pe... | 2 | null | Implement the Python class `PermissionService` described below.
Class description:
Provide services for Permissons.
Method signatures and docstrings:
- def assign_object_permissions(cls, user=None, instance=None): The function is used to provide permissions for releated user when an object is created (a teacher creat... | Implement the Python class `PermissionService` described below.
Class description:
Provide services for Permissons.
Method signatures and docstrings:
- def assign_object_permissions(cls, user=None, instance=None): The function is used to provide permissions for releated user when an object is created (a teacher creat... | 48cccddbe8347167cb6120a1cd7d61f9fc57cc7c | <|skeleton|>
class PermissionService:
"""Provide services for Permissons."""
def assign_object_permissions(cls, user=None, instance=None):
"""The function is used to provide permissions for releated user when an object is created (a teacher create a tranning record for exmaple). Parameters ---------- u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PermissionService:
"""Provide services for Permissons."""
def assign_object_permissions(cls, user=None, instance=None):
"""The function is used to provide permissions for releated user when an object is created (a teacher create a tranning record for exmaple). Parameters ---------- user: User the... | the_stack_v2_python_sparse | auth/services.py | DLUT-SIE/TMSFTT-BE | train | 1 |
39d06566bba13e9ac609eb50f1a06ca810181e0a | [
"super(MCDCNNClassifier, self).__init__(model_name=model_name, model_save_directory=model_save_directory)\nself.verbose = verbose\nself._is_fitted = False\nself.classes_ = None\nself.nb_classes = -1\nself.input_shape = None\nself.model = None\nself.history = None\nself.nb_epochs = nb_epochs\nself.batch_size = batch... | <|body_start_0|>
super(MCDCNNClassifier, self).__init__(model_name=model_name, model_save_directory=model_save_directory)
self.verbose = verbose
self._is_fitted = False
self.classes_ = None
self.nb_classes = -1
self.input_shape = None
self.model = None
sel... | Multi Channel Deep Convolutional Neural Network (MCDCNN). Adapted from the implementation from Fawaz et. al https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/mcdcnn.py Network originally defined in: @inproceedings{zheng2014time, title={Time series classification using multi-channels deep convolutional neural n... | MCDCNNClassifier | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MCDCNNClassifier:
"""Multi Channel Deep Convolutional Neural Network (MCDCNN). Adapted from the implementation from Fawaz et. al https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/mcdcnn.py Network originally defined in: @inproceedings{zheng2014time, title={Time series classification usin... | stack_v2_sparse_classes_36k_train_008806 | 7,939 | permissive | [
{
"docstring": ":param nb_epochs: int, the number of epochs to train the model :param batch_size: int, the number of samples per gradient update. :param kernel_size: int, specifying the length of the 1D convolution window :param pool_size: int, size of the max pooling windows :param filter_sizes: int, array of ... | 4 | stack_v2_sparse_classes_30k_train_017900 | Implement the Python class `MCDCNNClassifier` described below.
Class description:
Multi Channel Deep Convolutional Neural Network (MCDCNN). Adapted from the implementation from Fawaz et. al https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/mcdcnn.py Network originally defined in: @inproceedings{zheng2014time,... | Implement the Python class `MCDCNNClassifier` described below.
Class description:
Multi Channel Deep Convolutional Neural Network (MCDCNN). Adapted from the implementation from Fawaz et. al https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/mcdcnn.py Network originally defined in: @inproceedings{zheng2014time,... | b565b7499f58f43da7314f1bf26eccce94e88134 | <|skeleton|>
class MCDCNNClassifier:
"""Multi Channel Deep Convolutional Neural Network (MCDCNN). Adapted from the implementation from Fawaz et. al https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/mcdcnn.py Network originally defined in: @inproceedings{zheng2014time, title={Time series classification usin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MCDCNNClassifier:
"""Multi Channel Deep Convolutional Neural Network (MCDCNN). Adapted from the implementation from Fawaz et. al https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/mcdcnn.py Network originally defined in: @inproceedings{zheng2014time, title={Time series classification using multi-chann... | the_stack_v2_python_sparse | sktime_dl/classification/_mcdcnn.py | sktime/sktime-dl | train | 586 |
2e0879b551ec84aa23f85763be8a9c0e71cd4093 | [
"def preorder(node):\n if node is None:\n arr.append(None)\n else:\n arr.append(node.val)\n preorder(node.left)\n preorder(node.right)\narr = []\npreorder(root)\nstr_arr = [str(x) if x is not None else '$' for x in arr]\nserial = ','.join(str_arr)\nreturn serial",
"str_arr = data... | <|body_start_0|>
def preorder(node):
if node is None:
arr.append(None)
else:
arr.append(node.val)
preorder(node.left)
preorder(node.right)
arr = []
preorder(root)
str_arr = [str(x) if x is not None el... | 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_008807 | 3,000 | 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:... | c93c1897c5160a5bdf8e9e6dfa9ff746665565ec | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def preorder(node):
if node is None:
arr.append(None)
else:
arr.append(node.val)
preorder(node.left)
... | the_stack_v2_python_sparse | LeetCodeSolutions/297.serialize-and-deserialize-binary-tree.py | ckidckidckid/leetcode | train | 0 | |
dfa60c630297b0f7eb93e02f0cb2da1cb5d28f2d | [
"super(CraySdbProc, self).__init__(*args, **kwargs)\nself.subprocess_cmd = ['xtdb2proc', '-f', '-']\nself.key_order = []\nself.load()",
"repr_result = ''\nfor _, record in self.items():\n line = []\n for key in self.key_order:\n try:\n val = record[key]\n except KeyError:\n ... | <|body_start_0|>
super(CraySdbProc, self).__init__(*args, **kwargs)
self.subprocess_cmd = ['xtdb2proc', '-f', '-']
self.key_order = []
self.load()
<|end_body_0|>
<|body_start_1|>
repr_result = ''
for _, record in self.items():
line = []
for key in... | Dictionary subclass that self-populates with Cray SDB data. Presents certain views of the Cray Service Database (SDB) as a dictionary-like object through the Cray SDB CLI. | CraySdbProc | [
"BSD-3-Clause-LBNL",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CraySdbProc:
"""Dictionary subclass that self-populates with Cray SDB data. Presents certain views of the Cray Service Database (SDB) as a dictionary-like object through the Cray SDB CLI."""
def __init__(self, *args, **kwargs):
"""Load the processor configuration table from the SDB. ... | stack_v2_sparse_classes_36k_train_008808 | 3,380 | permissive | [
{
"docstring": "Load the processor configuration table from the SDB. Args: *args: Passed to tokio.connectors.common.SubprocessOutputDict **kwargs: Passed to tokio.connectors.common.SubprocessOutputDict",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Se... | 3 | null | Implement the Python class `CraySdbProc` described below.
Class description:
Dictionary subclass that self-populates with Cray SDB data. Presents certain views of the Cray Service Database (SDB) as a dictionary-like object through the Cray SDB CLI.
Method signatures and docstrings:
- def __init__(self, *args, **kwarg... | Implement the Python class `CraySdbProc` described below.
Class description:
Dictionary subclass that self-populates with Cray SDB data. Presents certain views of the Cray Service Database (SDB) as a dictionary-like object through the Cray SDB CLI.
Method signatures and docstrings:
- def __init__(self, *args, **kwarg... | 9e2f2f08742281c4550bf03d70fc96d8f02ea92b | <|skeleton|>
class CraySdbProc:
"""Dictionary subclass that self-populates with Cray SDB data. Presents certain views of the Cray Service Database (SDB) as a dictionary-like object through the Cray SDB CLI."""
def __init__(self, *args, **kwargs):
"""Load the processor configuration table from the SDB. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CraySdbProc:
"""Dictionary subclass that self-populates with Cray SDB data. Presents certain views of the Cray Service Database (SDB) as a dictionary-like object through the Cray SDB CLI."""
def __init__(self, *args, **kwargs):
"""Load the processor configuration table from the SDB. Args: *args: ... | the_stack_v2_python_sparse | tokio/connectors/craysdb.py | NERSC/pytokio | train | 25 |
25eac8896126e6737aa3b8b420a59ca6312c41cd | [
"trainable_args = set()\nfor idx, arg in enumerate(args):\n if getattr(arg, 'requires_grad', False):\n trainable_args.add(idx)\nqnode.set_trainable_args(trainable_args)",
"ctx.args = args_to_numpy(input_)\nctx.kwargs = kwargs_to_numpy(input_kwargs)\nctx.save_for_backward(*input_)\n_TorchQNode.set_traina... | <|body_start_0|>
trainable_args = set()
for idx, arg in enumerate(args):
if getattr(arg, 'requires_grad', False):
trainable_args.add(idx)
qnode.set_trainable_args(trainable_args)
<|end_body_0|>
<|body_start_1|>
ctx.args = args_to_numpy(input_)
ctx.kwa... | The TorchQNode | _TorchQNode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TorchQNode:
"""The TorchQNode"""
def set_trainable(args):
"""Given input arguments to the TorchQNode, determine which arguments are trainable and which aren't. Currently, all arguments are assumed to be nondifferentiable by default, unless the ``torch.tensor`` attribute ``requires_g... | stack_v2_sparse_classes_36k_train_008809 | 10,582 | permissive | [
{
"docstring": "Given input arguments to the TorchQNode, determine which arguments are trainable and which aren't. Currently, all arguments are assumed to be nondifferentiable by default, unless the ``torch.tensor`` attribute ``requires_grad`` is set to True. This method calls the underlying :meth:`set_trainabl... | 3 | null | Implement the Python class `_TorchQNode` described below.
Class description:
The TorchQNode
Method signatures and docstrings:
- def set_trainable(args): Given input arguments to the TorchQNode, determine which arguments are trainable and which aren't. Currently, all arguments are assumed to be nondifferentiable by de... | Implement the Python class `_TorchQNode` described below.
Class description:
The TorchQNode
Method signatures and docstrings:
- def set_trainable(args): Given input arguments to the TorchQNode, determine which arguments are trainable and which aren't. Currently, all arguments are assumed to be nondifferentiable by de... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class _TorchQNode:
"""The TorchQNode"""
def set_trainable(args):
"""Given input arguments to the TorchQNode, determine which arguments are trainable and which aren't. Currently, all arguments are assumed to be nondifferentiable by default, unless the ``torch.tensor`` attribute ``requires_g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _TorchQNode:
"""The TorchQNode"""
def set_trainable(args):
"""Given input arguments to the TorchQNode, determine which arguments are trainable and which aren't. Currently, all arguments are assumed to be nondifferentiable by default, unless the ``torch.tensor`` attribute ``requires_grad`` is set ... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits_v02/pennylane/pennylane#709/after/pennylane>interfaces>torch.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
6727a87e8e7c72b8498e2ef9ed244f7a3c059899 | [
"self.stack = []\nif root:\n if root.right:\n self.stack.append(root.right)\n self.stack.append(root.val)\n if root.left:\n self.stack.append(root.left)",
"if self.stack:\n if isinstance(self.stack[-1], int):\n return self.stack.pop()\n else:\n while self.stack:\n ... | <|body_start_0|>
self.stack = []
if root:
if root.right:
self.stack.append(root.right)
self.stack.append(root.val)
if root.left:
self.stack.append(root.left)
<|end_body_0|>
<|body_start_1|>
if self.stack:
if isinsta... | BSTIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def next(self):
"""@return the next smallest number :rtype: int"""
<|body_1|>
def hasNext(self):
"""@return whether we have a next smallest number :rtype: bool"""
... | stack_v2_sparse_classes_36k_train_008810 | 1,641 | no_license | [
{
"docstring": ":type root: TreeNode",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": "@return the next smallest number :rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": "@return whether we have a next smallest number :rt... | 3 | stack_v2_sparse_classes_30k_train_014342 | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def next(self): @return the next smallest number :rtype: int
- def hasNext(self): @return whether we have a next smallest n... | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def next(self): @return the next smallest number :rtype: int
- def hasNext(self): @return whether we have a next smallest n... | 1cb183a326a0612a5cd941778500a8265e1d7255 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def next(self):
"""@return the next smallest number :rtype: int"""
<|body_1|>
def hasNext(self):
"""@return whether we have a next smallest number :rtype: bool"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
self.stack = []
if root:
if root.right:
self.stack.append(root.right)
self.stack.append(root.val)
if root.left:
self.stack.append(root.left)
def ne... | the_stack_v2_python_sparse | LeetCode/BSTIterator.py | gavinz0228/AlgoPractice | train | 1 | |
edebe8b06ffadbb174af16214be96a8534947a94 | [
"if project == 'CMIP5':\n required = [{'short_name': 'cVeg', 'mip': 'Lmon'}, {'short_name': 'cSoil', 'mip': 'Lmon'}]\nelif project == 'CMIP6':\n required = [{'short_name': 'cVeg', 'mip': 'Lmon'}, {'short_name': 'cSoil', 'mip': 'Emon'}]\nreturn required",
"try:\n c_soil_cube = cubes.extract_cube(Constrain... | <|body_start_0|>
if project == 'CMIP5':
required = [{'short_name': 'cVeg', 'mip': 'Lmon'}, {'short_name': 'cSoil', 'mip': 'Lmon'}]
elif project == 'CMIP6':
required = [{'short_name': 'cVeg', 'mip': 'Lmon'}, {'short_name': 'cSoil', 'mip': 'Emon'}]
return required
<|end_bod... | Derivation of variable `ctotal`. | DerivedVariable | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DerivedVariable:
"""Derivation of variable `ctotal`."""
def required(project):
"""Declare the variables needed for derivation."""
<|body_0|>
def calculate(cubes):
"""Compute total ecosystem carbon storage."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_008811 | 1,931 | permissive | [
{
"docstring": "Declare the variables needed for derivation.",
"name": "required",
"signature": "def required(project)"
},
{
"docstring": "Compute total ecosystem carbon storage.",
"name": "calculate",
"signature": "def calculate(cubes)"
}
] | 2 | null | Implement the Python class `DerivedVariable` described below.
Class description:
Derivation of variable `ctotal`.
Method signatures and docstrings:
- def required(project): Declare the variables needed for derivation.
- def calculate(cubes): Compute total ecosystem carbon storage. | Implement the Python class `DerivedVariable` described below.
Class description:
Derivation of variable `ctotal`.
Method signatures and docstrings:
- def required(project): Declare the variables needed for derivation.
- def calculate(cubes): Compute total ecosystem carbon storage.
<|skeleton|>
class DerivedVariable:... | d5187438fea2928644cb53ecb26c6adb1e4cc947 | <|skeleton|>
class DerivedVariable:
"""Derivation of variable `ctotal`."""
def required(project):
"""Declare the variables needed for derivation."""
<|body_0|>
def calculate(cubes):
"""Compute total ecosystem carbon storage."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DerivedVariable:
"""Derivation of variable `ctotal`."""
def required(project):
"""Declare the variables needed for derivation."""
if project == 'CMIP5':
required = [{'short_name': 'cVeg', 'mip': 'Lmon'}, {'short_name': 'cSoil', 'mip': 'Lmon'}]
elif project == 'CMIP6':
... | the_stack_v2_python_sparse | esmvalcore/preprocessor/_derive/ctotal.py | ESMValGroup/ESMValCore | train | 41 |
2fc4e9f9006e308dff4c92bdb9e6acef78837ec9 | [
"self.d = collections.defaultdict(int)\nfor i, x in enumerate(sentences):\n self.d[x] = times[i]\nself.word = ''\nself.top_size = 3",
"if c == '#':\n self.d[self.word] += 1\n self.word = ''\n return []\nself.word += c\nh = []\nfor w, t in self.d.items():\n if w.startswith(self.word):\n heapq... | <|body_start_0|>
self.d = collections.defaultdict(int)
for i, x in enumerate(sentences):
self.d[x] = times[i]
self.word = ''
self.top_size = 3
<|end_body_0|>
<|body_start_1|>
if c == '#':
self.d[self.word] += 1
self.word = ''
retur... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.d = collections.d... | stack_v2_sparse_classes_36k_train_008812 | 3,528 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | null | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | 6aaf58b1e1170a994affd6330d90b89aaaf582d9 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
self.d = collections.defaultdict(int)
for i, x in enumerate(sentences):
self.d[x] = times[i]
self.word = ''
self.top_size = 3
def input(sel... | the_stack_v2_python_sparse | Python/642.py | skywhat/leetcode | train | 82 | |
ef8f4b0d8ee8e4f03689254e92044c3c5f191c09 | [
"def makeTree(s_i, e_i, t_i):\n st = self.seg_tree\n if s_i == e_i:\n st[t_i] = nums[s_i]\n return st[t_i]\n mid = s_i + (e_i - s_i) // 2\n st[t_i] = makeTree(s_i, mid, 2 * t_i + 1) + makeTree(mid + 1, e_i, 2 * t_i + 2)\n return st[t_i]\nif nums:\n tree_length = 2 * 2 ** int(math.cei... | <|body_start_0|>
def makeTree(s_i, e_i, t_i):
st = self.seg_tree
if s_i == e_i:
st[t_i] = nums[s_i]
return st[t_i]
mid = s_i + (e_i - s_i) // 2
st[t_i] = makeTree(s_i, mid, 2 * t_i + 1) + makeTree(mid + 1, e_i, 2 * t_i + 2)
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: int"""
<|body_1|>
def sumRange(self, i, j):
"""sum of elements nums[i... | stack_v2_sparse_classes_36k_train_008813 | 2,578 | no_license | [
{
"docstring": "initialize your data structure here. :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: int",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": "sum o... | 3 | stack_v2_sparse_classes_30k_train_017619 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: int
- def sumRange(self, i, j... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: int
- def sumRange(self, i, j... | ca7c940d3d2824daaf75011629aa167e0c3b3f7b | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: int"""
<|body_1|>
def sumRange(self, i, j):
"""sum of elements nums[i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
def makeTree(s_i, e_i, t_i):
st = self.seg_tree
if s_i == e_i:
st[t_i] = nums[s_i]
return st[t_i]
mid = s_i + (e_i - s_i) // ... | the_stack_v2_python_sparse | sum_range_update.py | asantinc/practice_algos | train | 0 | |
f0f80f3716b3efd0a35fd3914efbf09ed4d9e0d2 | [
"self.grid = grid\nself.bandwidth = bandwidth\nsuper(KDE_Block, self).__init__(**kwargs)",
"from sklearn.neighbors import KernelDensity\nkde = KernelDensity(bandwidth=self.bandwidth, **kwargs)\nkde.fit(self.coord.flatten()[:, np.newaxis])\nlog_pdf = kde.score_samples(self.grid[:, np.newaxis])\npdf = np.exp(log_pd... | <|body_start_0|>
self.grid = grid
self.bandwidth = bandwidth
super(KDE_Block, self).__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
from sklearn.neighbors import KernelDensity
kde = KernelDensity(bandwidth=self.bandwidth, **kwargs)
kde.fit(self.coord.flatten()[:, np.n... | Independent block of analysis for probability density function using a kernel density estimate | KDE_Block | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KDE_Block:
"""Independent block of analysis for probability density function using a kernel density estimate"""
def __init__(self, grid, bandwidth, **kwargs):
"""Initializes block of analysis **Arguments:** :*grid*: Grid on which to calculate pdf :*bandwidth*: Kernel bandwidth"""
... | stack_v2_sparse_classes_36k_train_008814 | 28,607 | permissive | [
{
"docstring": "Initializes block of analysis **Arguments:** :*grid*: Grid on which to calculate pdf :*bandwidth*: Kernel bandwidth",
"name": "__init__",
"signature": "def __init__(self, grid, bandwidth, **kwargs)"
},
{
"docstring": "Runs block of analysis",
"name": "__call__",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_000509 | Implement the Python class `KDE_Block` described below.
Class description:
Independent block of analysis for probability density function using a kernel density estimate
Method signatures and docstrings:
- def __init__(self, grid, bandwidth, **kwargs): Initializes block of analysis **Arguments:** :*grid*: Grid on whi... | Implement the Python class `KDE_Block` described below.
Class description:
Independent block of analysis for probability density function using a kernel density estimate
Method signatures and docstrings:
- def __init__(self, grid, bandwidth, **kwargs): Initializes block of analysis **Arguments:** :*grid*: Grid on whi... | 9e86e996ed7958a348012c053fa957d94729be8a | <|skeleton|>
class KDE_Block:
"""Independent block of analysis for probability density function using a kernel density estimate"""
def __init__(self, grid, bandwidth, **kwargs):
"""Initializes block of analysis **Arguments:** :*grid*: Grid on which to calculate pdf :*bandwidth*: Kernel bandwidth"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KDE_Block:
"""Independent block of analysis for probability density function using a kernel density estimate"""
def __init__(self, grid, bandwidth, **kwargs):
"""Initializes block of analysis **Arguments:** :*grid*: Grid on which to calculate pdf :*bandwidth*: Kernel bandwidth"""
self.gri... | the_stack_v2_python_sparse | secondary/pdist.py | KarlTDebiec/MDclt | train | 0 |
13b2b828ed1db2879c251acad926e256ef46f702 | [
"self.timeout = scr_env.param.get('SCR_WATCHDOG_TIMEOUT')\nself.timeout_pfs = scr_env.param.get('SCR_WATCHDOG_TIMEOUT_PFS')\nif self.timeout is not None and self.timeout_pfs is not None:\n self.timeout = int(self.timeout)\n self.timeout_pfs = int(self.timeout_pfs)\n self.launcher = scr_env.launcher\n se... | <|body_start_0|>
self.timeout = scr_env.param.get('SCR_WATCHDOG_TIMEOUT')
self.timeout_pfs = scr_env.param.get('SCR_WATCHDOG_TIMEOUT_PFS')
if self.timeout is not None and self.timeout_pfs is not None:
self.timeout = int(self.timeout)
self.timeout_pfs = int(self.timeout_pf... | This class attempts to detect hanging applications in order to avoid wasting allocations Use of the SCR_Watchdog requires 3 configuration variables to be set: SCR_WATCHDOG=1 The watchdog must be enabled (set to '1') We must also have an expected time (in seconds) to check for existence of checkpoint files. For example:... | SCR_Watchdog | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SCR_Watchdog:
"""This class attempts to detect hanging applications in order to avoid wasting allocations Use of the SCR_Watchdog requires 3 configuration variables to be set: SCR_WATCHDOG=1 The watchdog must be enabled (set to '1') We must also have an expected time (in seconds) to check for exi... | stack_v2_sparse_classes_36k_train_008815 | 4,737 | permissive | [
{
"docstring": "The SCR_Watchdog class is instantiated once, before any jobstep is ever launched, if SCR_Watchdog is enabled. Set timeout values from the environment. Copy the reference to the Joblauncher from the SCR_Env class. Instantiate an instance of SCRFlushFile using the provided prefix for later checkin... | 3 | stack_v2_sparse_classes_30k_train_009797 | Implement the Python class `SCR_Watchdog` described below.
Class description:
This class attempts to detect hanging applications in order to avoid wasting allocations Use of the SCR_Watchdog requires 3 configuration variables to be set: SCR_WATCHDOG=1 The watchdog must be enabled (set to '1') We must also have an expe... | Implement the Python class `SCR_Watchdog` described below.
Class description:
This class attempts to detect hanging applications in order to avoid wasting allocations Use of the SCR_Watchdog requires 3 configuration variables to be set: SCR_WATCHDOG=1 The watchdog must be enabled (set to '1') We must also have an expe... | 1d78ff0bccd02a9443ad07844c4ca75129a537a1 | <|skeleton|>
class SCR_Watchdog:
"""This class attempts to detect hanging applications in order to avoid wasting allocations Use of the SCR_Watchdog requires 3 configuration variables to be set: SCR_WATCHDOG=1 The watchdog must be enabled (set to '1') We must also have an expected time (in seconds) to check for exi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SCR_Watchdog:
"""This class attempts to detect hanging applications in order to avoid wasting allocations Use of the SCR_Watchdog requires 3 configuration variables to be set: SCR_WATCHDOG=1 The watchdog must be enabled (set to '1') We must also have an expected time (in seconds) to check for existence of che... | the_stack_v2_python_sparse | scripts/python/scrjob/scr_watchdog.py | LLNL/scr | train | 84 |
85003e042f2ee32a40d167c11ced6d3f6cc94ac6 | [
"if not triangle:\n return 0\nn = len(triangle)\ndp = [[0] * n for _ in range(n)]\ndp[0][0] = triangle[0][0]\nfor i in range(1, n):\n dp[i][0] = dp[i - 1][0] + triangle[i][0]\n for j in range(1, i):\n dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j]) + triangle[i][j]\n dp[i][i] = dp[i - 1][i - 1] + ... | <|body_start_0|>
if not triangle:
return 0
n = len(triangle)
dp = [[0] * n for _ in range(n)]
dp[0][0] = triangle[0][0]
for i in range(1, n):
dp[i][0] = dp[i - 1][0] + triangle[i][0]
for j in range(1, i):
dp[i][j] = min(dp[i - 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumTotal(self, triangle: list) -> int:
"""自顶向下的动态规划"""
<|body_0|>
def minimumTotal_1(self, triangle: list) -> int:
"""自底向上的动态规划"""
<|body_1|>
def minimumTotal_2(self, triangle: list) -> int:
"""自底向上的动态规划 空间优化 发现dp[i][j]只和下一层dp[i... | stack_v2_sparse_classes_36k_train_008816 | 1,739 | no_license | [
{
"docstring": "自顶向下的动态规划",
"name": "minimumTotal",
"signature": "def minimumTotal(self, triangle: list) -> int"
},
{
"docstring": "自底向上的动态规划",
"name": "minimumTotal_1",
"signature": "def minimumTotal_1(self, triangle: list) -> int"
},
{
"docstring": "自底向上的动态规划 空间优化 发现dp[i][j]只和下... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle: list) -> int: 自顶向下的动态规划
- def minimumTotal_1(self, triangle: list) -> int: 自底向上的动态规划
- def minimumTotal_2(self, triangle: list) -> int: 自底向上的动态规划... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle: list) -> int: 自顶向下的动态规划
- def minimumTotal_1(self, triangle: list) -> int: 自底向上的动态规划
- def minimumTotal_2(self, triangle: list) -> int: 自底向上的动态规划... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def minimumTotal(self, triangle: list) -> int:
"""自顶向下的动态规划"""
<|body_0|>
def minimumTotal_1(self, triangle: list) -> int:
"""自底向上的动态规划"""
<|body_1|>
def minimumTotal_2(self, triangle: list) -> int:
"""自底向上的动态规划 空间优化 发现dp[i][j]只和下一层dp[i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumTotal(self, triangle: list) -> int:
"""自顶向下的动态规划"""
if not triangle:
return 0
n = len(triangle)
dp = [[0] * n for _ in range(n)]
dp[0][0] = triangle[0][0]
for i in range(1, n):
dp[i][0] = dp[i - 1][0] + triangle[i][0]... | the_stack_v2_python_sparse | algorithm/leetcode/dp/14-三角形最小路径和.py | lxconfig/UbuntuCode_bak | train | 0 | |
863777be6a8136dd8144abda04eea8a9265533b8 | [
"if not data:\n return b'\\x00' * size if size else b'\\x00'\nif size and len(data) < size:\n data.extend(['' for _ in range(size - len(data))])\nif size and len(data) > size:\n data = data[:size]\nreturn b'\\x00'.join([d.replace('\\x00', '').encode('utf-8') for d in data]) + b'\\x00'",
"if size:\n tm... | <|body_start_0|>
if not data:
return b'\x00' * size if size else b'\x00'
if size and len(data) < size:
data.extend(['' for _ in range(size - len(data))])
if size and len(data) > size:
data = data[:size]
return b'\x00'.join([d.replace('\x00', '').encode... | List of null terminated string | SMPayloadTypeNTLIST | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SMPayloadTypeNTLIST:
"""List of null terminated string"""
def encode(data, size=None):
"""Encode list of unicode string into null terminated strings. :param data: the list to encode :param size: Size of the list :Example: >>> SMPayloadTypeNTLIST.encode(["string1", "string2"], 2) b'st... | stack_v2_sparse_classes_36k_train_008817 | 14,049 | permissive | [
{
"docstring": "Encode list of unicode string into null terminated strings. :param data: the list to encode :param size: Size of the list :Example: >>> SMPayloadTypeNTLIST.encode([\"string1\", \"string2\"], 2) b'string1\\\\x00string2\\\\x00' >>> # zero padding >>> SMPayloadTypeNTLIST.encode([\"string1\", \"stri... | 2 | stack_v2_sparse_classes_30k_train_007311 | Implement the Python class `SMPayloadTypeNTLIST` described below.
Class description:
List of null terminated string
Method signatures and docstrings:
- def encode(data, size=None): Encode list of unicode string into null terminated strings. :param data: the list to encode :param size: Size of the list :Example: >>> S... | Implement the Python class `SMPayloadTypeNTLIST` described below.
Class description:
List of null terminated string
Method signatures and docstrings:
- def encode(data, size=None): Encode list of unicode string into null terminated strings. :param data: the list to encode :param size: Size of the list :Example: >>> S... | cf20b363ed3d7bcb75101b17870e876a857ecd66 | <|skeleton|>
class SMPayloadTypeNTLIST:
"""List of null terminated string"""
def encode(data, size=None):
"""Encode list of unicode string into null terminated strings. :param data: the list to encode :param size: Size of the list :Example: >>> SMPayloadTypeNTLIST.encode(["string1", "string2"], 2) b'st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SMPayloadTypeNTLIST:
"""List of null terminated string"""
def encode(data, size=None):
"""Encode list of unicode string into null terminated strings. :param data: the list to encode :param size: Size of the list :Example: >>> SMPayloadTypeNTLIST.encode(["string1", "string2"], 2) b'string1\\x00str... | the_stack_v2_python_sparse | smserver/smutils/smpacket/smencoder.py | Moutix/stepmania-server | train | 4 |
8681cb0b4cd9d3f7f8086d0d85e51ce706a202f5 | [
"if req_format not in ('json', 'xml', ''):\n raise ValueError(\"Unknown data format '%s'\" % req_format)\nif api_version is 1:\n if domain == 'api.twitter.com' or domain == 'stream.twitter.com':\n api_version = '1'\n else:\n api_version = None\ndomain += '/%s' % api_version\nAPICall.__init__(... | <|body_start_0|>
if req_format not in ('json', 'xml', ''):
raise ValueError("Unknown data format '%s'" % req_format)
if api_version is 1:
if domain == 'api.twitter.com' or domain == 'stream.twitter.com':
api_version = '1'
else:
api_vers... | The minimalist yet fully featured Twitter API class. Get RESTful data by accessing members of this class. The result is decoded python objects (lists and dicts). >>> from frappy.services.twitter.twitter import Twitter >>> t = Twitter() >>> statuses = t.statuses.public_timeline() >>> '200 OK' == statuses.headers['respon... | Twitter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
"""The minimalist yet fully featured Twitter API class. Get RESTful data by accessing members of this class. The result is decoded python objects (lists and dicts). >>> from frappy.services.twitter.twitter import Twitter >>> t = Twitter() >>> statuses = t.statuses.public_timeline() >>> '... | stack_v2_sparse_classes_36k_train_008818 | 4,423 | permissive | [
{
"docstring": "Create a new twitter API connector. Pass an `auth` parameter to use the credentials of a specific user. Generally you'll want to pass an `OAuth` instance:: twitter = Twitter(auth=OAuth( token, token_secret, consumer_key, consumer_secret)) `domain` lets you change the domain you are connecting. B... | 2 | stack_v2_sparse_classes_30k_val_000659 | Implement the Python class `Twitter` described below.
Class description:
The minimalist yet fully featured Twitter API class. Get RESTful data by accessing members of this class. The result is decoded python objects (lists and dicts). >>> from frappy.services.twitter.twitter import Twitter >>> t = Twitter() >>> status... | Implement the Python class `Twitter` described below.
Class description:
The minimalist yet fully featured Twitter API class. Get RESTful data by accessing members of this class. The result is decoded python objects (lists and dicts). >>> from frappy.services.twitter.twitter import Twitter >>> t = Twitter() >>> status... | 543e8d1d6162d1414d05ac60a31c20e223de008d | <|skeleton|>
class Twitter:
"""The minimalist yet fully featured Twitter API class. Get RESTful data by accessing members of this class. The result is decoded python objects (lists and dicts). >>> from frappy.services.twitter.twitter import Twitter >>> t = Twitter() >>> statuses = t.statuses.public_timeline() >>> '... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Twitter:
"""The minimalist yet fully featured Twitter API class. Get RESTful data by accessing members of this class. The result is decoded python objects (lists and dicts). >>> from frappy.services.twitter.twitter import Twitter >>> t = Twitter() >>> statuses = t.statuses.public_timeline() >>> '200 OK' == st... | the_stack_v2_python_sparse | frappy/services/twitter/twitter.py | durden/frappy | train | 8 |
36f3acf40a61c67914f318d60899e58507cb7dc5 | [
"tracks = []\nfor line in data.splitlines():\n track = line.strip()\n if not url_only:\n if not track.lower().startswith('title'):\n continue\n track = re.sub('title\\\\d+?\\\\=', '', track, flags=re.IGNORECASE)\n else:\n if not track.lower().startswith('file'):\n ... | <|body_start_0|>
tracks = []
for line in data.splitlines():
track = line.strip()
if not url_only:
if not track.lower().startswith('title'):
continue
track = re.sub('title\\d+?\\=', '', track, flags=re.IGNORECASE)
els... | Very basic and silly PLS parser | PLSFileLibrary | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PLSFileLibrary:
"""Very basic and silly PLS parser"""
def pls_parser(data, url_only=False):
""".pls file parser"""
<|body_0|>
def parse(self, library_file, url_only=False):
"""Process PLS playlist, return items"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_008819 | 1,147 | permissive | [
{
"docstring": ".pls file parser",
"name": "pls_parser",
"signature": "def pls_parser(data, url_only=False)"
},
{
"docstring": "Process PLS playlist, return items",
"name": "parse",
"signature": "def parse(self, library_file, url_only=False)"
}
] | 2 | null | Implement the Python class `PLSFileLibrary` described below.
Class description:
Very basic and silly PLS parser
Method signatures and docstrings:
- def pls_parser(data, url_only=False): .pls file parser
- def parse(self, library_file, url_only=False): Process PLS playlist, return items | Implement the Python class `PLSFileLibrary` described below.
Class description:
Very basic and silly PLS parser
Method signatures and docstrings:
- def pls_parser(data, url_only=False): .pls file parser
- def parse(self, library_file, url_only=False): Process PLS playlist, return items
<|skeleton|>
class PLSFileLibr... | 3e35a25cfcf982a3871cf0d819bae4374ee31ecf | <|skeleton|>
class PLSFileLibrary:
"""Very basic and silly PLS parser"""
def pls_parser(data, url_only=False):
""".pls file parser"""
<|body_0|>
def parse(self, library_file, url_only=False):
"""Process PLS playlist, return items"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PLSFileLibrary:
"""Very basic and silly PLS parser"""
def pls_parser(data, url_only=False):
""".pls file parser"""
tracks = []
for line in data.splitlines():
track = line.strip()
if not url_only:
if not track.lower().startswith('title'):
... | the_stack_v2_python_sparse | voiceplay/datasources/playlists/libraries/plsfile.py | tb0hdan/voiceplay | train | 4 |
fa773c719364a4f39cf61df448f954bb15019827 | [
"m = len(obstacleGrid[0])\nn = len(obstacleGrid)\nif obstacleGrid[0][0] == 1 or obstacleGrid[n - 1][m - 1] == 1:\n return 0\ndp = []\nflag = True\nfor i in range(n):\n if obstacleGrid[i][0] == 0 and flag:\n dp.append([1] + [0] * (m - 1))\n else:\n dp.append([0] * m)\n flag = False\ndp ... | <|body_start_0|>
m = len(obstacleGrid[0])
n = len(obstacleGrid)
if obstacleGrid[0][0] == 1 or obstacleGrid[n - 1][m - 1] == 1:
return 0
dp = []
flag = True
for i in range(n):
if obstacleGrid[i][0] == 0 and flag:
dp.append([1] + [0] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_0|>
def uniquePathsWithObstacles2(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_008820 | 2,758 | no_license | [
{
"docstring": ":type obstacleGrid: List[List[int]] :rtype: int",
"name": "uniquePathsWithObstacles",
"signature": "def uniquePathsWithObstacles(self, obstacleGrid)"
},
{
"docstring": ":type obstacleGrid: List[List[int]] :rtype: int",
"name": "uniquePathsWithObstacles2",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_020907 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePathsWithObstacles(self, obstacleGrid): :type obstacleGrid: List[List[int]] :rtype: int
- def uniquePathsWithObstacles2(self, obstacleGrid): :type obstacleGrid: List[Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePathsWithObstacles(self, obstacleGrid): :type obstacleGrid: List[List[int]] :rtype: int
- def uniquePathsWithObstacles2(self, obstacleGrid): :type obstacleGrid: List[Li... | db2d0b05020a1fcb9f0cfaf9386f79daeaad759e | <|skeleton|>
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_0|>
def uniquePathsWithObstacles2(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
m = len(obstacleGrid[0])
n = len(obstacleGrid)
if obstacleGrid[0][0] == 1 or obstacleGrid[n - 1][m - 1] == 1:
return 0
dp = []
flag = Tr... | the_stack_v2_python_sparse | leetcode/dynamic_programming/63_unique_paths_with_obstacles.py | longgb246/MLlearn | train | 0 | |
c463f1cb1e9f86b53dad34946ca94053084a2454 | [
"log.debug('compose_alert() ' + locality + ' | <START>')\nalert_body = ''\ndb_cur_one.execute(\"select COUNT(*) from ZMT_RESTAURANTS ZR, ZMT_RESTAURANTS_EXT ZR_EXT where ZR.RESTAURANT_ID = ZR_EXT.RESTAURANT_ID and TO_CHAR(ZR.INSERT_DT, 'YYYYMM') = TO_CHAR(SYSDATE, 'YYYYMM') and ZR_EXT.PERIOD = TO_CHAR(SYSDATE,... | <|body_start_0|>
log.debug('compose_alert() ' + locality + ' | <START>')
alert_body = ''
db_cur_one.execute("select COUNT(*) from ZMT_RESTAURANTS ZR, ZMT_RESTAURANTS_EXT ZR_EXT where ZR.RESTAURANT_ID = ZR_EXT.RESTAURANT_ID and TO_CHAR(ZR.INSERT_DT, 'YYYYMM') = TO_CHAR(SYSDATE, 'YYYYMM') and... | ZomatoAlerts | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZomatoAlerts:
def compose_alert(self, locality):
"""Compose Alert"""
<|body_0|>
def send_alert(self, api_key, alert_body, locality):
"""Send Alert"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
log.debug('compose_alert() ' + locality + ' | <START>'... | stack_v2_sparse_classes_36k_train_008821 | 41,261 | no_license | [
{
"docstring": "Compose Alert",
"name": "compose_alert",
"signature": "def compose_alert(self, locality)"
},
{
"docstring": "Send Alert",
"name": "send_alert",
"signature": "def send_alert(self, api_key, alert_body, locality)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002557 | Implement the Python class `ZomatoAlerts` described below.
Class description:
Implement the ZomatoAlerts class.
Method signatures and docstrings:
- def compose_alert(self, locality): Compose Alert
- def send_alert(self, api_key, alert_body, locality): Send Alert | Implement the Python class `ZomatoAlerts` described below.
Class description:
Implement the ZomatoAlerts class.
Method signatures and docstrings:
- def compose_alert(self, locality): Compose Alert
- def send_alert(self, api_key, alert_body, locality): Send Alert
<|skeleton|>
class ZomatoAlerts:
def compose_aler... | 2e6c48d1a39f6f44e1db827f60dbdc7907b74b63 | <|skeleton|>
class ZomatoAlerts:
def compose_alert(self, locality):
"""Compose Alert"""
<|body_0|>
def send_alert(self, api_key, alert_body, locality):
"""Send Alert"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZomatoAlerts:
def compose_alert(self, locality):
"""Compose Alert"""
log.debug('compose_alert() ' + locality + ' | <START>')
alert_body = ''
db_cur_one.execute("select COUNT(*) from ZMT_RESTAURANTS ZR, ZMT_RESTAURANTS_EXT ZR_EXT where ZR.RESTAURANT_ID = ZR_EXT.RESTAURANT_ID ... | the_stack_v2_python_sparse | mylibrary/zmt_20180331.py | nitinx/zomato-mart | train | 0 | |
25362dc50185f1e9face87ee0f801b4996484faf | [
"config_model = config['model']\nconfig_control = config['control']\nconfig_bo = config['bo']\nseed = config.get('_RDM_SEED', None)\nif config_model.get('debug', False):\n pdb.set_trace()\nnp.random.seed(seed)\nalpha = config_control.get('alpha', None)\nif alpha is None:\n alpha_std = config_control.get('alph... | <|body_start_0|>
config_model = config['model']
config_control = config['control']
config_bo = config['bo']
seed = config.get('_RDM_SEED', None)
if config_model.get('debug', False):
pdb.set_trace()
np.random.seed(seed)
alpha = config_control.get('alpha... | Warp q_simulator to be run on the cluster | BatchQsim | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchQsim:
"""Warp q_simulator to be run on the cluster"""
def run_one_procedure(self, config):
"""Define what one run should do"""
<|body_0|>
def _process_collection_res(cls, collection_res, **xargs):
"""Process the collected res."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_008822 | 4,902 | no_license | [
{
"docstring": "Define what one run should do",
"name": "run_one_procedure",
"signature": "def run_one_procedure(self, config)"
},
{
"docstring": "Process the collected res.",
"name": "_process_collection_res",
"signature": "def _process_collection_res(cls, collection_res, **xargs)"
}
... | 2 | stack_v2_sparse_classes_30k_train_000891 | Implement the Python class `BatchQsim` described below.
Class description:
Warp q_simulator to be run on the cluster
Method signatures and docstrings:
- def run_one_procedure(self, config): Define what one run should do
- def _process_collection_res(cls, collection_res, **xargs): Process the collected res. | Implement the Python class `BatchQsim` described below.
Class description:
Warp q_simulator to be run on the cluster
Method signatures and docstrings:
- def run_one_procedure(self, config): Define what one run should do
- def _process_collection_res(cls, collection_res, **xargs): Process the collected res.
<|skeleto... | 0be68edfa33fb570d52e31be1d0b277a611b9ba4 | <|skeleton|>
class BatchQsim:
"""Warp q_simulator to be run on the cluster"""
def run_one_procedure(self, config):
"""Define what one run should do"""
<|body_0|>
def _process_collection_res(cls, collection_res, **xargs):
"""Process the collected res."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchQsim:
"""Warp q_simulator to be run on the cluster"""
def run_one_procedure(self, config):
"""Define what one run should do"""
config_model = config['model']
config_control = config['control']
config_bo = config['bo']
seed = config.get('_RDM_SEED', None)
... | the_stack_v2_python_sparse | Batch/metalearning/batch_qsim.py | FredericSauv/QuantumSimulation | train | 0 |
b1599471fcba9e272717bb752982cbc30362c232 | [
"if not pre:\n return None\nroot = TreeNode(pre[0])\nif len(pre) == 1:\n return root\nif pre[1] == post[-2]:\n right_length = len(pre[1:])\n right_post = post[:right_length]\n right_pre = pre[1:]\n left_pre = None\n left_post = None\nelse:\n post_left_index = post.index(pre[1])\n length_l... | <|body_start_0|>
if not pre:
return None
root = TreeNode(pre[0])
if len(pre) == 1:
return root
if pre[1] == post[-2]:
right_length = len(pre[1:])
right_post = post[:right_length]
right_pre = pre[1:]
left_pre = None
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def constructFromPrePost(self, pre, post):
""":type pre: List[int] :type post: List[int] :rtype: TreeNode"""
<|body_0|>
def constructFromPrePost2(self, pre, post):
""":type pre: List[int] :type post: List[int] :rtype: TreeNode"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_008823 | 1,684 | no_license | [
{
"docstring": ":type pre: List[int] :type post: List[int] :rtype: TreeNode",
"name": "constructFromPrePost",
"signature": "def constructFromPrePost(self, pre, post)"
},
{
"docstring": ":type pre: List[int] :type post: List[int] :rtype: TreeNode",
"name": "constructFromPrePost2",
"signat... | 2 | stack_v2_sparse_classes_30k_train_007798 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def constructFromPrePost(self, pre, post): :type pre: List[int] :type post: List[int] :rtype: TreeNode
- def constructFromPrePost2(self, pre, post): :type pre: List[int] :type po... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def constructFromPrePost(self, pre, post): :type pre: List[int] :type post: List[int] :rtype: TreeNode
- def constructFromPrePost2(self, pre, post): :type pre: List[int] :type po... | 4105e18050b15fc0409c75353ad31be17187dd34 | <|skeleton|>
class Solution:
def constructFromPrePost(self, pre, post):
""":type pre: List[int] :type post: List[int] :rtype: TreeNode"""
<|body_0|>
def constructFromPrePost2(self, pre, post):
""":type pre: List[int] :type post: List[int] :rtype: TreeNode"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def constructFromPrePost(self, pre, post):
""":type pre: List[int] :type post: List[int] :rtype: TreeNode"""
if not pre:
return None
root = TreeNode(pre[0])
if len(pre) == 1:
return root
if pre[1] == post[-2]:
right_length =... | the_stack_v2_python_sparse | constructFromPrePost.py | NeilWangziyu/Leetcode_py | train | 2 | |
c046327833a99c1f31663639e071facc92067f92 | [
"authenticated_user_id = token_auth.current_user()\nif UserService.is_user_blocked(authenticated_user_id):\n return ({'Error': 'User is on read only mode', 'SubCode': 'ReadOnly'}, 403)\ntry:\n task_comment = TaskCommentDTO(request.get_json())\n task_comment.user_id = token_auth.current_user()\n task_com... | <|body_start_0|>
authenticated_user_id = token_auth.current_user()
if UserService.is_user_blocked(authenticated_user_id):
return ({'Error': 'User is on read only mode', 'SubCode': 'ReadOnly'}, 403)
try:
task_comment = TaskCommentDTO(request.get_json())
task_co... | CommentsTasksRestAPI | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentsTasksRestAPI:
def post(self, project_id, task_id):
"""Adds a comment to the task outside of mapping/validation --- tags: - comments produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string defa... | stack_v2_sparse_classes_36k_train_008824 | 10,563 | permissive | [
{
"docstring": "Adds a comment to the task outside of mapping/validation --- tags: - comments produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - name: project_id in: path description:... | 2 | null | Implement the Python class `CommentsTasksRestAPI` described below.
Class description:
Implement the CommentsTasksRestAPI class.
Method signatures and docstrings:
- def post(self, project_id, task_id): Adds a comment to the task outside of mapping/validation --- tags: - comments produces: - application/json parameters... | Implement the Python class `CommentsTasksRestAPI` described below.
Class description:
Implement the CommentsTasksRestAPI class.
Method signatures and docstrings:
- def post(self, project_id, task_id): Adds a comment to the task outside of mapping/validation --- tags: - comments produces: - application/json parameters... | 45bf3937c74902226096aee5b49e7abea62df524 | <|skeleton|>
class CommentsTasksRestAPI:
def post(self, project_id, task_id):
"""Adds a comment to the task outside of mapping/validation --- tags: - comments produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string defa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentsTasksRestAPI:
def post(self, project_id, task_id):
"""Adds a comment to the task outside of mapping/validation --- tags: - comments produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token ses... | the_stack_v2_python_sparse | backend/api/comments/resources.py | hotosm/tasking-manager | train | 526 | |
b6a79dd37c7806e84fd3e2e2ed7201ba89d519df | [
"create_url = f'https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={self.token}'\n'\\n 1、把接口请求信息封装到字典中\\n 2、接口中不需要再引入requests\\n '\nreq = {'method': 'post', 'url': create_url, 'json': data}\nr = self.send_api(req)\nreturn r.json()",
"url = f'https://qyapi.weixin.qq.com/cgi-bin... | <|body_start_0|>
create_url = f'https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={self.token}'
'\n 1、把接口请求信息封装到字典中\n 2、接口中不需要再引入requests\n '
req = {'method': 'post', 'url': create_url, 'json': data}
r = self.send_api(req)
return r.json()
<|e... | Department | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Department:
def creat_department(self, data):
"""创建部门 :return:创建部门接口的响应"""
<|body_0|>
def update_department(self, data):
"""更新部门信息 :return:更新部门接口的响应"""
<|body_1|>
def delete_department(self, depart_id):
"""删除部门信息 :return:删除部门接口的响应"""
<|bo... | stack_v2_sparse_classes_36k_train_008825 | 2,542 | no_license | [
{
"docstring": "创建部门 :return:创建部门接口的响应",
"name": "creat_department",
"signature": "def creat_department(self, data)"
},
{
"docstring": "更新部门信息 :return:更新部门接口的响应",
"name": "update_department",
"signature": "def update_department(self, data)"
},
{
"docstring": "删除部门信息 :return:删除部门接... | 5 | stack_v2_sparse_classes_30k_train_000759 | Implement the Python class `Department` described below.
Class description:
Implement the Department class.
Method signatures and docstrings:
- def creat_department(self, data): 创建部门 :return:创建部门接口的响应
- def update_department(self, data): 更新部门信息 :return:更新部门接口的响应
- def delete_department(self, depart_id): 删除部门信息 :retur... | Implement the Python class `Department` described below.
Class description:
Implement the Department class.
Method signatures and docstrings:
- def creat_department(self, data): 创建部门 :return:创建部门接口的响应
- def update_department(self, data): 更新部门信息 :return:更新部门接口的响应
- def delete_department(self, depart_id): 删除部门信息 :retur... | cf66ffa38cb7196a533b89d9b31313a270a7cd84 | <|skeleton|>
class Department:
def creat_department(self, data):
"""创建部门 :return:创建部门接口的响应"""
<|body_0|>
def update_department(self, data):
"""更新部门信息 :return:更新部门接口的响应"""
<|body_1|>
def delete_department(self, depart_id):
"""删除部门信息 :return:删除部门接口的响应"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Department:
def creat_department(self, data):
"""创建部门 :return:创建部门接口的响应"""
create_url = f'https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={self.token}'
'\n 1、把接口请求信息封装到字典中\n 2、接口中不需要再引入requests\n '
req = {'method': 'post', 'url': create_u... | the_stack_v2_python_sparse | w_service/apis/department.py | yfgbamboo/wework | train | 0 | |
2c5b3255f2bc9fa3d96f5af3b5885f817ee45e34 | [
"self._padding = padding\nself._padding_mode = padding_mode\nsuper(Pad1D, self).__init__(**kwargs)",
"if self._padding_mode == 'zero':\n paddings = ((0, 0), self._padding, (0, 0))\n outputs = tf.pad(inputs, paddings)\nelif self._padding_mode == 'wrap':\n outputs = tf.concat([inputs[:, -self._padding[0]:,... | <|body_start_0|>
self._padding = padding
self._padding_mode = padding_mode
super(Pad1D, self).__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
if self._padding_mode == 'zero':
paddings = ((0, 0), self._padding, (0, 0))
outputs = tf.pad(inputs, paddings)
... | Pads a (batch, size, channels) tensor. | Pad1D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pad1D:
"""Pads a (batch, size, channels) tensor."""
def __init__(self, padding, padding_mode, **kwargs):
"""Creates the padding layer. Args: padding: (pad_left, pad_right) pair. How many elements to add to both sides of the second dimension. If this is used for the very first layer o... | stack_v2_sparse_classes_36k_train_008826 | 14,886 | permissive | [
{
"docstring": "Creates the padding layer. Args: padding: (pad_left, pad_right) pair. How many elements to add to both sides of the second dimension. If this is used for the very first layer of the feelers CNN, this can be thought as the number of feeler entries to add before the first feeler entry and after th... | 2 | stack_v2_sparse_classes_30k_train_007352 | Implement the Python class `Pad1D` described below.
Class description:
Pads a (batch, size, channels) tensor.
Method signatures and docstrings:
- def __init__(self, padding, padding_mode, **kwargs): Creates the padding layer. Args: padding: (pad_left, pad_right) pair. How many elements to add to both sides of the sec... | Implement the Python class `Pad1D` described below.
Class description:
Pads a (batch, size, channels) tensor.
Method signatures and docstrings:
- def __init__(self, padding, padding_mode, **kwargs): Creates the padding layer. Args: padding: (pad_left, pad_right) pair. How many elements to add to both sides of the sec... | 26ab377a6853463b2efce40970e54d44b91e79ca | <|skeleton|>
class Pad1D:
"""Pads a (batch, size, channels) tensor."""
def __init__(self, padding, padding_mode, **kwargs):
"""Creates the padding layer. Args: padding: (pad_left, pad_right) pair. How many elements to add to both sides of the second dimension. If this is used for the very first layer o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pad1D:
"""Pads a (batch, size, channels) tensor."""
def __init__(self, padding, padding_mode, **kwargs):
"""Creates the padding layer. Args: padding: (pad_left, pad_right) pair. How many elements to add to both sides of the second dimension. If this is used for the very first layer of the feelers... | the_stack_v2_python_sparse | service/learner/brains/layers.py | stewartmiles/falken | train | 1 |
cfc1cc22fce9e37dbe3fbe44a8875a76cfc0a2ac | [
"super(PreprocessImage, self).__init__(env)\nself.img_size = (height, width)\nself.grayscale = grayscale\nno_crop = lambda img: img\nself.crop = crop or no_crop\nn_colors = 1 if self.grayscale else 3\nself.observation_space = Box(0.0, 1.0, [height, width, n_colors])",
"img = self.crop(img)\nimg = imresize(img, se... | <|body_start_0|>
super(PreprocessImage, self).__init__(env)
self.img_size = (height, width)
self.grayscale = grayscale
no_crop = lambda img: img
self.crop = crop or no_crop
n_colors = 1 if self.grayscale else 3
self.observation_space = Box(0.0, 1.0, [height, width... | PreprocessImage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreprocessImage:
def __init__(self, env, height=64, width=64, grayscale=True, crop=None):
"""A gym wrapper that crops, scales image into the desired shapes and optionally grayscales it."""
<|body_0|>
def _observation(self, img):
"""what happens to the observation"""
... | stack_v2_sparse_classes_36k_train_008827 | 5,600 | permissive | [
{
"docstring": "A gym wrapper that crops, scales image into the desired shapes and optionally grayscales it.",
"name": "__init__",
"signature": "def __init__(self, env, height=64, width=64, grayscale=True, crop=None)"
},
{
"docstring": "what happens to the observation",
"name": "_observation... | 2 | stack_v2_sparse_classes_30k_train_021188 | Implement the Python class `PreprocessImage` described below.
Class description:
Implement the PreprocessImage class.
Method signatures and docstrings:
- def __init__(self, env, height=64, width=64, grayscale=True, crop=None): A gym wrapper that crops, scales image into the desired shapes and optionally grayscales it... | Implement the Python class `PreprocessImage` described below.
Class description:
Implement the PreprocessImage class.
Method signatures and docstrings:
- def __init__(self, env, height=64, width=64, grayscale=True, crop=None): A gym wrapper that crops, scales image into the desired shapes and optionally grayscales it... | 25aaa545167a2cddc4645e93bd3e5f98df34baa6 | <|skeleton|>
class PreprocessImage:
def __init__(self, env, height=64, width=64, grayscale=True, crop=None):
"""A gym wrapper that crops, scales image into the desired shapes and optionally grayscales it."""
<|body_0|>
def _observation(self, img):
"""what happens to the observation"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreprocessImage:
def __init__(self, env, height=64, width=64, grayscale=True, crop=None):
"""A gym wrapper that crops, scales image into the desired shapes and optionally grayscales it."""
super(PreprocessImage, self).__init__(env)
self.img_size = (height, width)
self.grayscale... | the_stack_v2_python_sparse | wrappers/gym_wrappers.py | diegslva/rl-course-experiments | train | 1 | |
0e0e91540b79cf7534968fcfcff20bba4558030a | [
"number = int(number)\ntag = ''\nstundenindex = 0\nif number in range(1, 10):\n tag = 'Montag'\n stundenindex = range(1, 10).index(number) + 1\nif number in range(10, 19):\n tag = 'Dienstag'\n stundenindex = range(10, 19).index(number) + 1\nif number in range(19, 28):\n tag = 'Mittwoch'\n stundeni... | <|body_start_0|>
number = int(number)
tag = ''
stundenindex = 0
if number in range(1, 10):
tag = 'Montag'
stundenindex = range(1, 10).index(number) + 1
if number in range(10, 19):
tag = 'Dienstag'
stundenindex = range(10, 19).index(... | writingTimetables | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class writingTimetables:
def convert_to_slot(number):
"""converting given number from 1 to 40 to a slot in out model"""
<|body_0|>
def getTimetableUnits():
"""gehe durch X_res und finde alle Zeilen, die die gegebene Klasse haben Für jeden Tag, gehe durch jede Stunde und sa... | stack_v2_sparse_classes_36k_train_008828 | 6,215 | no_license | [
{
"docstring": "converting given number from 1 to 40 to a slot in out model",
"name": "convert_to_slot",
"signature": "def convert_to_slot(number)"
},
{
"docstring": "gehe durch X_res und finde alle Zeilen, die die gegebene Klasse haben Für jeden Tag, gehe durch jede Stunde und sammle die dortig... | 2 | stack_v2_sparse_classes_30k_train_021173 | Implement the Python class `writingTimetables` described below.
Class description:
Implement the writingTimetables class.
Method signatures and docstrings:
- def convert_to_slot(number): converting given number from 1 to 40 to a slot in out model
- def getTimetableUnits(): gehe durch X_res und finde alle Zeilen, die ... | Implement the Python class `writingTimetables` described below.
Class description:
Implement the writingTimetables class.
Method signatures and docstrings:
- def convert_to_slot(number): converting given number from 1 to 40 to a slot in out model
- def getTimetableUnits(): gehe durch X_res und finde alle Zeilen, die ... | 359975b01f2bc8162d7337b03413b52dba5aa4f0 | <|skeleton|>
class writingTimetables:
def convert_to_slot(number):
"""converting given number from 1 to 40 to a slot in out model"""
<|body_0|>
def getTimetableUnits():
"""gehe durch X_res und finde alle Zeilen, die die gegebene Klasse haben Für jeden Tag, gehe durch jede Stunde und sa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class writingTimetables:
def convert_to_slot(number):
"""converting given number from 1 to 40 to a slot in out model"""
number = int(number)
tag = ''
stundenindex = 0
if number in range(1, 10):
tag = 'Montag'
stundenindex = range(1, 10).index(number) +... | the_stack_v2_python_sparse | src/dataoutput/write_timetables.py | franzimossner/stundentool | train | 0 | |
1d4b6c0d99c6a16c98ec62635743e9970013b043 | [
"if not root:\n return ''\nprintout = []\n\ndef recurserialize(root):\n if not root:\n printout.append('* ')\n else:\n printout.append(str(root.val) + ' ')\n recurserialize(root.left)\n recurserialize(root.right)\nrecurserialize(root)\nreturn ''.join(printout)[:-1]",
"if not d... | <|body_start_0|>
if not root:
return ''
printout = []
def recurserialize(root):
if not root:
printout.append('* ')
else:
printout.append(str(root.val) + ' ')
recurserialize(root.left)
recurserial... | 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_008829 | 3,172 | 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_009464 | 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:... | 2cc179bdb33a97294a2bf99dbda278e935165943 | <|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 ''
printout = []
def recurserialize(root):
if not root:
printout.append('* ')
else:
... | the_stack_v2_python_sparse | leetcode/449.py | Zedmor/hackerrank-puzzles | train | 0 | |
7281d1de9c797fd6dda73bac435566f3f0504290 | [
"input_json, output_json = (request.data, {})\noutput_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['AvailabilityDetails'], input_json['AuthenticationDetails'], input_json['SessionDetails'], None]))\npayload = {'Payload': None}\noutput_json['Payload'] = {... | <|body_start_0|>
input_json, output_json = (request.data, {})
output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['AvailabilityDetails'], input_json['AuthenticationDetails'], input_json['SessionDetails'], None]))
payload = {'Payload':... | This covers the API for logout of verified user from current_session or all sessions. | UserLogoutAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserLogoutAPI:
"""This covers the API for logout of verified user from current_session or all sessions."""
def post(self, request):
"""Function to perform logout of verified user from current_session or all sessions."""
<|body_0|>
def logout_session(self, request):
... | stack_v2_sparse_classes_36k_train_008830 | 3,909 | no_license | [
{
"docstring": "Function to perform logout of verified user from current_session or all sessions.",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Function to validate logout type input by user from logout type present in UserSessions table.",
"name": "logout_sessi... | 2 | null | Implement the Python class `UserLogoutAPI` described below.
Class description:
This covers the API for logout of verified user from current_session or all sessions.
Method signatures and docstrings:
- def post(self, request): Function to perform logout of verified user from current_session or all sessions.
- def logo... | Implement the Python class `UserLogoutAPI` described below.
Class description:
This covers the API for logout of verified user from current_session or all sessions.
Method signatures and docstrings:
- def post(self, request): Function to perform logout of verified user from current_session or all sessions.
- def logo... | 36eb9931f330e64902354c6fc471be2adf4b7049 | <|skeleton|>
class UserLogoutAPI:
"""This covers the API for logout of verified user from current_session or all sessions."""
def post(self, request):
"""Function to perform logout of verified user from current_session or all sessions."""
<|body_0|>
def logout_session(self, request):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserLogoutAPI:
"""This covers the API for logout of verified user from current_session or all sessions."""
def post(self, request):
"""Function to perform logout of verified user from current_session or all sessions."""
input_json, output_json = (request.data, {})
output_json = di... | the_stack_v2_python_sparse | Generic/common/logout/api/userlogout/views_userlogout.py | archiemb303/common_backend_django | train | 0 |
af5defcd48a064025a059ebacbf989bc06bd0c12 | [
"param = dict(locals())\nparam['param_dict'] = {'mean': mean, 'sd': sd}\nvalid_dtype = mstype.float_type\nValidator.check_type_name('dtype', dtype, valid_dtype, type(self).__name__)\nsuper(HalfNormal, self).__init__(seed, dtype, name, param)\nself._mean_value = self._add_parameter(mean, 'mean')\nself._sd_value = se... | <|body_start_0|>
param = dict(locals())
param['param_dict'] = {'mean': mean, 'sd': sd}
valid_dtype = mstype.float_type
Validator.check_type_name('dtype', dtype, valid_dtype, type(self).__name__)
super(HalfNormal, self).__init__(seed, dtype, name, param)
self._mean_value =... | HalfNormal distribution. A HalfNormal distribution is a continuous distribution with the range :math:`[\\mu, \\inf)` and the probability density function: .. math:: f(x, \\mu, \\sigma) = 1 / \\sigma\\sqrt{2\\pi} \\exp(-(x - \\mu)^2 / 2\\sigma^2). where :math:`\\mu, \\sigma` are the mean and the standard deviation of th... | HalfNormal | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-f... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HalfNormal:
"""HalfNormal distribution. A HalfNormal distribution is a continuous distribution with the range :math:`[\\mu, \\inf)` and the probability density function: .. math:: f(x, \\mu, \\sigma) = 1 / \\sigma\\sqrt{2\\pi} \\exp(-(x - \\mu)^2 / 2\\sigma^2). where :math:`\\mu, \\sigma` are the... | stack_v2_sparse_classes_36k_train_008831 | 5,845 | permissive | [
{
"docstring": "Constructor of HalfNormal.",
"name": "__init__",
"signature": "def __init__(self, mean=None, sd=None, seed=None, dtype=mstype.float32, name='HalfNormal')"
},
{
"docstring": "Evaluate probability of the value of the HalfNormal distribution. Args: value (Tensor): The value to be ev... | 2 | null | Implement the Python class `HalfNormal` described below.
Class description:
HalfNormal distribution. A HalfNormal distribution is a continuous distribution with the range :math:`[\\mu, \\inf)` and the probability density function: .. math:: f(x, \\mu, \\sigma) = 1 / \\sigma\\sqrt{2\\pi} \\exp(-(x - \\mu)^2 / 2\\sigma^... | Implement the Python class `HalfNormal` described below.
Class description:
HalfNormal distribution. A HalfNormal distribution is a continuous distribution with the range :math:`[\\mu, \\inf)` and the probability density function: .. math:: f(x, \\mu, \\sigma) = 1 / \\sigma\\sqrt{2\\pi} \\exp(-(x - \\mu)^2 / 2\\sigma^... | 54acb15d435533c815ee1bd9f6dc0b56b4d4cf83 | <|skeleton|>
class HalfNormal:
"""HalfNormal distribution. A HalfNormal distribution is a continuous distribution with the range :math:`[\\mu, \\inf)` and the probability density function: .. math:: f(x, \\mu, \\sigma) = 1 / \\sigma\\sqrt{2\\pi} \\exp(-(x - \\mu)^2 / 2\\sigma^2). where :math:`\\mu, \\sigma` are the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HalfNormal:
"""HalfNormal distribution. A HalfNormal distribution is a continuous distribution with the range :math:`[\\mu, \\inf)` and the probability density function: .. math:: f(x, \\mu, \\sigma) = 1 / \\sigma\\sqrt{2\\pi} \\exp(-(x - \\mu)^2 / 2\\sigma^2). where :math:`\\mu, \\sigma` are the mean and the... | the_stack_v2_python_sparse | mindspore/python/mindspore/nn/probability/distribution/half_normal.py | mindspore-ai/mindspore | train | 4,178 |
bbe3a6b06258fd0296926f68f0b2b50646e87392 | [
"super().__init__()\nself.factory = factory\nself.task_queue = task_queue\nself.done_queue = done_queue\nself.batch_queue = batch_queue\nif args is None:\n self.args = []\nelse:\n self.args = args\nif kwargs is None:\n self.kwargs = []\nelse:\n self.kwargs = kwargs",
"super().run()\nwhile True:\n f... | <|body_start_0|>
super().__init__()
self.factory = factory
self.task_queue = task_queue
self.done_queue = done_queue
self.batch_queue = batch_queue
if args is None:
self.args = []
else:
self.args = args
if kwargs is None:
... | The active dataset class takes care of concurrent reading of data from a dataset. | DatasetLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetLoader:
"""The active dataset class takes care of concurrent reading of data from a dataset."""
def __init__(self, factory, task_queue, done_queue, batch_queue, args=None, kwargs=None):
"""Args: factory: Class or factory function to use to open the dataset. filename: Filename ... | stack_v2_sparse_classes_36k_train_008832 | 17,927 | permissive | [
{
"docstring": "Args: factory: Class or factory function to use to open the dataset. filename: Filename of the dataset file to open. batch_queue: Queue on which to put the loaded batches. args: List of positional arguments to pass to the dataset factory following the dataset name. kwargs: Dictionary of keyword ... | 2 | stack_v2_sparse_classes_30k_train_020646 | Implement the Python class `DatasetLoader` described below.
Class description:
The active dataset class takes care of concurrent reading of data from a dataset.
Method signatures and docstrings:
- def __init__(self, factory, task_queue, done_queue, batch_queue, args=None, kwargs=None): Args: factory: Class or factory... | Implement the Python class `DatasetLoader` described below.
Class description:
The active dataset class takes care of concurrent reading of data from a dataset.
Method signatures and docstrings:
- def __init__(self, factory, task_queue, done_queue, batch_queue, args=None, kwargs=None): Args: factory: Class or factory... | a27e329cd30337995c359160a0d878bf331c13fb | <|skeleton|>
class DatasetLoader:
"""The active dataset class takes care of concurrent reading of data from a dataset."""
def __init__(self, factory, task_queue, done_queue, batch_queue, args=None, kwargs=None):
"""Args: factory: Class or factory function to use to open the dataset. filename: Filename ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatasetLoader:
"""The active dataset class takes care of concurrent reading of data from a dataset."""
def __init__(self, factory, task_queue, done_queue, batch_queue, args=None, kwargs=None):
"""Args: factory: Class or factory function to use to open the dataset. filename: Filename of the datase... | the_stack_v2_python_sparse | quantnn/data.py | simonpf/quantnn | train | 7 |
6bdc62e4e294afedd8066db2a224373c030a7c6f | [
"self.Reinitialize(urllib.urlencode([('prefix_integer_field', '10'), ('prefix_string_field', 'a string'), ('prefix_enum_field', 'VAL1')]), self.content_type)\nurl_encoded_mapper = service_handlers.URLEncodedRPCMapper(parameter_prefix='prefix_')\nrequest = url_encoded_mapper.build_request(self.service_handler, Reque... | <|body_start_0|>
self.Reinitialize(urllib.urlencode([('prefix_integer_field', '10'), ('prefix_string_field', 'a string'), ('prefix_enum_field', 'VAL1')]), self.content_type)
url_encoded_mapper = service_handlers.URLEncodedRPCMapper(parameter_prefix='prefix_')
request = url_encoded_mapper.build_r... | Test the URL encoded RPC mapper. | URLEncodedRPCMapperTest | [
"Apache-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class URLEncodedRPCMapperTest:
"""Test the URL encoded RPC mapper."""
def testBuildRequest_Prefix(self):
"""Test building request with parameter prefix."""
<|body_0|>
def testBuildRequest_DecodeError(self):
"""Test trying to build request that causes a decode error."""... | stack_v2_sparse_classes_36k_train_008833 | 46,517 | permissive | [
{
"docstring": "Test building request with parameter prefix.",
"name": "testBuildRequest_Prefix",
"signature": "def testBuildRequest_Prefix(self)"
},
{
"docstring": "Test trying to build request that causes a decode error.",
"name": "testBuildRequest_DecodeError",
"signature": "def testB... | 3 | stack_v2_sparse_classes_30k_train_020815 | Implement the Python class `URLEncodedRPCMapperTest` described below.
Class description:
Test the URL encoded RPC mapper.
Method signatures and docstrings:
- def testBuildRequest_Prefix(self): Test building request with parameter prefix.
- def testBuildRequest_DecodeError(self): Test trying to build request that caus... | Implement the Python class `URLEncodedRPCMapperTest` described below.
Class description:
Test the URL encoded RPC mapper.
Method signatures and docstrings:
- def testBuildRequest_Prefix(self): Test building request with parameter prefix.
- def testBuildRequest_DecodeError(self): Test trying to build request that caus... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class URLEncodedRPCMapperTest:
"""Test the URL encoded RPC mapper."""
def testBuildRequest_Prefix(self):
"""Test building request with parameter prefix."""
<|body_0|>
def testBuildRequest_DecodeError(self):
"""Test trying to build request that causes a decode error."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class URLEncodedRPCMapperTest:
"""Test the URL encoded RPC mapper."""
def testBuildRequest_Prefix(self):
"""Test building request with parameter prefix."""
self.Reinitialize(urllib.urlencode([('prefix_integer_field', '10'), ('prefix_string_field', 'a string'), ('prefix_enum_field', 'VAL1')]), s... | the_stack_v2_python_sparse | third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/webapp/service_handlers_test.py | metux/chromium-suckless | train | 5 |
8cd8269dd57e9adfd434de906e67c82aaeaf35b2 | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects = Base.__nb_objects + 1\n self.id = Base.__nb_objects",
"if list_dictionaries is None:\n return '[]'\nelse:\n return json.dumps(list_dictionaries)",
"new_list = []\nif list_objs is None:\n pass\nelse:\n for elements in list_objs:... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects = Base.__nb_objects + 1
self.id = Base.__nb_objects
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None:
return '[]'
else:
return json.dumps(list... | Class Base | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""Class Base"""
def __init__(self, id=None):
"""Function that initializes"""
<|body_0|>
def to_json_string(list_dictionaries):
"""Static method that returns JSON string representation"""
<|body_1|>
def save_to_file(cls, list_objs):
"""... | stack_v2_sparse_classes_36k_train_008834 | 2,243 | no_license | [
{
"docstring": "Function that initializes",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "Static method that returns JSON string representation",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docstring": "... | 6 | stack_v2_sparse_classes_30k_train_020409 | Implement the Python class `Base` described below.
Class description:
Class Base
Method signatures and docstrings:
- def __init__(self, id=None): Function that initializes
- def to_json_string(list_dictionaries): Static method that returns JSON string representation
- def save_to_file(cls, list_objs): Class method th... | Implement the Python class `Base` described below.
Class description:
Class Base
Method signatures and docstrings:
- def __init__(self, id=None): Function that initializes
- def to_json_string(list_dictionaries): Static method that returns JSON string representation
- def save_to_file(cls, list_objs): Class method th... | 6024909b7a4fc142f88159b021b5d482111648fc | <|skeleton|>
class Base:
"""Class Base"""
def __init__(self, id=None):
"""Function that initializes"""
<|body_0|>
def to_json_string(list_dictionaries):
"""Static method that returns JSON string representation"""
<|body_1|>
def save_to_file(cls, list_objs):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base:
"""Class Base"""
def __init__(self, id=None):
"""Function that initializes"""
if id is not None:
self.id = id
else:
Base.__nb_objects = Base.__nb_objects + 1
self.id = Base.__nb_objects
def to_json_string(list_dictionaries):
"... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | guilmeister/holbertonschool-higher_level_programming | train | 0 |
cad96d1039f8d8ca0cc96966fc5067676a146c64 | [
"if len(typed) == 0:\n return len(name) == len(typed) == 0\n\ndef change(typed):\n start = typed[0]\n t = []\n count = 1\n for char in typed[1:]:\n if char == start:\n count += 1\n else:\n t.append([start, count])\n count = 1\n start = char\n t... | <|body_start_0|>
if len(typed) == 0:
return len(name) == len(typed) == 0
def change(typed):
start = typed[0]
t = []
count = 1
for char in typed[1:]:
if char == start:
count += 1
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isLongPressedName(self, name, typed):
""":type name: str :type typed: str :rtype: bool 32 ms"""
<|body_0|>
def isLongPressedName_1(self, name, typed):
""":type name: str :type typed: str :rtype: bool 36ms"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_008835 | 2,873 | no_license | [
{
"docstring": ":type name: str :type typed: str :rtype: bool 32 ms",
"name": "isLongPressedName",
"signature": "def isLongPressedName(self, name, typed)"
},
{
"docstring": ":type name: str :type typed: str :rtype: bool 36ms",
"name": "isLongPressedName_1",
"signature": "def isLongPresse... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isLongPressedName(self, name, typed): :type name: str :type typed: str :rtype: bool 32 ms
- def isLongPressedName_1(self, name, typed): :type name: str :type typed: str :rtyp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isLongPressedName(self, name, typed): :type name: str :type typed: str :rtype: bool 32 ms
- def isLongPressedName_1(self, name, typed): :type name: str :type typed: str :rtyp... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def isLongPressedName(self, name, typed):
""":type name: str :type typed: str :rtype: bool 32 ms"""
<|body_0|>
def isLongPressedName_1(self, name, typed):
""":type name: str :type typed: str :rtype: bool 36ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isLongPressedName(self, name, typed):
""":type name: str :type typed: str :rtype: bool 32 ms"""
if len(typed) == 0:
return len(name) == len(typed) == 0
def change(typed):
start = typed[0]
t = []
count = 1
for ch... | the_stack_v2_python_sparse | LongPressedName_925.py | 953250587/leetcode-python | train | 2 | |
0f375f0f5bc5ff81b28b2302bee2d5b5a5954aac | [
"if not root:\n return []\ncurr_lvl = [root]\nres = [root.val]\nwhile curr_lvl:\n nxt_lvl = []\n for node in curr_lvl:\n if node.left:\n nxt_lvl.append(node.left)\n res.append(node.left.val)\n else:\n res.append(None)\n if node.right:\n nxt_l... | <|body_start_0|>
if not root:
return []
curr_lvl = [root]
res = [root.val]
while curr_lvl:
nxt_lvl = []
for node in curr_lvl:
if node.left:
nxt_lvl.append(node.left)
res.append(node.left.val)
... | 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_008836 | 4,842 | 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_016734 | 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:... | 63120dbaabd7c3c19633ebe952bcee4cf826b0e0 | <|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 []
curr_lvl = [root]
res = [root.val]
while curr_lvl:
nxt_lvl = []
for node in curr_lvl:
i... | the_stack_v2_python_sparse | 297. Serialize and Deserialize Binary Tree _ tee.py | CaizhiXu/LeetCode-Python-Solutions | train | 0 | |
945a70860fe757229246716a98013de787c4c0da | [
"for prog, _, func in self.lexmap:\n mo = prog.match(self.txt, self.pos)\n if mo:\n column = mo.start() - self.line_start\n length = mo.end() - mo.start()\n loc = SourceLocation(self.filename, self.line, column, length)\n self.pos = mo.end()\n val = mo.group(0)\n if '... | <|body_start_0|>
for prog, _, func in self.lexmap:
mo = prog.match(self.txt, self.pos)
if mo:
column = mo.start() - self.line_start
length = mo.end() - mo.start()
loc = SourceLocation(self.filename, self.line, column, length)
... | Simple class for lexing. Use this class by subclassing it and decorating handler methods with the 'on' function. | SimpleLexer | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleLexer:
"""Simple class for lexing. Use this class by subclassing it and decorating handler methods with the 'on' function."""
def gettok(self):
"""Find a match at the given position"""
<|body_0|>
def tokenize(self, txt, eof=False):
"""Generator that generat... | stack_v2_sparse_classes_36k_train_008837 | 5,205 | permissive | [
{
"docstring": "Find a match at the given position",
"name": "gettok",
"signature": "def gettok(self)"
},
{
"docstring": "Generator that generates lexical tokens from text. Optionally yield the EOF token.",
"name": "tokenize",
"signature": "def tokenize(self, txt, eof=False)"
}
] | 2 | null | Implement the Python class `SimpleLexer` described below.
Class description:
Simple class for lexing. Use this class by subclassing it and decorating handler methods with the 'on' function.
Method signatures and docstrings:
- def gettok(self): Find a match at the given position
- def tokenize(self, txt, eof=False): G... | Implement the Python class `SimpleLexer` described below.
Class description:
Simple class for lexing. Use this class by subclassing it and decorating handler methods with the 'on' function.
Method signatures and docstrings:
- def gettok(self): Find a match at the given position
- def tokenize(self, txt, eof=False): G... | ba0840bc5f4ffd889f882a814fb26f88cd854379 | <|skeleton|>
class SimpleLexer:
"""Simple class for lexing. Use this class by subclassing it and decorating handler methods with the 'on' function."""
def gettok(self):
"""Find a match at the given position"""
<|body_0|>
def tokenize(self, txt, eof=False):
"""Generator that generat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleLexer:
"""Simple class for lexing. Use this class by subclassing it and decorating handler methods with the 'on' function."""
def gettok(self):
"""Find a match at the given position"""
for prog, _, func in self.lexmap:
mo = prog.match(self.txt, self.pos)
if m... | the_stack_v2_python_sparse | ppci/lang/tools/baselex.py | obround/ppci | train | 0 |
74ba213d4fab33b0a7cfabe35671d93818512ca4 | [
"self.mu_g = mu_g\nself.s_g = s_g\nself.s_s = s_s\nself.h = h\nself.alpha = alpha",
"assert len(f1.shape) == 1, 'input must be 1d ndarray'\nassert len(f2.shape) == 1, 'input must be 1d ndarray'\nassert f1.shape == f2.shape\nn_trial = len(f1)\nf1_ = np.tile(f1, (n_samp, 1)) + self.s_s * np.random.randn(n_samp, n_t... | <|body_start_0|>
self.mu_g = mu_g
self.s_g = s_g
self.s_s = s_s
self.h = h
self.alpha = alpha
<|end_body_0|>
<|body_start_1|>
assert len(f1.shape) == 1, 'input must be 1d ndarray'
assert len(f2.shape) == 1, 'input must be 1d ndarray'
assert f1.shape == f2... | Same as recency model except that gaussian prior mean is set somewhere between - average of previous tones - long term prior mean | LocalGlobalModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalGlobalModel:
"""Same as recency model except that gaussian prior mean is set somewhere between - average of previous tones - long term prior mean"""
def __init__(self, mu_g, s_g, h, s_s, alpha=0.0):
"""Constructor :param mu_g: mean of gaussian part of unigauss :param s_g: std of... | stack_v2_sparse_classes_36k_train_008838 | 11,426 | no_license | [
{
"docstring": "Constructor :param mu_g: mean of gaussian part of unigauss :param s_g: std of gaussian part of unigauss :param h: weight of flat prior in unigauss mixture assuming unnormalized gaussian p(x) 1/Z*( h + exp((x-mu)/2/s^2) ) :param s_s: std of likelihood :param alpha: interpolation factor 1=local,0=... | 2 | stack_v2_sparse_classes_30k_train_016686 | Implement the Python class `LocalGlobalModel` described below.
Class description:
Same as recency model except that gaussian prior mean is set somewhere between - average of previous tones - long term prior mean
Method signatures and docstrings:
- def __init__(self, mu_g, s_g, h, s_s, alpha=0.0): Constructor :param m... | Implement the Python class `LocalGlobalModel` described below.
Class description:
Same as recency model except that gaussian prior mean is set somewhere between - average of previous tones - long term prior mean
Method signatures and docstrings:
- def __init__(self, mu_g, s_g, h, s_s, alpha=0.0): Constructor :param m... | 2a05aa98b501c8633e1fe2baf611d137740709de | <|skeleton|>
class LocalGlobalModel:
"""Same as recency model except that gaussian prior mean is set somewhere between - average of previous tones - long term prior mean"""
def __init__(self, mu_g, s_g, h, s_s, alpha=0.0):
"""Constructor :param mu_g: mean of gaussian part of unigauss :param s_g: std of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalGlobalModel:
"""Same as recency model except that gaussian prior mean is set somewhere between - average of previous tones - long term prior mean"""
def __init__(self, mu_g, s_g, h, s_s, alpha=0.0):
"""Constructor :param mu_g: mean of gaussian part of unigauss :param s_g: std of gaussian par... | the_stack_v2_python_sparse | model/simple_model.py | ItayLieder/GMM_simulations | train | 0 |
c3f07b8e249cc7196e8883b64da882ce4c5aa5f8 | [
"m = len(grid)\nn = len(grid[0])\ndp = [[0] * n for _ in range(m)]\ndp[0][0] = grid[0][0]\nfor i in range(1, m):\n dp[i][0] = grid[i][0] + dp[i - 1][0]\nfor i in range(1, n):\n dp[0][i] = grid[0][i] + dp[0][i - 1]\nfor i in range(1, m):\n for j in range(1, n):\n dp[i][j] = min(dp[i - 1][j], dp[i][j ... | <|body_start_0|>
m = len(grid)
n = len(grid[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = grid[0][0]
for i in range(1, m):
dp[i][0] = grid[i][0] + dp[i - 1][0]
for i in range(1, n):
dp[0][i] = grid[0][i] + dp[0][i - 1]
for i in range(1, m... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minPathSum1(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = len(grid)
n = len(grid... | stack_v2_sparse_classes_36k_train_008839 | 1,246 | no_license | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum1",
"signature": "def minPathSum1(self, grid)"
},
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum",
"signature": "def minPathSum(self, grid)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum1(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum1(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
<|skeleton|>
class Solution:
def ... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def minPathSum1(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minPathSum1(self, grid):
""":type grid: List[List[int]] :rtype: int"""
m = len(grid)
n = len(grid[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = grid[0][0]
for i in range(1, m):
dp[i][0] = grid[i][0] + dp[i - 1][0]
for i in ran... | the_stack_v2_python_sparse | DynamicProgramming/q064_minimum_path_sum.py | sevenhe716/LeetCode | train | 0 | |
5377d0c89a8e8fe48a39bb554a973ba1494f0f76 | [
"if not head or not head.next:\n return True\nslow = head\nfast = head.next\nwhile fast and fast.next:\n slow = slow.next\n fast = fast.next.next\nif fast:\n slow = slow.next\nhead1 = head\nwhile head.next != slow:\n head = head.next\nhead.next = None\nhead2 = self.reverseList(slow)\nwhile head1 and ... | <|body_start_0|>
if not head or not head.next:
return True
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast:
slow = slow.next
head1 = head
while head.next != slow:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or not head.next:
... | stack_v2_sparse_classes_36k_train_008840 | 2,063 | no_license | [
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def reverseList(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def isPali... | 8babc83cefc6722b9845f61ef5d15edc99648cb6 | <|skeleton|>
class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
if not head or not head.next:
return True
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast:
... | the_stack_v2_python_sparse | Python/234.palindrome-linked-list.py | zhoujf620/LeetCode-Practice | train | 0 | |
d8b37a686ef9e8dad507b9c0e276acbd212d1e67 | [
"try:\n resource, authorized, user = view_utils.authorize(request, pk, needed_permission=ACTION_TO_AUTHORIZE.VIEW_RESOURCE, raises_exception=False)\nexcept NotFound as ex:\n return Response(str(ex), status=status.HTTP_404_NOT_FOUND)\nif not authorized:\n return Response('Insufficient permission', status=st... | <|body_start_0|>
try:
resource, authorized, user = view_utils.authorize(request, pk, needed_permission=ACTION_TO_AUTHORIZE.VIEW_RESOURCE, raises_exception=False)
except NotFound as ex:
return Response(str(ex), status=status.HTTP_404_NOT_FOUND)
if not authorized:
... | list or delete a ticket Methods: GET, DELETE Returns: HTTP 200, 400, 403, 403 Example of a correct list request: GET /hsapi/resource/28f87079ceaf440588e7866a0f4b6c57/ticket/info/pwYwPanpnwdDZa9/ This returns HTTP_200_OK with content: {u'expires': u'2017-07-26.00:17:00', u'filename': u'28f87079ceaf440588e7866a0f4b6c57.z... | ManageResourceTicket | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManageResourceTicket:
"""list or delete a ticket Methods: GET, DELETE Returns: HTTP 200, 400, 403, 403 Example of a correct list request: GET /hsapi/resource/28f87079ceaf440588e7866a0f4b6c57/ticket/info/pwYwPanpnwdDZa9/ This returns HTTP_200_OK with content: {u'expires': u'2017-07-26.00:17:00', u... | stack_v2_sparse_classes_36k_train_008841 | 9,855 | permissive | [
{
"docstring": "list a ticket",
"name": "get",
"signature": "def get(self, request, pk, ticket)"
},
{
"docstring": "Delete a ticket.",
"name": "delete",
"signature": "def delete(self, request, pk, ticket)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004441 | Implement the Python class `ManageResourceTicket` described below.
Class description:
list or delete a ticket Methods: GET, DELETE Returns: HTTP 200, 400, 403, 403 Example of a correct list request: GET /hsapi/resource/28f87079ceaf440588e7866a0f4b6c57/ticket/info/pwYwPanpnwdDZa9/ This returns HTTP_200_OK with content:... | Implement the Python class `ManageResourceTicket` described below.
Class description:
list or delete a ticket Methods: GET, DELETE Returns: HTTP 200, 400, 403, 403 Example of a correct list request: GET /hsapi/resource/28f87079ceaf440588e7866a0f4b6c57/ticket/info/pwYwPanpnwdDZa9/ This returns HTTP_200_OK with content:... | 69855813052243c702c9b0108d2eac3f4f1a768f | <|skeleton|>
class ManageResourceTicket:
"""list or delete a ticket Methods: GET, DELETE Returns: HTTP 200, 400, 403, 403 Example of a correct list request: GET /hsapi/resource/28f87079ceaf440588e7866a0f4b6c57/ticket/info/pwYwPanpnwdDZa9/ This returns HTTP_200_OK with content: {u'expires': u'2017-07-26.00:17:00', u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManageResourceTicket:
"""list or delete a ticket Methods: GET, DELETE Returns: HTTP 200, 400, 403, 403 Example of a correct list request: GET /hsapi/resource/28f87079ceaf440588e7866a0f4b6c57/ticket/info/pwYwPanpnwdDZa9/ This returns HTTP_200_OK with content: {u'expires': u'2017-07-26.00:17:00', u'filename': u... | the_stack_v2_python_sparse | hs_core/views/resource_ticket_rest_api.py | hydroshare/hydroshare | train | 207 |
0a67aac55415940cf6dcaac938d76800a8a256be | [
"depth_arr = deque()\ndepth_arr.append(root)\nreturn self.findDepthSum(depth_arr, 0, 0)",
"if not depth_arr:\n return prev_total\nnew_depth_arr = deque()\ndepth_total = 0\nwhile depth_arr:\n node = depth_arr.popleft()\n depth_total += node.val\n if node.left:\n new_depth_arr.append(node.left)\n... | <|body_start_0|>
depth_arr = deque()
depth_arr.append(root)
return self.findDepthSum(depth_arr, 0, 0)
<|end_body_0|>
<|body_start_1|>
if not depth_arr:
return prev_total
new_depth_arr = deque()
depth_total = 0
while depth_arr:
node = depth... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deepestLeavesSum(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def findDepthSum(self, depth_arr, prev_total, new_total):
"""Step through each depth keeping track of the sum"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_008842 | 1,041 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "deepestLeavesSum",
"signature": "def deepestLeavesSum(self, root)"
},
{
"docstring": "Step through each depth keeping track of the sum",
"name": "findDepthSum",
"signature": "def findDepthSum(self, depth_arr, prev_total, new_tot... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deepestLeavesSum(self, root): :type root: TreeNode :rtype: int
- def findDepthSum(self, depth_arr, prev_total, new_total): Step through each depth keeping track of the sum | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deepestLeavesSum(self, root): :type root: TreeNode :rtype: int
- def findDepthSum(self, depth_arr, prev_total, new_total): Step through each depth keeping track of the sum
<... | 07c76cf1387fec433b9c63265cfc36a826a47f94 | <|skeleton|>
class Solution:
def deepestLeavesSum(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def findDepthSum(self, depth_arr, prev_total, new_total):
"""Step through each depth keeping track of the sum"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def deepestLeavesSum(self, root):
""":type root: TreeNode :rtype: int"""
depth_arr = deque()
depth_arr.append(root)
return self.findDepthSum(depth_arr, 0, 0)
def findDepthSum(self, depth_arr, prev_total, new_total):
"""Step through each depth keeping trac... | the_stack_v2_python_sparse | 1302DeepestLeavesSumRecursively.py | bragon9/leetcode | train | 0 | |
8276e1b589c31740fca51c035d2c0f21d9683078 | [
"if config is None:\n raise TypeError('Input parameter config is None')\nif isinstance(config, StubConfiguration):\n self._config = config\nelse:\n raise TypeError('Input parameter config is not a StubConfiguration')\nself._api_interface = api_interface(self._config)",
"kwargs = kwargs or {}\nctx = self.... | <|body_start_0|>
if config is None:
raise TypeError('Input parameter config is None')
if isinstance(config, StubConfiguration):
self._config = config
else:
raise TypeError('Input parameter config is not a StubConfiguration')
self._api_interface = api_i... | vAPI Interface class is used by the python client side bindings. This encapsulates the ApiInterfaceStub instance | VapiInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VapiInterface:
"""vAPI Interface class is used by the python client side bindings. This encapsulates the ApiInterfaceStub instance"""
def __init__(self, config, api_interface):
"""Initialize VapiInterface object :type config: :class:`StubConfiguration` :param config: Configuration da... | stack_v2_sparse_classes_36k_train_008843 | 16,678 | no_license | [
{
"docstring": "Initialize VapiInterface object :type config: :class:`StubConfiguration` :param config: Configuration data for vAPI stubs :type api_interface: :class:`ApiInterfaceStub` :param api_interface: Instance of ApiInterfaceStub class that can execute the ApiMethods",
"name": "__init__",
"signatu... | 2 | null | Implement the Python class `VapiInterface` described below.
Class description:
vAPI Interface class is used by the python client side bindings. This encapsulates the ApiInterfaceStub instance
Method signatures and docstrings:
- def __init__(self, config, api_interface): Initialize VapiInterface object :type config: :... | Implement the Python class `VapiInterface` described below.
Class description:
vAPI Interface class is used by the python client side bindings. This encapsulates the ApiInterfaceStub instance
Method signatures and docstrings:
- def __init__(self, config, api_interface): Initialize VapiInterface object :type config: :... | 5d395700ab3d0d1d45b497e48beab8c366fca9f5 | <|skeleton|>
class VapiInterface:
"""vAPI Interface class is used by the python client side bindings. This encapsulates the ApiInterfaceStub instance"""
def __init__(self, config, api_interface):
"""Initialize VapiInterface object :type config: :class:`StubConfiguration` :param config: Configuration da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VapiInterface:
"""vAPI Interface class is used by the python client side bindings. This encapsulates the ApiInterfaceStub instance"""
def __init__(self, config, api_interface):
"""Initialize VapiInterface object :type config: :class:`StubConfiguration` :param config: Configuration data for vAPI s... | the_stack_v2_python_sparse | alexa-program/vmware/vapi/bindings/stub.py | taromurata/TDP2018_VMCAPI | train | 1 |
6a163677610ac84225bfba4488e1d17aa3eb5af6 | [
"visited = set([0])\n\ndef dfs(i):\n for r in rooms[i]:\n if r not in visited:\n visited.add(r)\n dfs(r)\ndfs(0)\nreturn len(visited) == len(rooms)",
"n = len(rooms)\nvisited = [False] * n\nkeys = deque([0])\nwhile keys:\n key = keys.popleft()\n if visited[key]:\n cont... | <|body_start_0|>
visited = set([0])
def dfs(i):
for r in rooms[i]:
if r not in visited:
visited.add(r)
dfs(r)
dfs(0)
return len(visited) == len(rooms)
<|end_body_0|>
<|body_start_1|>
n = len(rooms)
visi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Sep 26, 2020 15:10"""
<|body_0|>
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Feb 19, 2023 17:13"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
visited = set... | stack_v2_sparse_classes_36k_train_008844 | 2,415 | no_license | [
{
"docstring": "Sep 26, 2020 15:10",
"name": "canVisitAllRooms",
"signature": "def canVisitAllRooms(self, rooms: List[List[int]]) -> bool"
},
{
"docstring": "Feb 19, 2023 17:13",
"name": "canVisitAllRooms",
"signature": "def canVisitAllRooms(self, rooms: List[List[int]]) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_017432 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: Sep 26, 2020 15:10
- def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: Feb 19, 2023 17:13 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: Sep 26, 2020 15:10
- def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: Feb 19, 2023 17:13
<|skeleton|>
clas... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Sep 26, 2020 15:10"""
<|body_0|>
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Feb 19, 2023 17:13"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Sep 26, 2020 15:10"""
visited = set([0])
def dfs(i):
for r in rooms[i]:
if r not in visited:
visited.add(r)
dfs(r)
dfs(0)
return... | the_stack_v2_python_sparse | leetcode/solved/871_Keys_and_Rooms/solution.py | sungminoh/algorithms | train | 0 | |
ef42eda96574711369ea418e2bb8fbcf69f8b620 | [
"Gtk.Grid.__init__(self)\nself._position = position\nself._displayedChar = Gtk.Button()\nself._displayedChar.set_size_request(30, 40)\nself._displayedChar.add(Gtk.Label())\nself.attach(self._displayedChar, 0, 0, 2, 3)\nself._displayedChar.connect('clicked', self._onCellClicked)\nself.dot7 = BrlDot(7)\nself.dot8 = B... | <|body_start_0|>
Gtk.Grid.__init__(self)
self._position = position
self._displayedChar = Gtk.Button()
self._displayedChar.set_size_request(30, 40)
self._displayedChar.add(Gtk.Label())
self.attach(self._displayedChar, 0, 0, 2, 3)
self._displayedChar.connect('clicke... | A single graphical braille cell with cursor routing capability. | BrlCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrlCell:
"""A single graphical braille cell with cursor routing capability."""
def __init__(self, position):
"""Create a new BrlCell. Arguments: - position: The location of the cell with respect to the monitor."""
<|body_0|>
def _onCellClicked(self, widget):
"""C... | stack_v2_sparse_classes_36k_train_008845 | 7,254 | no_license | [
{
"docstring": "Create a new BrlCell. Arguments: - position: The location of the cell with respect to the monitor.",
"name": "__init__",
"signature": "def __init__(self, position)"
},
{
"docstring": "Callback for the 'clicked' signal on the push button. Synthesizes a fake brlapi command to route... | 4 | stack_v2_sparse_classes_30k_train_008224 | Implement the Python class `BrlCell` described below.
Class description:
A single graphical braille cell with cursor routing capability.
Method signatures and docstrings:
- def __init__(self, position): Create a new BrlCell. Arguments: - position: The location of the cell with respect to the monitor.
- def _onCellCli... | Implement the Python class `BrlCell` described below.
Class description:
A single graphical braille cell with cursor routing capability.
Method signatures and docstrings:
- def __init__(self, position): Create a new BrlCell. Arguments: - position: The location of the cell with respect to the monitor.
- def _onCellCli... | 6976d7e1d8af45b1432cbf4f1461076ca04349e0 | <|skeleton|>
class BrlCell:
"""A single graphical braille cell with cursor routing capability."""
def __init__(self, position):
"""Create a new BrlCell. Arguments: - position: The location of the cell with respect to the monitor."""
<|body_0|>
def _onCellClicked(self, widget):
"""C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrlCell:
"""A single graphical braille cell with cursor routing capability."""
def __init__(self, position):
"""Create a new BrlCell. Arguments: - position: The location of the cell with respect to the monitor."""
Gtk.Grid.__init__(self)
self._position = position
self._dis... | the_stack_v2_python_sparse | rootfs/usr/lib64/python2.7/site-packages/orca/brlmon.py | outstanding-mjy/make_rootfs | train | 0 |
01fb4211687671edf0e5e8ec37738aa2c4cb3f2b | [
"gui = self.gui\nif self.start():\n window = self.workbench.create_window(position=self.window_position, size=self.window_size)\n window.open()\n if self.start_gui_event_loop:\n gui.start_event_loop()\nreturn",
"from cviewer.version import version\nadds = ['ConnectomeViewer BETA - Version %s' % ve... | <|body_start_0|>
gui = self.gui
if self.start():
window = self.workbench.create_window(position=self.window_position, size=self.window_size)
window.open()
if self.start_gui_event_loop:
gui.start_event_loop()
return
<|end_body_0|>
<|body_start_... | The ConnectoneViewer workbench application. | CViewerWorkbenchApplication | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CViewerWorkbenchApplication:
"""The ConnectoneViewer workbench application."""
def run(self):
"""Run the application. This does the following: 1) Starts the application 2) Creates and opens a workbench window 3) Starts the GUI event loop (only if start_gui_event_loop is True) 4) When... | stack_v2_sparse_classes_36k_train_008846 | 4,476 | no_license | [
{
"docstring": "Run the application. This does the following: 1) Starts the application 2) Creates and opens a workbench window 3) Starts the GUI event loop (only if start_gui_event_loop is True) 4) When the event loop terminates, stops the application This particular method is overridden from the parent class ... | 3 | stack_v2_sparse_classes_30k_val_000588 | Implement the Python class `CViewerWorkbenchApplication` described below.
Class description:
The ConnectoneViewer workbench application.
Method signatures and docstrings:
- def run(self): Run the application. This does the following: 1) Starts the application 2) Creates and opens a workbench window 3) Starts the GUI ... | Implement the Python class `CViewerWorkbenchApplication` described below.
Class description:
The ConnectoneViewer workbench application.
Method signatures and docstrings:
- def run(self): Run the application. This does the following: 1) Starts the application 2) Creates and opens a workbench window 3) Starts the GUI ... | 2c2c81b0cf786f8a22d35c184f97abcb24fc4a8e | <|skeleton|>
class CViewerWorkbenchApplication:
"""The ConnectoneViewer workbench application."""
def run(self):
"""Run the application. This does the following: 1) Starts the application 2) Creates and opens a workbench window 3) Starts the GUI event loop (only if start_gui_event_loop is True) 4) When... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CViewerWorkbenchApplication:
"""The ConnectoneViewer workbench application."""
def run(self):
"""Run the application. This does the following: 1) Starts the application 2) Creates and opens a workbench window 3) Starts the GUI event loop (only if start_gui_event_loop is True) 4) When the event lo... | the_stack_v2_python_sparse | cviewer/cviewer_workbench_application.py | satra/connectomeviewer | train | 1 |
a5a2f5a58e879ede6feed9bb416561e846babf56 | [
"global logger\nlogger = utils.get_logger('ui.views.purchase_view')\nself.view_all()",
"PRODUCT_VIEW_COLUMNS = ('Purchase ID', '# Items', 'Total', 'Date')\nPURCHASES_TABLE = 'Purchases'\nentries = [[str(item) for item in purchase] for purchase in self.db.get_entries(PURCHASES_TABLE)]\nself.view_purchases(entries)... | <|body_start_0|>
global logger
logger = utils.get_logger('ui.views.purchase_view')
self.view_all()
<|end_body_0|>
<|body_start_1|>
PRODUCT_VIEW_COLUMNS = ('Purchase ID', '# Items', 'Total', 'Date')
PURCHASES_TABLE = 'Purchases'
entries = [[str(item) for item in purchase]... | View purchases | PurchaseView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PurchaseView:
"""View purchases"""
def show_view(self):
"""Implement the abstrect method show_view"""
<|body_0|>
def view_all(self):
"""View all the records in Purchases table"""
<|body_1|>
def by_year(self):
"""View Purchases from a certin y... | stack_v2_sparse_classes_36k_train_008847 | 6,067 | no_license | [
{
"docstring": "Implement the abstrect method show_view",
"name": "show_view",
"signature": "def show_view(self)"
},
{
"docstring": "View all the records in Purchases table",
"name": "view_all",
"signature": "def view_all(self)"
},
{
"docstring": "View Purchases from a certin yea... | 6 | stack_v2_sparse_classes_30k_val_000037 | Implement the Python class `PurchaseView` described below.
Class description:
View purchases
Method signatures and docstrings:
- def show_view(self): Implement the abstrect method show_view
- def view_all(self): View all the records in Purchases table
- def by_year(self): View Purchases from a certin year
- def by_mo... | Implement the Python class `PurchaseView` described below.
Class description:
View purchases
Method signatures and docstrings:
- def show_view(self): Implement the abstrect method show_view
- def view_all(self): View all the records in Purchases table
- def by_year(self): View Purchases from a certin year
- def by_mo... | 53949593c11c6a152929ce4eca5e63b4efc74aad | <|skeleton|>
class PurchaseView:
"""View purchases"""
def show_view(self):
"""Implement the abstrect method show_view"""
<|body_0|>
def view_all(self):
"""View all the records in Purchases table"""
<|body_1|>
def by_year(self):
"""View Purchases from a certin y... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PurchaseView:
"""View purchases"""
def show_view(self):
"""Implement the abstrect method show_view"""
global logger
logger = utils.get_logger('ui.views.purchase_view')
self.view_all()
def view_all(self):
"""View all the records in Purchases table"""
PR... | the_stack_v2_python_sparse | ui/Views/purchase_view.py | OzTamir/Databases-Project | train | 2 |
a15d5df0346eff0279f6d5fad528dfa9ba231ca8 | [
"ufo.app.logger.info('Starting user sync.')\ndb_users = models.User.query.all()\ndirectory_users = {}\nconfig = ufo.get_user_config()\nwith ufo.app.app_context():\n credentials = oauth.getSavedCredentials()\n if not credentials:\n ufo.app.logger.info(\"OAuth credentials not set up. Can't sync users.\")... | <|body_start_0|>
ufo.app.logger.info('Starting user sync.')
db_users = models.User.query.all()
directory_users = {}
config = ufo.get_user_config()
with ufo.app.app_context():
credentials = oauth.getSavedCredentials()
if not credentials:
ufo... | Syncs users in the db's status with Google directory service. | UserSynchronizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSynchronizer:
"""Syncs users in the db's status with Google directory service."""
def sync_db_users_against_directory_service(self):
"""Checks whether the users currently in the DB are still valid. This gets all users in the DB, finds those that match the current domain, and comp... | stack_v2_sparse_classes_36k_train_008848 | 3,399 | permissive | [
{
"docstring": "Checks whether the users currently in the DB are still valid. This gets all users in the DB, finds those that match the current domain, and compares them to those found in the domain in Google Directory Service. If a user in the DB is not the domain, then it is presumed to be deleted and will th... | 2 | stack_v2_sparse_classes_30k_train_001829 | Implement the Python class `UserSynchronizer` described below.
Class description:
Syncs users in the db's status with Google directory service.
Method signatures and docstrings:
- def sync_db_users_against_directory_service(self): Checks whether the users currently in the DB are still valid. This gets all users in th... | Implement the Python class `UserSynchronizer` described below.
Class description:
Syncs users in the db's status with Google directory service.
Method signatures and docstrings:
- def sync_db_users_against_directory_service(self): Checks whether the users currently in the DB are still valid. This gets all users in th... | a9efb83cfa3a5aa26bf3c4012ca0ef99b6e67829 | <|skeleton|>
class UserSynchronizer:
"""Syncs users in the db's status with Google directory service."""
def sync_db_users_against_directory_service(self):
"""Checks whether the users currently in the DB are still valid. This gets all users in the DB, finds those that match the current domain, and comp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSynchronizer:
"""Syncs users in the db's status with Google directory service."""
def sync_db_users_against_directory_service(self):
"""Checks whether the users currently in the DB are still valid. This gets all users in the DB, finds those that match the current domain, and compares them to ... | the_stack_v2_python_sparse | ufo/services/user_synchronizer.py | UWNetworksLab/ufo-management-server-flask | train | 0 |
925058d1e6aae973e51f0902c741c798245a3641 | [
"args = utils.get_args_raw(message).replace(' ', '+')\nawait message.edit('Узнаем погоду...')\ncity = requests.get(f\"https://wttr.in/{(args if args != None else '')}.png\").content\nawait message.client.send_file(message.to_id, city)\nawait message.delete()",
"city = utils.get_args_raw(message)\nawait message.ed... | <|body_start_0|>
args = utils.get_args_raw(message).replace(' ', '+')
await message.edit('Узнаем погоду...')
city = requests.get(f"https://wttr.in/{(args if args != None else '')}.png").content
await message.client.send_file(message.to_id, city)
await message.delete()
<|end_body_... | Погода с сайта wttr.in | WeatherMod | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeatherMod:
"""Погода с сайта wttr.in"""
async def pwcmd(self, message):
""""Кидает погоду картинкой. Использование: .pw <город>; ничего."""
<|body_0|>
async def awcmd(self, message):
"""Кидает погоду ascii-артом. Использование: .aw <город>; ничего."""
<|... | stack_v2_sparse_classes_36k_train_008849 | 1,106 | no_license | [
{
"docstring": "\"Кидает погоду картинкой. Использование: .pw <город>; ничего.",
"name": "pwcmd",
"signature": "async def pwcmd(self, message)"
},
{
"docstring": "Кидает погоду ascii-артом. Использование: .aw <город>; ничего.",
"name": "awcmd",
"signature": "async def awcmd(self, message... | 2 | stack_v2_sparse_classes_30k_train_018185 | Implement the Python class `WeatherMod` described below.
Class description:
Погода с сайта wttr.in
Method signatures and docstrings:
- async def pwcmd(self, message): "Кидает погоду картинкой. Использование: .pw <город>; ничего.
- async def awcmd(self, message): Кидает погоду ascii-артом. Использование: .aw <город>; ... | Implement the Python class `WeatherMod` described below.
Class description:
Погода с сайта wttr.in
Method signatures and docstrings:
- async def pwcmd(self, message): "Кидает погоду картинкой. Использование: .pw <город>; ничего.
- async def awcmd(self, message): Кидает погоду ascii-артом. Использование: .aw <город>; ... | a29db28872a452fcc48445279aff58e676dd0e3c | <|skeleton|>
class WeatherMod:
"""Погода с сайта wttr.in"""
async def pwcmd(self, message):
""""Кидает погоду картинкой. Использование: .pw <город>; ничего."""
<|body_0|>
async def awcmd(self, message):
"""Кидает погоду ascii-артом. Использование: .aw <город>; ничего."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeatherMod:
"""Погода с сайта wttr.in"""
async def pwcmd(self, message):
""""Кидает погоду картинкой. Использование: .pw <город>; ничего."""
args = utils.get_args_raw(message).replace(' ', '+')
await message.edit('Узнаем погоду...')
city = requests.get(f"https://wttr.in/{(... | the_stack_v2_python_sparse | weather.py | Fl1yd/FTG-Modules | train | 6 |
a8ef28be87004bcd6d936df1350d6bbdea4b415c | [
"super(Decoder, self).__init__()\nself.dec_units = dec_units\nself.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\nself.gru = tf.keras.layers.GRU(self.dec_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform', recurrent_dropout=dropout)\nself.fc = tf.keras.layers.... | <|body_start_0|>
super(Decoder, self).__init__()
self.dec_units = dec_units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.gru = tf.keras.layers.GRU(self.dec_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform', recurrent_dro... | Decoder of the gru with attention model. | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Decoder of the gru with attention model."""
def __init__(self, vocab_size, embedding_dim, dec_units, dropout):
"""Create the decoder."""
<|body_0|>
def call(self, x, hidden, enc_output, training):
"""Call the foward past. Note that the call must be fo... | stack_v2_sparse_classes_36k_train_008850 | 8,984 | no_license | [
{
"docstring": "Create the decoder.",
"name": "__init__",
"signature": "def __init__(self, vocab_size, embedding_dim, dec_units, dropout)"
},
{
"docstring": "Call the foward past. Note that the call must be for one caracter/word at a time.",
"name": "call",
"signature": "def call(self, x... | 2 | stack_v2_sparse_classes_30k_train_007633 | Implement the Python class `Decoder` described below.
Class description:
Decoder of the gru with attention model.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, dec_units, dropout): Create the decoder.
- def call(self, x, hidden, enc_output, training): Call the foward past. Note tha... | Implement the Python class `Decoder` described below.
Class description:
Decoder of the gru with attention model.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, dec_units, dropout): Create the decoder.
- def call(self, x, hidden, enc_output, training): Call the foward past. Note tha... | 4502d9e7461520664e72165a91bedd8e65464bae | <|skeleton|>
class Decoder:
"""Decoder of the gru with attention model."""
def __init__(self, vocab_size, embedding_dim, dec_units, dropout):
"""Create the decoder."""
<|body_0|>
def call(self, x, hidden, enc_output, training):
"""Call the foward past. Note that the call must be fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""Decoder of the gru with attention model."""
def __init__(self, vocab_size, embedding_dim, dec_units, dropout):
"""Create the decoder."""
super(Decoder, self).__init__()
self.dec_units = dec_units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_... | the_stack_v2_python_sparse | src/model/gru_attention.py | nathanielsimard/Low-Resource-Machine-Translation | train | 0 |
83ed12139ab57f61824f81ee8c14c3edb4b06bdb | [
"stack, rslt = (root and [root], [])\nwhile stack:\n currNode = stack.pop()\n rslt.append(currNode.val)\n stack.extend(reversed(currNode.children or []))\nreturn rslt",
"rslt = []\nif root:\n rslt.append(root.val)\n for child in root.children:\n rslt.extend(self.preorder2(child))\nreturn rsl... | <|body_start_0|>
stack, rslt = (root and [root], [])
while stack:
currNode = stack.pop()
rslt.append(currNode.val)
stack.extend(reversed(currNode.children or []))
return rslt
<|end_body_0|>
<|body_start_1|>
rslt = []
if root:
rslt.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorder(self, root: NaryTreeNode) -> List[int]:
"""Use iteration."""
<|body_0|>
def preorder2(self, root: NaryTreeNode) -> List[int]:
"""Use recursion."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stack, rslt = (root and [root], []... | stack_v2_sparse_classes_36k_train_008851 | 760 | no_license | [
{
"docstring": "Use iteration.",
"name": "preorder",
"signature": "def preorder(self, root: NaryTreeNode) -> List[int]"
},
{
"docstring": "Use recursion.",
"name": "preorder2",
"signature": "def preorder2(self, root: NaryTreeNode) -> List[int]"
}
] | 2 | stack_v2_sparse_classes_30k_train_001234 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorder(self, root: NaryTreeNode) -> List[int]: Use iteration.
- def preorder2(self, root: NaryTreeNode) -> List[int]: Use recursion. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorder(self, root: NaryTreeNode) -> List[int]: Use iteration.
- def preorder2(self, root: NaryTreeNode) -> List[int]: Use recursion.
<|skeleton|>
class Solution:
def ... | edb870f83f0c4568cce0cacec04ee70cf6b545bf | <|skeleton|>
class Solution:
def preorder(self, root: NaryTreeNode) -> List[int]:
"""Use iteration."""
<|body_0|>
def preorder2(self, root: NaryTreeNode) -> List[int]:
"""Use recursion."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def preorder(self, root: NaryTreeNode) -> List[int]:
"""Use iteration."""
stack, rslt = (root and [root], [])
while stack:
currNode = stack.pop()
rslt.append(currNode.val)
stack.extend(reversed(currNode.children or []))
return rslt
... | the_stack_v2_python_sparse | 2020/n_ary_tree_preorder_traversal.py | eronekogin/leetcode | train | 0 | |
4461b2eba907b9afb6292ad0ef79f692485cc5db | [
"super(ClassificationTaskModel, self).__init__()\nmodel_type = model_config.get('model_type', 'transformer')\nhidden_size = model_config.get('hidden_size', 512)\nin_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size\nself.fc_decoder = nn.Sequential(nn.Linear(in_features=in_channels, out_features=51... | <|body_start_0|>
super(ClassificationTaskModel, self).__init__()
model_type = model_config.get('model_type', 'transformer')
hidden_size = model_config.get('hidden_size', 512)
in_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size
self.fc_decoder = nn.Sequential(nn... | ClassificationTaskModel | ClassificationTaskModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassificationTaskModel:
"""ClassificationTaskModel"""
def __init__(self, class_num, model_config, encoder_model):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Classifi... | stack_v2_sparse_classes_36k_train_008852 | 17,522 | permissive | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self, class_num, model_config, encoder_model)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, input, pos)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002403 | Implement the Python class `ClassificationTaskModel` described below.
Class description:
ClassificationTaskModel
Method signatures and docstrings:
- def __init__(self, class_num, model_config, encoder_model): __init__
- def forward(self, input, pos): forward | Implement the Python class `ClassificationTaskModel` described below.
Class description:
ClassificationTaskModel
Method signatures and docstrings:
- def __init__(self, class_num, model_config, encoder_model): __init__
- def forward(self, input, pos): forward
<|skeleton|>
class ClassificationTaskModel:
"""Classif... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class ClassificationTaskModel:
"""ClassificationTaskModel"""
def __init__(self, class_num, model_config, encoder_model):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassificationTaskModel:
"""ClassificationTaskModel"""
def __init__(self, class_num, model_config, encoder_model):
"""__init__"""
super(ClassificationTaskModel, self).__init__()
model_type = model_config.get('model_type', 'transformer')
hidden_size = model_config.get('hidd... | the_stack_v2_python_sparse | pahelix/model_zoo/protein_sequence_model.py | PaddlePaddle/PaddleHelix | train | 771 |
0bce5d590b96e434cd8aee7531a321bc648c1981 | [
"self.graph = graph\nself.parent = dict()\nself.dag = self.graph.__class__(self.graph.v(), directed=True)\nfor node in self.graph.iternodes():\n self.dag.add_node(node)",
"if source is not None:\n self._visit(source, pre_action, post_action)\nelse:\n for node in self.graph.iternodes():\n if node n... | <|body_start_0|>
self.graph = graph
self.parent = dict()
self.dag = self.graph.__class__(self.graph.v(), directed=True)
for node in self.graph.iternodes():
self.dag.add_node(node)
<|end_body_0|>
<|body_start_1|>
if source is not None:
self._visit(source, ... | Breadth-First Search. Attributes ---------- graph : input graph parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph >>> from graphtheory.traversing.bfs import SimpleBFS >>> G = Graph(n=10, False) # an exe... | SimpleBFS | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleBFS:
"""Breadth-First Search. Attributes ---------- graph : input graph parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph >>> from graphtheory.traversing.bfs import SimpleBF... | stack_v2_sparse_classes_36k_train_008853 | 6,370 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self, source=None, pre_action=None, post_action=None)"
},
{
"docstring": "Explore the conn... | 4 | stack_v2_sparse_classes_30k_train_000889 | Implement the Python class `SimpleBFS` described below.
Class description:
Breadth-First Search. Attributes ---------- graph : input graph parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph >>> from gra... | Implement the Python class `SimpleBFS` described below.
Class description:
Breadth-First Search. Attributes ---------- graph : input graph parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph >>> from gra... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class SimpleBFS:
"""Breadth-First Search. Attributes ---------- graph : input graph parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph >>> from graphtheory.traversing.bfs import SimpleBF... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleBFS:
"""Breadth-First Search. Attributes ---------- graph : input graph parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph >>> from graphtheory.traversing.bfs import SimpleBFS >>> G = Gra... | the_stack_v2_python_sparse | graphtheory/traversing/bfs.py | kgashok/graphs-dict | train | 0 |
0e324456ce8625f2fa22a1a85266f646beaf4f7e | [
"def backTrack(n, res, tmp, flag, row):\n if row == n:\n z = []\n for t in tmp:\n z.append(''.join(t))\n res.append(z)\n else:\n for col in range(n):\n if flag[row] and flag[n + col] and flag[2 * n + row + col] and flag[5 * n - 2 + col - row]:\n ... | <|body_start_0|>
def backTrack(n, res, tmp, flag, row):
if row == n:
z = []
for t in tmp:
z.append(''.join(t))
res.append(z)
else:
for col in range(n):
if flag[row] and flag[n + col] a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
<|body_0|>
def solveNQueens0(self, n):
""":type n: int :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def backTrack(n, res, tmp, flag, row):
... | stack_v2_sparse_classes_36k_train_008854 | 2,064 | no_license | [
{
"docstring": ":type n: int :rtype: List[List[str]]",
"name": "solveNQueens",
"signature": "def solveNQueens(self, n)"
},
{
"docstring": ":type n: int :rtype: List[List[str]]",
"name": "solveNQueens0",
"signature": "def solveNQueens0(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000771 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solveNQueens(self, n): :type n: int :rtype: List[List[str]]
- def solveNQueens0(self, n): :type n: int :rtype: List[List[str]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solveNQueens(self, n): :type n: int :rtype: List[List[str]]
- def solveNQueens0(self, n): :type n: int :rtype: List[List[str]]
<|skeleton|>
class Solution:
def solveNQu... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
<|body_0|>
def solveNQueens0(self, n):
""":type n: int :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
def backTrack(n, res, tmp, flag, row):
if row == n:
z = []
for t in tmp:
z.append(''.join(t))
res.append(z)
else:
... | the_stack_v2_python_sparse | PythonCode/src/0051_N-Queens.py | oneyuan/CodeforFun | train | 0 | |
a1cfb63f53c3ca948a0e9ee2d737b3392e2a9129 | [
"url = f'{self.code_cloud_api.branch_api}/{repo_name}/pull-requests/{pull_request_id}/comments'\nresponse = self.code_cloud_api.post(url=url, json_data={'text': comment}, cred_hash=cred_hash)\nresponse['data']['repo_name'] = repo_name\nreturn response",
"url = f'{self.code_cloud_api.branch_api}/{repo_name}/pull-r... | <|body_start_0|>
url = f'{self.code_cloud_api.branch_api}/{repo_name}/pull-requests/{pull_request_id}/comments'
response = self.code_cloud_api.post(url=url, json_data={'text': comment}, cred_hash=cred_hash)
response['data']['repo_name'] = repo_name
return response
<|end_body_0|>
<|body_... | Handles all comment actions for code cloud. | Comments | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Comments:
"""Handles all comment actions for code cloud."""
def add_comment_to_pull_request(self, repo_name, pull_request_id, comment, cred_hash):
"""Add a comment to a pull request."""
<|body_0|>
def get_activities(self, repo_name, pull_request_id, cred_hash):
"... | stack_v2_sparse_classes_36k_train_008855 | 853 | no_license | [
{
"docstring": "Add a comment to a pull request.",
"name": "add_comment_to_pull_request",
"signature": "def add_comment_to_pull_request(self, repo_name, pull_request_id, comment, cred_hash)"
},
{
"docstring": "Get the activity details for a pull request.",
"name": "get_activities",
"sign... | 2 | stack_v2_sparse_classes_30k_train_016069 | Implement the Python class `Comments` described below.
Class description:
Handles all comment actions for code cloud.
Method signatures and docstrings:
- def add_comment_to_pull_request(self, repo_name, pull_request_id, comment, cred_hash): Add a comment to a pull request.
- def get_activities(self, repo_name, pull_r... | Implement the Python class `Comments` described below.
Class description:
Handles all comment actions for code cloud.
Method signatures and docstrings:
- def add_comment_to_pull_request(self, repo_name, pull_request_id, comment, cred_hash): Add a comment to a pull request.
- def get_activities(self, repo_name, pull_r... | 52ba4eecd727c200f8ad82652434d171655c5f0a | <|skeleton|>
class Comments:
"""Handles all comment actions for code cloud."""
def add_comment_to_pull_request(self, repo_name, pull_request_id, comment, cred_hash):
"""Add a comment to a pull request."""
<|body_0|>
def get_activities(self, repo_name, pull_request_id, cred_hash):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Comments:
"""Handles all comment actions for code cloud."""
def add_comment_to_pull_request(self, repo_name, pull_request_id, comment, cred_hash):
"""Add a comment to a pull request."""
url = f'{self.code_cloud_api.branch_api}/{repo_name}/pull-requests/{pull_request_id}/comments'
... | the_stack_v2_python_sparse | devcenter/codecloud/comments.py | ljmerza/devCenter | train | 0 |
0b0340a48943e1e8f622985a01afa56f2ce4278b | [
"self.selected_year = kwargs.get('selected_year', datetime.now().year)\nassert str(self.selected_year).isdigit(), 'selected_year must be an integer'\nself.time_now = datetime.now()\nself.monthly_user_counts = []\nself.calculate_new_users()",
"for month_num in range(1, 13):\n if self.selected_year == self.time_... | <|body_start_0|>
self.selected_year = kwargs.get('selected_year', datetime.now().year)
assert str(self.selected_year).isdigit(), 'selected_year must be an integer'
self.time_now = datetime.now()
self.monthly_user_counts = []
self.calculate_new_users()
<|end_body_0|>
<|body_start... | MonthlyNewUserStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonthlyNewUserStats:
def __init__(self, **kwargs):
"""num_days = how many days back from today to count users who logged in"""
<|body_0|>
def calculate_new_users(self):
"""Calculate new user info for the given year"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_008856 | 4,273 | no_license | [
{
"docstring": "num_days = how many days back from today to count users who logged in",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Calculate new user info for the given year",
"name": "calculate_new_users",
"signature": "def calculate_new_users(sel... | 2 | stack_v2_sparse_classes_30k_train_008398 | Implement the Python class `MonthlyNewUserStats` described below.
Class description:
Implement the MonthlyNewUserStats class.
Method signatures and docstrings:
- def __init__(self, **kwargs): num_days = how many days back from today to count users who logged in
- def calculate_new_users(self): Calculate new user info... | Implement the Python class `MonthlyNewUserStats` described below.
Class description:
Implement the MonthlyNewUserStats class.
Method signatures and docstrings:
- def __init__(self, **kwargs): num_days = how many days back from today to count users who logged in
- def calculate_new_users(self): Calculate new user info... | 2a17e5ba918d6d1c7d38c192e0504e6cd96b32d2 | <|skeleton|>
class MonthlyNewUserStats:
def __init__(self, **kwargs):
"""num_days = how many days back from today to count users who logged in"""
<|body_0|>
def calculate_new_users(self):
"""Calculate new user info for the given year"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MonthlyNewUserStats:
def __init__(self, **kwargs):
"""num_days = how many days back from today to count users who logged in"""
self.selected_year = kwargs.get('selected_year', datetime.now().year)
assert str(self.selected_year).isdigit(), 'selected_year must be an integer'
self... | the_stack_v2_python_sparse | dv_apps/dataverse_auth/util_logins.py | IQSS/miniverse | train | 3 | |
4bd26a9c2cfd415e14a474cbc9fed01debf6c186 | [
"question = '你喜欢什么?'\nmy_answer = Wenjuan(question)\nmy_answer.tj_answer('money')\nself.assertIn('money', my_answer.answers)",
"question = '你喜欢的是什么?'\nmy_answer = Wenjuan(question)\nanswers = ['money', 'big', 'full']\nfor answer in answers:\n my_answer.tj_answer(answer)\nfor answer in answers:\n self.assert... | <|body_start_0|>
question = '你喜欢什么?'
my_answer = Wenjuan(question)
my_answer.tj_answer('money')
self.assertIn('money', my_answer.answers)
<|end_body_0|>
<|body_start_1|>
question = '你喜欢的是什么?'
my_answer = Wenjuan(question)
answers = ['money', 'big', 'full']
... | 针对类的测试 | TestWenjuan | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestWenjuan:
"""针对类的测试"""
def test_show_question(self):
"""测试单个答案是否被存储成功"""
<|body_0|>
def test_three_answer(self):
"""测试多个答案是否都被存储"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
question = '你喜欢什么?'
my_answer = Wenjuan(question)
... | stack_v2_sparse_classes_36k_train_008857 | 776 | no_license | [
{
"docstring": "测试单个答案是否被存储成功",
"name": "test_show_question",
"signature": "def test_show_question(self)"
},
{
"docstring": "测试多个答案是否都被存储",
"name": "test_three_answer",
"signature": "def test_three_answer(self)"
}
] | 2 | null | Implement the Python class `TestWenjuan` described below.
Class description:
针对类的测试
Method signatures and docstrings:
- def test_show_question(self): 测试单个答案是否被存储成功
- def test_three_answer(self): 测试多个答案是否都被存储 | Implement the Python class `TestWenjuan` described below.
Class description:
针对类的测试
Method signatures and docstrings:
- def test_show_question(self): 测试单个答案是否被存储成功
- def test_three_answer(self): 测试多个答案是否都被存储
<|skeleton|>
class TestWenjuan:
"""针对类的测试"""
def test_show_question(self):
"""测试单个答案是否被存储成功"... | 93fe784a3127e76995e9ae018605efbe78238385 | <|skeleton|>
class TestWenjuan:
"""针对类的测试"""
def test_show_question(self):
"""测试单个答案是否被存储成功"""
<|body_0|>
def test_three_answer(self):
"""测试多个答案是否都被存储"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestWenjuan:
"""针对类的测试"""
def test_show_question(self):
"""测试单个答案是否被存储成功"""
question = '你喜欢什么?'
my_answer = Wenjuan(question)
my_answer.tj_answer('money')
self.assertIn('money', my_answer.answers)
def test_three_answer(self):
"""测试多个答案是否都被存储"""
... | the_stack_v2_python_sparse | 学习笔记/yanzhengleifangfa.py | huangno27/learn | train | 0 |
4973df93e71c46326b7b21ffaa5220b55befbf3c | [
"super().__init__()\nprecision_range_lower = 0.0\nprecision_range_upper = 1.0\nself.num_classes = num_classes\nself.num_anchors = num_anchors\nself.precision_range = (precision_range_lower, precision_range_upper)\nprecision_values, self.delta = range_to_anchors_and_delta(self.precision_range, self.num_anchors)\nsel... | <|body_start_0|>
super().__init__()
precision_range_lower = 0.0
precision_range_upper = 1.0
self.num_classes = num_classes
self.num_anchors = num_anchors
self.precision_range = (precision_range_lower, precision_range_upper)
precision_values, self.delta = range_to_... | area under the precision-recall curve loss, Reference: "Scalable Learning of Non-Decomposable Objectives", Section 5 TensorFlow Implementation: https://github.com/tensorflow/models/tree/master/research/global_objectives | AUCPRHingeLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AUCPRHingeLoss:
"""area under the precision-recall curve loss, Reference: "Scalable Learning of Non-Decomposable Objectives", Section 5 TensorFlow Implementation: https://github.com/tensorflow/models/tree/master/research/global_objectives"""
def __init__(self, num_classes=1, num_anchors=20):... | stack_v2_sparse_classes_36k_train_008858 | 16,953 | no_license | [
{
"docstring": "Args: config: Config containing `precision_range_lower`, `precision_range_upper`, `num_classes`, `num_anchors`",
"name": "__init__",
"signature": "def __init__(self, num_classes=1, num_anchors=20)"
},
{
"docstring": "Args: logits: Variable :math:`(N, C)` where `C = number of clas... | 3 | stack_v2_sparse_classes_30k_train_010600 | Implement the Python class `AUCPRHingeLoss` described below.
Class description:
area under the precision-recall curve loss, Reference: "Scalable Learning of Non-Decomposable Objectives", Section 5 TensorFlow Implementation: https://github.com/tensorflow/models/tree/master/research/global_objectives
Method signatures ... | Implement the Python class `AUCPRHingeLoss` described below.
Class description:
area under the precision-recall curve loss, Reference: "Scalable Learning of Non-Decomposable Objectives", Section 5 TensorFlow Implementation: https://github.com/tensorflow/models/tree/master/research/global_objectives
Method signatures ... | ed667918b78184c658361b3bccf2d23cca1c76f3 | <|skeleton|>
class AUCPRHingeLoss:
"""area under the precision-recall curve loss, Reference: "Scalable Learning of Non-Decomposable Objectives", Section 5 TensorFlow Implementation: https://github.com/tensorflow/models/tree/master/research/global_objectives"""
def __init__(self, num_classes=1, num_anchors=20):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AUCPRHingeLoss:
"""area under the precision-recall curve loss, Reference: "Scalable Learning of Non-Decomposable Objectives", Section 5 TensorFlow Implementation: https://github.com/tensorflow/models/tree/master/research/global_objectives"""
def __init__(self, num_classes=1, num_anchors=20):
"""A... | the_stack_v2_python_sparse | src/model/loss.py | lming24/kaggle-melanoma | train | 0 |
af345c7c01a4192c919e5844b32bec2202118694 | [
"self.blank = blank\nself.eos = eos\nself.xlen = len(log_probs)\nself.log_probs = log_probs\nself.logzero = -10000000000.0",
"r = np.full((self.xlen, 2), self.logzero, dtype=np.float32)\nr[0, 1] = self.log_probs[0, self.blank]\nfor i in range(1, self.xlen):\n r[i, 1] = r[i - 1, 1] + self.log_probs[i, self.blan... | <|body_start_0|>
self.blank = blank
self.eos = eos
self.xlen = len(log_probs)
self.log_probs = log_probs
self.logzero = -10000000000.0
<|end_body_0|>
<|body_start_1|>
r = np.full((self.xlen, 2), self.logzero, dtype=np.float32)
r[0, 1] = self.log_probs[0, self.bla... | Compute CTC label sequence scores. which is based on Algorithm 2 in WATANABE et al. "HYBRID CTC/ATTENTION ARCHITECTURE FOR END-TO-END SPEECH RECOGNITION," but extended to efficiently compute the probablities of multiple labels simultaneously [Reference]: https://github.com/espnet/espnet | CTCPrefixScore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CTCPrefixScore:
"""Compute CTC label sequence scores. which is based on Algorithm 2 in WATANABE et al. "HYBRID CTC/ATTENTION ARCHITECTURE FOR END-TO-END SPEECH RECOGNITION," but extended to efficiently compute the probablities of multiple labels simultaneously [Reference]: https://github.com/espn... | stack_v2_sparse_classes_36k_train_008859 | 10,278 | no_license | [
{
"docstring": "Args: log_probs (): blank (int): index of <blank> eos (int): index of <eos>",
"name": "__init__",
"signature": "def __init__(self, log_probs, blank, eos)"
},
{
"docstring": "Obtain an initial CTC state :return: CTC state",
"name": "initial_state",
"signature": "def initia... | 3 | stack_v2_sparse_classes_30k_train_002660 | Implement the Python class `CTCPrefixScore` described below.
Class description:
Compute CTC label sequence scores. which is based on Algorithm 2 in WATANABE et al. "HYBRID CTC/ATTENTION ARCHITECTURE FOR END-TO-END SPEECH RECOGNITION," but extended to efficiently compute the probablities of multiple labels simultaneous... | Implement the Python class `CTCPrefixScore` described below.
Class description:
Compute CTC label sequence scores. which is based on Algorithm 2 in WATANABE et al. "HYBRID CTC/ATTENTION ARCHITECTURE FOR END-TO-END SPEECH RECOGNITION," but extended to efficiently compute the probablities of multiple labels simultaneous... | 852d523023de5baba717df2ac988b90f4131b5d7 | <|skeleton|>
class CTCPrefixScore:
"""Compute CTC label sequence scores. which is based on Algorithm 2 in WATANABE et al. "HYBRID CTC/ATTENTION ARCHITECTURE FOR END-TO-END SPEECH RECOGNITION," but extended to efficiently compute the probablities of multiple labels simultaneously [Reference]: https://github.com/espn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CTCPrefixScore:
"""Compute CTC label sequence scores. which is based on Algorithm 2 in WATANABE et al. "HYBRID CTC/ATTENTION ARCHITECTURE FOR END-TO-END SPEECH RECOGNITION," but extended to efficiently compute the probablities of multiple labels simultaneously [Reference]: https://github.com/espnet/espnet"""
... | the_stack_v2_python_sparse | neural_sp/models/seq2seq/decoders/ctc_beam_search.py | xdcesc/neural_sp | train | 1 |
95db5da1ab3df11c87f14faecbf61c03074635d9 | [
"base_list = base_dir.split('/')\nabsolute_list = file_path.split('/')\nwhile base_list:\n base_list = base_list[1:]\n absolute_list = absolute_list[1:]\nreturn '/'.join(absolute_list)",
"catalog_entry_data = []\nfor dir_path in catalog_metadata.get('paths'):\n base_dir = self.get_absolute_path(dir_path)... | <|body_start_0|>
base_list = base_dir.split('/')
absolute_list = file_path.split('/')
while base_list:
base_list = base_list[1:]
absolute_list = absolute_list[1:]
return '/'.join(absolute_list)
<|end_body_0|>
<|body_start_1|>
catalog_entry_data = []
... | Read component definitions from a local directory | DirectoryComponentCatalogConnector | [
"Apache-2.0",
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-SA-4.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectoryComponentCatalogConnector:
"""Read component definitions from a local directory"""
def get_relative_path_from_base(self, base_dir: str, file_path: str) -> str:
"""Determines the relative portion of a path from the given base directory. :param base_dir: the absolute path to a... | stack_v2_sparse_classes_36k_train_008860 | 30,890 | permissive | [
{
"docstring": "Determines the relative portion of a path from the given base directory. :param base_dir: the absolute path to a base directory to compare against :param file_path: the absolute path to a file within the given base directory :returns: the path to the given file relative to the given base directo... | 2 | stack_v2_sparse_classes_30k_train_008691 | Implement the Python class `DirectoryComponentCatalogConnector` described below.
Class description:
Read component definitions from a local directory
Method signatures and docstrings:
- def get_relative_path_from_base(self, base_dir: str, file_path: str) -> str: Determines the relative portion of a path from the give... | Implement the Python class `DirectoryComponentCatalogConnector` described below.
Class description:
Read component definitions from a local directory
Method signatures and docstrings:
- def get_relative_path_from_base(self, base_dir: str, file_path: str) -> str: Determines the relative portion of a path from the give... | 3c27ada25a27b719529e88268bed38d135e40805 | <|skeleton|>
class DirectoryComponentCatalogConnector:
"""Read component definitions from a local directory"""
def get_relative_path_from_base(self, base_dir: str, file_path: str) -> str:
"""Determines the relative portion of a path from the given base directory. :param base_dir: the absolute path to a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirectoryComponentCatalogConnector:
"""Read component definitions from a local directory"""
def get_relative_path_from_base(self, base_dir: str, file_path: str) -> str:
"""Determines the relative portion of a path from the given base directory. :param base_dir: the absolute path to a base directo... | the_stack_v2_python_sparse | elyra/pipeline/catalog_connector.py | elyra-ai/elyra | train | 1,707 |
b944d90d4784de8c2f92b8ac1bae26e5718db186 | [
"super(jfcEncoderNet, self).__init__()\ndense = []\nfor i in range(num_layers):\n input_dim = np.product(in_dim) if i == 0 else hidden_dim\n dense.extend([nn.Linear(input_dim, hidden_dim), nn.Tanh()])\nself.dense = nn.Sequential(*dense)\nself.reshape_ = hidden_dim\nself.fc11 = nn.Linear(self.reshape_, latent_... | <|body_start_0|>
super(jfcEncoderNet, self).__init__()
dense = []
for i in range(num_layers):
input_dim = np.product(in_dim) if i == 0 else hidden_dim
dense.extend([nn.Linear(input_dim, hidden_dim), nn.Tanh()])
self.dense = nn.Sequential(*dense)
self.resha... | Encoder/inference network (for variational autoencoder) Args: in_dim: Input dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions (the first 3 latent dimensions are angle & translations by default) num_layers: number of NN layers... | jfcEncoderNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class jfcEncoderNet:
"""Encoder/inference network (for variational autoencoder) Args: in_dim: Input dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions (the first 3 latent dimensions are angle & translations by... | stack_v2_sparse_classes_36k_train_008861 | 28,462 | permissive | [
{
"docstring": "Initializes network parameters",
"name": "__init__",
"signature": "def __init__(self, in_dim: Tuple[int], latent_dim: int=2, discrete_dim: List=[1], num_layers: int=2, hidden_dim: int=32, **kwargs: bool) -> None"
},
{
"docstring": "Forward pass",
"name": "forward",
"signa... | 2 | stack_v2_sparse_classes_30k_train_012575 | Implement the Python class `jfcEncoderNet` described below.
Class description:
Encoder/inference network (for variational autoencoder) Args: in_dim: Input dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions (the first 3 latent... | Implement the Python class `jfcEncoderNet` described below.
Class description:
Encoder/inference network (for variational autoencoder) Args: in_dim: Input dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions (the first 3 latent... | 6d187296074143d017ca8fc60302364cd946b180 | <|skeleton|>
class jfcEncoderNet:
"""Encoder/inference network (for variational autoencoder) Args: in_dim: Input dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions (the first 3 latent dimensions are angle & translations by... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class jfcEncoderNet:
"""Encoder/inference network (for variational autoencoder) Args: in_dim: Input dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions (the first 3 latent dimensions are angle & translations by default) num... | the_stack_v2_python_sparse | atomai/nets/ed.py | pycroscopy/atomai | train | 157 |
66ada6ea65123fbced34bdc40f09528f9a3898a8 | [
"if len(nums) == 1:\n return [nums]\nn = len(nums)\nrec = []\nfor i in range(n):\n res = self.permute(nums[:i] + nums[i + 1:])\n for r in res:\n a = [nums[i]] + r\n rec.append(a)\nreturn rec",
"res = []\nrec = self.permute(nums)\nfor r in rec:\n if r in res:\n continue\n res.ap... | <|body_start_0|>
if len(nums) == 1:
return [nums]
n = len(nums)
rec = []
for i in range(n):
res = self.permute(nums[:i] + nums[i + 1:])
for r in res:
a = [nums[i]] + r
rec.append(a)
return rec
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permute(self, nums):
"""leetcode 46 题题解 8.20 重做, 请好好反思 :type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteUnique(self, nums):
"""leetcode 47. Permutations II, 同题28 :type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_008862 | 2,030 | no_license | [
{
"docstring": "leetcode 46 题题解 8.20 重做, 请好好反思 :type nums: List[int] :rtype: List[List[int]]",
"name": "permute",
"signature": "def permute(self, nums)"
},
{
"docstring": "leetcode 47. Permutations II, 同题28 :type nums: List[int] :rtype: List[List[int]]",
"name": "permuteUnique",
"signatu... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums): leetcode 46 题题解 8.20 重做, 请好好反思 :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique(self, nums): leetcode 47. Permutations II, 同题28 :type nu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums): leetcode 46 题题解 8.20 重做, 请好好反思 :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique(self, nums): leetcode 47. Permutations II, 同题28 :type nu... | 8c0c2a8bcd51825e6902e4d03dabbaf6f303ba83 | <|skeleton|>
class Solution:
def permute(self, nums):
"""leetcode 46 题题解 8.20 重做, 请好好反思 :type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteUnique(self, nums):
"""leetcode 47. Permutations II, 同题28 :type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def permute(self, nums):
"""leetcode 46 题题解 8.20 重做, 请好好反思 :type nums: List[int] :rtype: List[List[int]]"""
if len(nums) == 1:
return [nums]
n = len(nums)
rec = []
for i in range(n):
res = self.permute(nums[:i] + nums[i + 1:])
... | the_stack_v2_python_sparse | python_fundemental/28_permutation.py | Deanwinger/python_project | train | 0 | |
fa76714830181e6c3b977d4e34b46f6101e5b10a | [
"self.start_all_services()\nclient = self.get_client('deproxy')\nclient.parsing = False\nfor length in range(1, 5):\n header = 'x' * length\n client.send_request(self.get_request + [(header, 'test')], '200')",
"self.start_all_services()\nclient = self.get_client('deproxy')\nclient.parsing = False\nclient.se... | <|body_start_0|>
self.start_all_services()
client = self.get_client('deproxy')
client.parsing = False
for length in range(1, 5):
header = 'x' * length
client.send_request(self.get_request + [(header, 'test')], '200')
<|end_body_0|>
<|body_start_1|>
self.s... | HeadersParsing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeadersParsing:
def test_small_header_in_request(self):
"""Request with small header name length completes successfully."""
<|body_0|>
def test_transfer_encoding_header_in_request(self):
"""The only exception to this is the TE header field, which MAY be present in an... | stack_v2_sparse_classes_36k_train_008863 | 49,368 | no_license | [
{
"docstring": "Request with small header name length completes successfully.",
"name": "test_small_header_in_request",
"signature": "def test_small_header_in_request(self)"
},
{
"docstring": "The only exception to this is the TE header field, which MAY be present in an HTTP/2 request; when it i... | 4 | stack_v2_sparse_classes_30k_train_010465 | Implement the Python class `HeadersParsing` described below.
Class description:
Implement the HeadersParsing class.
Method signatures and docstrings:
- def test_small_header_in_request(self): Request with small header name length completes successfully.
- def test_transfer_encoding_header_in_request(self): The only e... | Implement the Python class `HeadersParsing` described below.
Class description:
Implement the HeadersParsing class.
Method signatures and docstrings:
- def test_small_header_in_request(self): Request with small header name length completes successfully.
- def test_transfer_encoding_header_in_request(self): The only e... | d56358ea653dbb367624937197ce5e489abf0b00 | <|skeleton|>
class HeadersParsing:
def test_small_header_in_request(self):
"""Request with small header name length completes successfully."""
<|body_0|>
def test_transfer_encoding_header_in_request(self):
"""The only exception to this is the TE header field, which MAY be present in an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeadersParsing:
def test_small_header_in_request(self):
"""Request with small header name length completes successfully."""
self.start_all_services()
client = self.get_client('deproxy')
client.parsing = False
for length in range(1, 5):
header = 'x' * length
... | the_stack_v2_python_sparse | http2_general/test_h2_headers.py | tempesta-tech/tempesta-test | train | 13 | |
97a7a71507640e4392b8ba029febfab9a047e027 | [
"Module.__init__(self, **kws)\nself.images = []\nself.x, self.y, self.z = (0, 0, 0)\nself.extent = None\nself.running = 0\nself.depth = 8\nself.reset()",
"Module.reset(self)\nself.preview = None\nself.intensityTransferFunctions = []\nself.extent = None",
"Module.addInput(self, dataunit, data)\nsettings = dataun... | <|body_start_0|>
Module.__init__(self, **kws)
self.images = []
self.x, self.y, self.z = (0, 0, 0)
self.extent = None
self.running = 0
self.depth = 8
self.reset()
<|end_body_0|>
<|body_start_1|>
Module.reset(self)
self.preview = None
self.i... | Process a dataunit using an intensity transfer funtion | Adjust | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Adjust:
"""Process a dataunit using an intensity transfer funtion"""
def __init__(self, **kws):
"""Initialization"""
<|body_0|>
def reset(self):
"""Resets the module to initial state. This method is used mainly when doing previews, when the parameters that contro... | stack_v2_sparse_classes_36k_train_008864 | 3,725 | no_license | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, **kws)"
},
{
"docstring": "Resets the module to initial state. This method is used mainly when doing previews, when the parameters that control the colocalization are changed and the preview data becomes invali... | 5 | null | Implement the Python class `Adjust` described below.
Class description:
Process a dataunit using an intensity transfer funtion
Method signatures and docstrings:
- def __init__(self, **kws): Initialization
- def reset(self): Resets the module to initial state. This method is used mainly when doing previews, when the p... | Implement the Python class `Adjust` described below.
Class description:
Process a dataunit using an intensity transfer funtion
Method signatures and docstrings:
- def __init__(self, **kws): Initialization
- def reset(self): Resets the module to initial state. This method is used mainly when doing previews, when the p... | ea8bafa073de5090bd8f83fb4f5ca16669d0211f | <|skeleton|>
class Adjust:
"""Process a dataunit using an intensity transfer funtion"""
def __init__(self, **kws):
"""Initialization"""
<|body_0|>
def reset(self):
"""Resets the module to initial state. This method is used mainly when doing previews, when the parameters that contro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Adjust:
"""Process a dataunit using an intensity transfer funtion"""
def __init__(self, **kws):
"""Initialization"""
Module.__init__(self, **kws)
self.images = []
self.x, self.y, self.z = (0, 0, 0)
self.extent = None
self.running = 0
self.depth = 8
... | the_stack_v2_python_sparse | Graphs/LX-2/molecule_otsu = False/BioImageXD-1.0/Modules/Task/Adjust/Adjust.py | giacomo21/Image-analysis | train | 1 |
4253aa4ac0e41ca5e2fa9e00e54db78befc79d85 | [
"playbooks = self._client.get_playbooks(**kwargs)['items']\nif check:\n assert_that(playbooks, is_not(empty()))\nreturn playbooks",
"playbooks = self.get_playbooks(**kwargs)\nfor playbook in playbooks:\n if playbook['id'] == playbook_id:\n break\nelse:\n playbook = None\nif check:\n assert_that... | <|body_start_0|>
playbooks = self._client.get_playbooks(**kwargs)['items']
if check:
assert_that(playbooks, is_not(empty()))
return playbooks
<|end_body_0|>
<|body_start_1|>
playbooks = self.get_playbooks(**kwargs)
for playbook in playbooks:
if playbook['... | Playbook steps. | PlaybookSteps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaybookSteps:
"""Playbook steps."""
def get_playbooks(self, check=True, **kwargs):
"""Step to get all available playbooks. Args: check (bool): flag whether to check step or not **kwargs: any suitable keyword arguments Returns: list: list of all playbooks Raises: AssertionError: if c... | stack_v2_sparse_classes_36k_train_008865 | 2,018 | no_license | [
{
"docstring": "Step to get all available playbooks. Args: check (bool): flag whether to check step or not **kwargs: any suitable keyword arguments Returns: list: list of all playbooks Raises: AssertionError: if check failed",
"name": "get_playbooks",
"signature": "def get_playbooks(self, check=True, **... | 2 | stack_v2_sparse_classes_30k_test_000856 | Implement the Python class `PlaybookSteps` described below.
Class description:
Playbook steps.
Method signatures and docstrings:
- def get_playbooks(self, check=True, **kwargs): Step to get all available playbooks. Args: check (bool): flag whether to check step or not **kwargs: any suitable keyword arguments Returns:... | Implement the Python class `PlaybookSteps` described below.
Class description:
Playbook steps.
Method signatures and docstrings:
- def get_playbooks(self, check=True, **kwargs): Step to get all available playbooks. Args: check (bool): flag whether to check step or not **kwargs: any suitable keyword arguments Returns:... | 78950b95d98e791e6e5852aaef05ce9b7266be04 | <|skeleton|>
class PlaybookSteps:
"""Playbook steps."""
def get_playbooks(self, check=True, **kwargs):
"""Step to get all available playbooks. Args: check (bool): flag whether to check step or not **kwargs: any suitable keyword arguments Returns: list: list of all playbooks Raises: AssertionError: if c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlaybookSteps:
"""Playbook steps."""
def get_playbooks(self, check=True, **kwargs):
"""Step to get all available playbooks. Args: check (bool): flag whether to check step or not **kwargs: any suitable keyword arguments Returns: list: list of all playbooks Raises: AssertionError: if check failed""... | the_stack_v2_python_sparse | whale/decapod/steps/playbooks.py | Mirantis/whale | train | 1 |
adafd6cb5182f39ff77cfe935672e7455129913f | [
"def floyd(dist, n):\n for k in range(n):\n for i in range(n):\n for j in range(n):\n if dist[i][j] > dist[i][k] + dist[k][j]:\n dist[i][j] = dist[i][k] + dist[k][j]\n return dist\ndist = np.ones([n, n]) * n\nfor start, end in edges:\n dist[start][end] = ... | <|body_start_0|>
def floyd(dist, n):
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][j] > dist[i][k] + dist[k][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return dist
dist = n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinHeightTrees(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def _findMinHeightTrees(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: List[int]"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_008866 | 2,339 | no_license | [
{
"docstring": ":type n: int :type edges: List[List[int]] :rtype: List[int]",
"name": "findMinHeightTrees",
"signature": "def findMinHeightTrees(self, n, edges)"
},
{
"docstring": ":type n: int :type edges: List[List[int]] :rtype: List[int]",
"name": "_findMinHeightTrees",
"signature": "... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinHeightTrees(self, n, edges): :type n: int :type edges: List[List[int]] :rtype: List[int]
- def _findMinHeightTrees(self, n, edges): :type n: int :type edges: List[List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinHeightTrees(self, n, edges): :type n: int :type edges: List[List[int]] :rtype: List[int]
- def _findMinHeightTrees(self, n, edges): :type n: int :type edges: List[List... | fc5f0d70ca35789600a7e1d7ec356f648d09a7bf | <|skeleton|>
class Solution:
def findMinHeightTrees(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def _findMinHeightTrees(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: List[int]"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMinHeightTrees(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: List[int]"""
def floyd(dist, n):
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][j] > dist[i][k] + ... | the_stack_v2_python_sparse | Minimum Height Trees.py | zpyao1996/leetcode | train | 0 | |
5833770deff7f7e73a61ad3693973664da3c7ba2 | [
"help_group = kwargs.pop('group', None)\ndecorator = super().command(*args, **kwargs)\n\ndef wrapper(f):\n cmd = decorator(f)\n cmd.help_group = help_group\n return cmd\nreturn wrapper",
"commands = []\nfor subcommand in self.list_commands(ctx):\n cmd = self.get_command(ctx, subcommand)\n if cmd is... | <|body_start_0|>
help_group = kwargs.pop('group', None)
decorator = super().command(*args, **kwargs)
def wrapper(f):
cmd = decorator(f)
cmd.help_group = help_group
return cmd
return wrapper
<|end_body_0|>
<|body_start_1|>
commands = []
... | Custom group class which implements command grouping in --help display. Based on Stephen Rauch's excellent answer: https://stackoverflow.com/a/58770064/229511 | GroupedGroup | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupedGroup:
"""Custom group class which implements command grouping in --help display. Based on Stephen Rauch's excellent answer: https://stackoverflow.com/a/58770064/229511"""
def command(self, *args, **kwargs):
"""Gather the command help groups"""
<|body_0|>
def form... | stack_v2_sparse_classes_36k_train_008867 | 17,797 | permissive | [
{
"docstring": "Gather the command help groups",
"name": "command",
"signature": "def command(self, *args, **kwargs)"
},
{
"docstring": "Extra format methods for multi methods that adds all the commands after the options.",
"name": "format_commands",
"signature": "def format_commands(sel... | 3 | stack_v2_sparse_classes_30k_train_021537 | Implement the Python class `GroupedGroup` described below.
Class description:
Custom group class which implements command grouping in --help display. Based on Stephen Rauch's excellent answer: https://stackoverflow.com/a/58770064/229511
Method signatures and docstrings:
- def command(self, *args, **kwargs): Gather th... | Implement the Python class `GroupedGroup` described below.
Class description:
Custom group class which implements command grouping in --help display. Based on Stephen Rauch's excellent answer: https://stackoverflow.com/a/58770064/229511
Method signatures and docstrings:
- def command(self, *args, **kwargs): Gather th... | 833fcf233c81bd4eec708bc49cd653d4715de9e3 | <|skeleton|>
class GroupedGroup:
"""Custom group class which implements command grouping in --help display. Based on Stephen Rauch's excellent answer: https://stackoverflow.com/a/58770064/229511"""
def command(self, *args, **kwargs):
"""Gather the command help groups"""
<|body_0|>
def form... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupedGroup:
"""Custom group class which implements command grouping in --help display. Based on Stephen Rauch's excellent answer: https://stackoverflow.com/a/58770064/229511"""
def command(self, *args, **kwargs):
"""Gather the command help groups"""
help_group = kwargs.pop('group', None... | the_stack_v2_python_sparse | vpype_cli/cli.py | abey79/vpype | train | 615 |
b1d53a1b2a15c85fa0dbb4f6ed7cb233c0e1ed65 | [
"delivery = data.get('delivery')\nif current_app.config.get('ILS_CIRCULATION_DELIVERY_METHODS', {}) and (not delivery):\n raise ValidationError('Delivery is required.', 'delivery')",
"start = arrow.get(data['request_start_date']).date()\nend = arrow.get(data['request_expire_date']).date()\nduration_days = curr... | <|body_start_0|>
delivery = data.get('delivery')
if current_app.config.get('ILS_CIRCULATION_DELIVERY_METHODS', {}) and (not delivery):
raise ValidationError('Delivery is required.', 'delivery')
<|end_body_0|>
<|body_start_1|>
start = arrow.get(data['request_start_date']).date()
... | Loan request schema. | LoanRequestSchemaV1 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoanRequestSchemaV1:
"""Loan request schema."""
def validates_schema(self, data, **kwargs):
"""Validate schema delivery field."""
<|body_0|>
def postload_checks(self, data, **kwargs):
"""Validate dates values."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_008868 | 3,449 | permissive | [
{
"docstring": "Validate schema delivery field.",
"name": "validates_schema",
"signature": "def validates_schema(self, data, **kwargs)"
},
{
"docstring": "Validate dates values.",
"name": "postload_checks",
"signature": "def postload_checks(self, data, **kwargs)"
}
] | 2 | null | Implement the Python class `LoanRequestSchemaV1` described below.
Class description:
Loan request schema.
Method signatures and docstrings:
- def validates_schema(self, data, **kwargs): Validate schema delivery field.
- def postload_checks(self, data, **kwargs): Validate dates values. | Implement the Python class `LoanRequestSchemaV1` described below.
Class description:
Loan request schema.
Method signatures and docstrings:
- def validates_schema(self, data, **kwargs): Validate schema delivery field.
- def postload_checks(self, data, **kwargs): Validate dates values.
<|skeleton|>
class LoanRequestS... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class LoanRequestSchemaV1:
"""Loan request schema."""
def validates_schema(self, data, **kwargs):
"""Validate schema delivery field."""
<|body_0|>
def postload_checks(self, data, **kwargs):
"""Validate dates values."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoanRequestSchemaV1:
"""Loan request schema."""
def validates_schema(self, data, **kwargs):
"""Validate schema delivery field."""
delivery = data.get('delivery')
if current_app.config.get('ILS_CIRCULATION_DELIVERY_METHODS', {}) and (not delivery):
raise ValidationError... | the_stack_v2_python_sparse | invenio_app_ils/circulation/loaders/schemas/json/loan_request.py | inveniosoftware/invenio-app-ils | train | 64 |
47b22c1aa6c1db7d343da33c986611db35ab9b9a | [
"points = [(x - y, x + y) for x, y in peaks]\nadjMap = defaultdict(list)\nfor x, y in points:\n adjMap[x].append((x, y))\nkeys = sorted(adjMap)\nres, maxY = (0, -INF)\nfor key in keys:\n group = adjMap[key]\n cur = 0\n for _, py in group:\n if py > maxY:\n maxY = py\n cur = ... | <|body_start_0|>
points = [(x - y, x + y) for x, y in peaks]
adjMap = defaultdict(list)
for x, y in points:
adjMap[x].append((x, y))
keys = sorted(adjMap)
res, maxY = (0, -INF)
for key in keys:
group = adjMap[key]
cur = 0
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def visibleMountains(self, peaks: List[List[int]]) -> int:
"""逆时针旋转点 + 二维偏序看这个点是否被其他山峰包含"""
<|body_0|>
def visibleMountains2(self, peaks: List[List[int]]) -> int:
"""不旋转点 把每个山对应到x轴的区间上 一个维度排序 维护另一个维度"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_008869 | 2,030 | no_license | [
{
"docstring": "逆时针旋转点 + 二维偏序看这个点是否被其他山峰包含",
"name": "visibleMountains",
"signature": "def visibleMountains(self, peaks: List[List[int]]) -> int"
},
{
"docstring": "不旋转点 把每个山对应到x轴的区间上 一个维度排序 维护另一个维度",
"name": "visibleMountains2",
"signature": "def visibleMountains2(self, peaks: List[List... | 2 | stack_v2_sparse_classes_30k_train_002943 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def visibleMountains(self, peaks: List[List[int]]) -> int: 逆时针旋转点 + 二维偏序看这个点是否被其他山峰包含
- def visibleMountains2(self, peaks: List[List[int]]) -> int: 不旋转点 把每个山对应到x轴的区间上 一个维度排序 维护另一... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def visibleMountains(self, peaks: List[List[int]]) -> int: 逆时针旋转点 + 二维偏序看这个点是否被其他山峰包含
- def visibleMountains2(self, peaks: List[List[int]]) -> int: 不旋转点 把每个山对应到x轴的区间上 一个维度排序 维护另一... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def visibleMountains(self, peaks: List[List[int]]) -> int:
"""逆时针旋转点 + 二维偏序看这个点是否被其他山峰包含"""
<|body_0|>
def visibleMountains2(self, peaks: List[List[int]]) -> int:
"""不旋转点 把每个山对应到x轴的区间上 一个维度排序 维护另一个维度"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def visibleMountains(self, peaks: List[List[int]]) -> int:
"""逆时针旋转点 + 二维偏序看这个点是否被其他山峰包含"""
points = [(x - y, x + y) for x, y in peaks]
adjMap = defaultdict(list)
for x, y in points:
adjMap[x].append((x, y))
keys = sorted(adjMap)
res, maxY ... | the_stack_v2_python_sparse | 4_set/有序集合/二维偏序/2345. Finding the Number of Visible Mountains.py | 981377660LMT/algorithm-study | train | 225 | |
48f5a16e46e5257b01f8c844bc86e76002b3507d | [
"self.res = 0\nself.helper(root)\nreturn self.res",
"if not root:\n return 0\nl = self.helper(root.left)\nr = self.helper(root.right)\nself.res += abs(l - r)\nreturn l + r + root.val"
] | <|body_start_0|>
self.res = 0
self.helper(root)
return self.res
<|end_body_0|>
<|body_start_1|>
if not root:
return 0
l = self.helper(root.left)
r = self.helper(root.right)
self.res += abs(l - r)
return l + r + root.val
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTilt(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def helper(self, root):
""":param root: :return: int 当前节点的子树和当前节点的和"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.res = 0
self.helper(root)
... | stack_v2_sparse_classes_36k_train_008870 | 1,163 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "findTilt",
"signature": "def findTilt(self, root)"
},
{
"docstring": ":param root: :return: int 当前节点的子树和当前节点的和",
"name": "helper",
"signature": "def helper(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTilt(self, root): :type root: TreeNode :rtype: int
- def helper(self, root): :param root: :return: int 当前节点的子树和当前节点的和 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTilt(self, root): :type root: TreeNode :rtype: int
- def helper(self, root): :param root: :return: int 当前节点的子树和当前节点的和
<|skeleton|>
class Solution:
def findTilt(self... | beabfd31379f44ffd767fc676912db5022495b53 | <|skeleton|>
class Solution:
def findTilt(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def helper(self, root):
""":param root: :return: int 当前节点的子树和当前节点的和"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findTilt(self, root):
""":type root: TreeNode :rtype: int"""
self.res = 0
self.helper(root)
return self.res
def helper(self, root):
""":param root: :return: int 当前节点的子树和当前节点的和"""
if not root:
return 0
l = self.helper(root.l... | the_stack_v2_python_sparse | leetCode/tree/563findTilt.py | fatezy/Algorithm | train | 1 | |
ecc155365a8e038959673b8a6101cbb3a2f0e0f0 | [
"self.level = level\nself.patch_size = patch_size\nself.slide_path = slide_path\nself.loader = loader",
"d = self.__dict__\nd['slide_path'] = str(self.slide_path)\nd['loader'] = self.loader.name\nreturn d",
"sdict['slide_path'] = Path(sdict['slide_path'])\nsdict['loader'] = get_loader(sdict['loader'])\nreturn c... | <|body_start_0|>
self.level = level
self.patch_size = patch_size
self.slide_path = slide_path
self.loader = loader
<|end_body_0|>
<|body_start_1|>
d = self.__dict__
d['slide_path'] = str(self.slide_path)
d['loader'] = self.loader.name
return d
<|end_body_... | PatchSetting | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatchSetting:
def __init__(self, level: int, patch_size: int, slide_path: Path, loader: Loader) -> None:
"""Patch Setting Definition Args: level (int): The level at which patches are extracted patch_size (int): The size of patches to be created assumes square slide_path (Path): the path ... | stack_v2_sparse_classes_36k_train_008871 | 6,371 | permissive | [
{
"docstring": "Patch Setting Definition Args: level (int): The level at which patches are extracted patch_size (int): The size of patches to be created assumes square slide_path (Path): the path to the whole slide image loader (Loader): A method for loading the slide",
"name": "__init__",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_015483 | Implement the Python class `PatchSetting` described below.
Class description:
Implement the PatchSetting class.
Method signatures and docstrings:
- def __init__(self, level: int, patch_size: int, slide_path: Path, loader: Loader) -> None: Patch Setting Definition Args: level (int): The level at which patches are extr... | Implement the Python class `PatchSetting` described below.
Class description:
Implement the PatchSetting class.
Method signatures and docstrings:
- def __init__(self, level: int, patch_size: int, slide_path: Path, loader: Loader) -> None: Patch Setting Definition Args: level (int): The level at which patches are extr... | e9474e518fef4ea104f075a8efcf060989c5dc38 | <|skeleton|>
class PatchSetting:
def __init__(self, level: int, patch_size: int, slide_path: Path, loader: Loader) -> None:
"""Patch Setting Definition Args: level (int): The level at which patches are extracted patch_size (int): The size of patches to be created assumes square slide_path (Path): the path ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PatchSetting:
def __init__(self, level: int, patch_size: int, slide_path: Path, loader: Loader) -> None:
"""Patch Setting Definition Args: level (int): The level at which patches are extracted patch_size (int): The size of patches to be created assumes square slide_path (Path): the path to the whole s... | the_stack_v2_python_sparse | wsipipe/preprocess/patching/patchset.py | StAndrewsMedTech/wsipipe | train | 0 | |
0accb919720c716fd15bafaf23c6a1cd96e3316b | [
"from collections import deque\nif root is None:\n return []\nq = deque([root])\nlevel = 0\nresult = []\nwhile q:\n sz = len(q)\n result.append([])\n for _ in range(sz):\n node = q.popleft()\n result[-1].append(node.val)\n if node.left:\n q.append(node.left)\n if n... | <|body_start_0|>
from collections import deque
if root is None:
return []
q = deque([root])
level = 0
result = []
while q:
sz = len(q)
result.append([])
for _ in range(sz):
node = q.popleft()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
"""BFS with Reverse, Time: O(n), Space: O(n)"""
<|body_0|>
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
"""BFS without Reverse, Time: O(n), Space: O(n)"""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_008872 | 1,527 | no_license | [
{
"docstring": "BFS with Reverse, Time: O(n), Space: O(n)",
"name": "zigzagLevelOrder",
"signature": "def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]"
},
{
"docstring": "BFS without Reverse, Time: O(n), Space: O(n)",
"name": "zigzagLevelOrder",
"signature": "def zigzagLevel... | 2 | stack_v2_sparse_classes_30k_train_007366 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: BFS with Reverse, Time: O(n), Space: O(n)
- def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: BFS with... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: BFS with Reverse, Time: O(n), Space: O(n)
- def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: BFS with... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
"""BFS with Reverse, Time: O(n), Space: O(n)"""
<|body_0|>
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
"""BFS without Reverse, Time: O(n), Space: O(n)"""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
"""BFS with Reverse, Time: O(n), Space: O(n)"""
from collections import deque
if root is None:
return []
q = deque([root])
level = 0
result = []
while q:
sz ... | the_stack_v2_python_sparse | python/103-Binary Tree Zigzag Level Order Traversal.py | cwza/leetcode | train | 0 | |
b774a4c328d8efddba3aa98bcd64d7a3c5da1b18 | [
"self.k = data_splits[0]\nself.reader = Reader(file_name)\nself.df = self.reader.df\nself.normalize()\nif classification_type == 'classification':\n self.one_hot_encode()\nself.tuning_set = self.df.iloc[0:int(data_splits[1] * self.df.shape[0]), :]\nself.train_test_set = self.df.iloc[int(data_splits[1] * self.df.... | <|body_start_0|>
self.k = data_splits[0]
self.reader = Reader(file_name)
self.df = self.reader.df
self.normalize()
if classification_type == 'classification':
self.one_hot_encode()
self.tuning_set = self.df.iloc[0:int(data_splits[1] * self.df.shape[0]), :]
... | The data class is responsible for reading in, processing, storing, and manipulating data. An instance of the data class is passed into the algorithm so the algorithm has access to all data | DataClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataClass:
"""The data class is responsible for reading in, processing, storing, and manipulating data. An instance of the data class is passed into the algorithm so the algorithm has access to all data"""
def __init__(self, file_name, data_splits, classification_type):
"""Initializa... | stack_v2_sparse_classes_36k_train_008873 | 4,572 | no_license | [
{
"docstring": "Initialization method that normalizes all real values and creates value difference metrics for the categorical features as well as splitting data into tuning and train/test sets.",
"name": "__init__",
"signature": "def __init__(self, file_name, data_splits, classification_type)"
},
{... | 5 | stack_v2_sparse_classes_30k_train_006857 | Implement the Python class `DataClass` described below.
Class description:
The data class is responsible for reading in, processing, storing, and manipulating data. An instance of the data class is passed into the algorithm so the algorithm has access to all data
Method signatures and docstrings:
- def __init__(self,... | Implement the Python class `DataClass` described below.
Class description:
The data class is responsible for reading in, processing, storing, and manipulating data. An instance of the data class is passed into the algorithm so the algorithm has access to all data
Method signatures and docstrings:
- def __init__(self,... | 85b17bce4bef8de1bad52b66d9e9759432cb792a | <|skeleton|>
class DataClass:
"""The data class is responsible for reading in, processing, storing, and manipulating data. An instance of the data class is passed into the algorithm so the algorithm has access to all data"""
def __init__(self, file_name, data_splits, classification_type):
"""Initializa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataClass:
"""The data class is responsible for reading in, processing, storing, and manipulating data. An instance of the data class is passed into the algorithm so the algorithm has access to all data"""
def __init__(self, file_name, data_splits, classification_type):
"""Initialization method t... | the_stack_v2_python_sparse | proj3/DataClass.py | benholmgren/csci447 | train | 0 |
140fa8bf903eae975d0bd7eb10204aadb426f740 | [
"methods, platform_type = (self.LEGACY_SETUP, PLATFORM_TYPE_LEGACY)\nfor method in methods:\n if hasattr(self.platform, method):\n return platform_type\nreturn None",
"assert self.type == PLATFORM_TYPE_LEGACY\nfull_name = f'{DOMAIN}.{self.name}'\nLOGGER.info('Setting up %s', full_name)\nwith async_start... | <|body_start_0|>
methods, platform_type = (self.LEGACY_SETUP, PLATFORM_TYPE_LEGACY)
for method in methods:
if hasattr(self.platform, method):
return platform_type
return None
<|end_body_0|>
<|body_start_1|>
assert self.type == PLATFORM_TYPE_LEGACY
ful... | Class to hold platform information. | DeviceTrackerPlatform | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceTrackerPlatform:
"""Class to hold platform information."""
def type(self) -> str | None:
"""Return platform type."""
<|body_0|>
async def async_setup_legacy(self, hass: HomeAssistant, tracker: DeviceTracker, discovery_info: dict[str, Any] | None=None) -> None:
... | stack_v2_sparse_classes_36k_train_008874 | 33,527 | permissive | [
{
"docstring": "Return platform type.",
"name": "type",
"signature": "def type(self) -> str | None"
},
{
"docstring": "Set up a legacy platform.",
"name": "async_setup_legacy",
"signature": "async def async_setup_legacy(self, hass: HomeAssistant, tracker: DeviceTracker, discovery_info: d... | 2 | stack_v2_sparse_classes_30k_train_017591 | Implement the Python class `DeviceTrackerPlatform` described below.
Class description:
Class to hold platform information.
Method signatures and docstrings:
- def type(self) -> str | None: Return platform type.
- async def async_setup_legacy(self, hass: HomeAssistant, tracker: DeviceTracker, discovery_info: dict[str,... | Implement the Python class `DeviceTrackerPlatform` described below.
Class description:
Class to hold platform information.
Method signatures and docstrings:
- def type(self) -> str | None: Return platform type.
- async def async_setup_legacy(self, hass: HomeAssistant, tracker: DeviceTracker, discovery_info: dict[str,... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class DeviceTrackerPlatform:
"""Class to hold platform information."""
def type(self) -> str | None:
"""Return platform type."""
<|body_0|>
async def async_setup_legacy(self, hass: HomeAssistant, tracker: DeviceTracker, discovery_info: dict[str, Any] | None=None) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeviceTrackerPlatform:
"""Class to hold platform information."""
def type(self) -> str | None:
"""Return platform type."""
methods, platform_type = (self.LEGACY_SETUP, PLATFORM_TYPE_LEGACY)
for method in methods:
if hasattr(self.platform, method):
retur... | the_stack_v2_python_sparse | homeassistant/components/device_tracker/legacy.py | home-assistant/core | train | 35,501 |
3f3e1afad41a4469c7e251f93567751df01defd2 | [
"self.carange = carange\nself.crrange = crrange\nself.seed = seed\nself.ma = len(carange[0]) + 1 if carange is not None else None\nself.mr = len(crrange[0]) + 1 if crrange is not None else None\nif seed is not None:\n ts.setseed(seed)",
"if seed is not None:\n ts.setseed(seed)\nif self.ma is not None:\n ... | <|body_start_0|>
self.carange = carange
self.crrange = crrange
self.seed = seed
self.ma = len(carange[0]) + 1 if carange is not None else None
self.mr = len(crrange[0]) + 1 if crrange is not None else None
if seed is not None:
ts.setseed(seed)
<|end_body_0|>
... | PolyPhaseErrorGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolyPhaseErrorGenerator:
def __init__(self, carange=None, crrange=None, seed=None):
"""Polynominal phase error generator. Args: carange (None or tuple or list, optional): List of coefficients range of phase error in azimuth direction. crrange (None or tuple or list, optional): List of co... | stack_v2_sparse_classes_36k_train_008875 | 8,808 | permissive | [
{
"docstring": "Polynominal phase error generator. Args: carange (None or tuple or list, optional): List of coefficients range of phase error in azimuth direction. crrange (None or tuple or list, optional): List of coefficients range of phase error in range direction. seed (None or int, optional): The random se... | 2 | stack_v2_sparse_classes_30k_train_004624 | Implement the Python class `PolyPhaseErrorGenerator` described below.
Class description:
Implement the PolyPhaseErrorGenerator class.
Method signatures and docstrings:
- def __init__(self, carange=None, crrange=None, seed=None): Polynominal phase error generator. Args: carange (None or tuple or list, optional): List ... | Implement the Python class `PolyPhaseErrorGenerator` described below.
Class description:
Implement the PolyPhaseErrorGenerator class.
Method signatures and docstrings:
- def __init__(self, carange=None, crrange=None, seed=None): Polynominal phase error generator. Args: carange (None or tuple or list, optional): List ... | 05a46610d68bc884743a483565279f361ade5384 | <|skeleton|>
class PolyPhaseErrorGenerator:
def __init__(self, carange=None, crrange=None, seed=None):
"""Polynominal phase error generator. Args: carange (None or tuple or list, optional): List of coefficients range of phase error in azimuth direction. crrange (None or tuple or list, optional): List of co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PolyPhaseErrorGenerator:
def __init__(self, carange=None, crrange=None, seed=None):
"""Polynominal phase error generator. Args: carange (None or tuple or list, optional): List of coefficients range of phase error in azimuth direction. crrange (None or tuple or list, optional): List of coefficients ran... | the_stack_v2_python_sparse | torchsar/autofocus/phase_error_model.py | wrccrwx/torchsar | train | 0 | |
d0edc79db99e52ef101296d89d9ea8fc6661c7fb | [
"user = UserModel.query.get(user_id)\nif not user:\n abort(404, error=f'No user with id={user_id}')\nreturn (user, 200)",
"user = UserModel.query.get(user_id)\nif not user:\n abort(404, error=f'No user with id={user_id}')\nuser.username = kwargs['username']\ntry:\n user.save()\n return (user, 200)\nex... | <|body_start_0|>
user = UserModel.query.get(user_id)
if not user:
abort(404, error=f'No user with id={user_id}')
return (user, 200)
<|end_body_0|>
<|body_start_1|>
user = UserModel.query.get(user_id)
if not user:
abort(404, error=f'No user with id={user_i... | UserResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserResource:
def get(self, user_id):
"""Возвращает пользователя по id. :param user_id: id пользователя :return: пользователя"""
<|body_0|>
def put(self, user_id, **kwargs):
"""Изменяет пользователя по id. :param user_id: id пользователя :param kwargs: параметры для ... | stack_v2_sparse_classes_36k_train_008876 | 3,510 | no_license | [
{
"docstring": "Возвращает пользователя по id. :param user_id: id пользователя :return: пользователя",
"name": "get",
"signature": "def get(self, user_id)"
},
{
"docstring": "Изменяет пользователя по id. :param user_id: id пользователя :param kwargs: параметры для изменения пользователя :return:... | 3 | stack_v2_sparse_classes_30k_train_015388 | Implement the Python class `UserResource` described below.
Class description:
Implement the UserResource class.
Method signatures and docstrings:
- def get(self, user_id): Возвращает пользователя по id. :param user_id: id пользователя :return: пользователя
- def put(self, user_id, **kwargs): Изменяет пользователя по ... | Implement the Python class `UserResource` described below.
Class description:
Implement the UserResource class.
Method signatures and docstrings:
- def get(self, user_id): Возвращает пользователя по id. :param user_id: id пользователя :return: пользователя
- def put(self, user_id, **kwargs): Изменяет пользователя по ... | adb9a3f4524ab76e8ba656344e2ed452e87b577c | <|skeleton|>
class UserResource:
def get(self, user_id):
"""Возвращает пользователя по id. :param user_id: id пользователя :return: пользователя"""
<|body_0|>
def put(self, user_id, **kwargs):
"""Изменяет пользователя по id. :param user_id: id пользователя :param kwargs: параметры для ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserResource:
def get(self, user_id):
"""Возвращает пользователя по id. :param user_id: id пользователя :return: пользователя"""
user = UserModel.query.get(user_id)
if not user:
abort(404, error=f'No user with id={user_id}')
return (user, 200)
def put(self, use... | the_stack_v2_python_sparse | api/resources/user.py | UshakovAleksandr/Blog | train | 1 | |
2ddecd9114f9d28791355050c36172b4f42fbdf5 | [
"self.name = label.get('Name')\nself.confidence = label.get('Confidence')\nself.instances = label.get('Instances')\nself.parents = label.get('Parents')\nself.timestamp = timestamp",
"rendering = {}\nif self.name is not None:\n rendering['name'] = self.name\nif self.timestamp is not None:\n rendering['timest... | <|body_start_0|>
self.name = label.get('Name')
self.confidence = label.get('Confidence')
self.instances = label.get('Instances')
self.parents = label.get('Parents')
self.timestamp = timestamp
<|end_body_0|>
<|body_start_1|>
rendering = {}
if self.name is not None... | Encapsulates an Amazon Rekognition label. | RekognitionLabel | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RekognitionLabel:
"""Encapsulates an Amazon Rekognition label."""
def __init__(self, label, timestamp=None):
"""Initializes the label object. :param label: Label data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the label was detected, if t... | stack_v2_sparse_classes_36k_train_008877 | 11,689 | permissive | [
{
"docstring": "Initializes the label object. :param label: Label data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the label was detected, if the label was detected in a video.",
"name": "__init__",
"signature": "def __init__(self, label, timestamp=None)"
}... | 2 | null | Implement the Python class `RekognitionLabel` described below.
Class description:
Encapsulates an Amazon Rekognition label.
Method signatures and docstrings:
- def __init__(self, label, timestamp=None): Initializes the label object. :param label: Label data, in the format returned by Amazon Rekognition functions. :pa... | Implement the Python class `RekognitionLabel` described below.
Class description:
Encapsulates an Amazon Rekognition label.
Method signatures and docstrings:
- def __init__(self, label, timestamp=None): Initializes the label object. :param label: Label data, in the format returned by Amazon Rekognition functions. :pa... | dec41fb589043ac9d8667aac36fb88a53c3abe50 | <|skeleton|>
class RekognitionLabel:
"""Encapsulates an Amazon Rekognition label."""
def __init__(self, label, timestamp=None):
"""Initializes the label object. :param label: Label data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the label was detected, if t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RekognitionLabel:
"""Encapsulates an Amazon Rekognition label."""
def __init__(self, label, timestamp=None):
"""Initializes the label object. :param label: Label data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the label was detected, if the label was ... | the_stack_v2_python_sparse | python/example_code/rekognition/rekognition_objects.py | awsdocs/aws-doc-sdk-examples | train | 8,240 |
2d3507cc4df2f2a4fe84c1a9228cfc16a755875b | [
"if not 0 < p_dropout_inpt < 1 and (not 0 < p_dropout_hidden < 1):\n raise ValueError('dropout rates have to be in (0, 1)')\nself.p_dropout_inpt = p_dropout_inpt\nself.p_dropout_hidden = p_dropout_hidden\nself.max_length = max_length\nself.inpt_var = inpt_var\nsuper(FastDropoutNetwork, self).__init__(n_inpt, n_h... | <|body_start_0|>
if not 0 < p_dropout_inpt < 1 and (not 0 < p_dropout_hidden < 1):
raise ValueError('dropout rates have to be in (0, 1)')
self.p_dropout_inpt = p_dropout_inpt
self.p_dropout_hidden = p_dropout_hidden
self.max_length = max_length
self.inpt_var = inpt_va... | Class representing an MLP that is trained with fast dropout [FD]_. This method employs a smooth approximation of dropout training. References ---------- .. [FD] Wang, Sida, and Christopher Manning. "Fast dropout training." Proceedings of the 30th International Conference on Machine Learning (ICML-13). 2013. Attributes ... | FastDropoutNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastDropoutNetwork:
"""Class representing an MLP that is trained with fast dropout [FD]_. This method employs a smooth approximation of dropout training. References ---------- .. [FD] Wang, Sida, and Christopher Manning. "Fast dropout training." Proceedings of the 30th International Conference on... | stack_v2_sparse_classes_36k_train_008878 | 13,818 | no_license | [
{
"docstring": "Create a FastDropoutMlp object. Parameters ---------- Same parameters as an ``Mlp`` object. p_dropout_inpt : float Probability that an input unit is ommitted during a pass. p_dropout_hidden : float Probability that an input unit is ommitted during a pass. max_length : float or None Maximum squar... | 2 | stack_v2_sparse_classes_30k_train_004955 | Implement the Python class `FastDropoutNetwork` described below.
Class description:
Class representing an MLP that is trained with fast dropout [FD]_. This method employs a smooth approximation of dropout training. References ---------- .. [FD] Wang, Sida, and Christopher Manning. "Fast dropout training." Proceedings ... | Implement the Python class `FastDropoutNetwork` described below.
Class description:
Class representing an MLP that is trained with fast dropout [FD]_. This method employs a smooth approximation of dropout training. References ---------- .. [FD] Wang, Sida, and Christopher Manning. "Fast dropout training." Proceedings ... | 88db4a7fedba9e9ac6375c2051bd36825981c844 | <|skeleton|>
class FastDropoutNetwork:
"""Class representing an MLP that is trained with fast dropout [FD]_. This method employs a smooth approximation of dropout training. References ---------- .. [FD] Wang, Sida, and Christopher Manning. "Fast dropout training." Proceedings of the 30th International Conference on... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FastDropoutNetwork:
"""Class representing an MLP that is trained with fast dropout [FD]_. This method employs a smooth approximation of dropout training. References ---------- .. [FD] Wang, Sida, and Christopher Manning. "Fast dropout training." Proceedings of the 30th International Conference on Machine Lear... | the_stack_v2_python_sparse | breze/learn/mlp.py | rachelhornung/breze | train | 0 |
5bd461dd8bb2847f563ff9c7bd5858ef22484037 | [
"amended_events_and_context = await datastore.store_state_deltas_for_batched(events_and_context, room_id, last_known_state_group)\nevents_and_persisted_context = []\nfor event, unpersisted_context in amended_events_and_context:\n state_group_deltas = unpersisted_context._build_state_group_deltas()\n context =... | <|body_start_0|>
amended_events_and_context = await datastore.store_state_deltas_for_batched(events_and_context, room_id, last_known_state_group)
events_and_persisted_context = []
for event, unpersisted_context in amended_events_and_context:
state_group_deltas = unpersisted_context._... | The event context holds information about the state groups for an event. It is important to remember that an event technically has two state groups: the state group before the event, and the state group after the event. If the event is not a state event, the state group will not change (ie the state group before the ev... | UnpersistedEventContext | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnpersistedEventContext:
"""The event context holds information about the state groups for an event. It is important to remember that an event technically has two state groups: the state group before the event, and the state group after the event. If the event is not a state event, the state grou... | stack_v2_sparse_classes_36k_train_008879 | 21,722 | permissive | [
{
"docstring": "Takes a list of events and their associated unpersisted contexts and persists the unpersisted contexts, returning a list of events and persisted contexts. Note that all the events must be in a linear chain (ie a <- b <- c). Args: events_and_context: A list of events and their unpersisted context... | 4 | null | Implement the Python class `UnpersistedEventContext` described below.
Class description:
The event context holds information about the state groups for an event. It is important to remember that an event technically has two state groups: the state group before the event, and the state group after the event. If the eve... | Implement the Python class `UnpersistedEventContext` described below.
Class description:
The event context holds information about the state groups for an event. It is important to remember that an event technically has two state groups: the state group before the event, and the state group after the event. If the eve... | d35bed8369514fe727b4fe1afb68f48cc8b2655a | <|skeleton|>
class UnpersistedEventContext:
"""The event context holds information about the state groups for an event. It is important to remember that an event technically has two state groups: the state group before the event, and the state group after the event. If the event is not a state event, the state grou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnpersistedEventContext:
"""The event context holds information about the state groups for an event. It is important to remember that an event technically has two state groups: the state group before the event, and the state group after the event. If the event is not a state event, the state group will not ch... | the_stack_v2_python_sparse | synapse/events/snapshot.py | matrix-org/synapse | train | 12,215 |
501a12258170832716a7e696b0f771bcbfa1ac28 | [
"self.output = output\nself._c_function = self._compile(entry_name, tree, entry_type)\nreturn self",
"duration = c_float()\nif self.output is not None:\n output = self.output\n self.output = None\nelse:\n output = np.zeros_like(args[0])\nargs += (output, byref(duration))\nself._c_function(*args)\nreturn ... | <|body_start_0|>
self.output = output
self._c_function = self._compile(entry_name, tree, entry_type)
return self
<|end_body_0|>
<|body_start_1|>
duration = c_float()
if self.output is not None:
output = self.output
self.output = None
else:
... | StencilFunction The standard concrete specialized function that is returned when using the C or OpenMP backend. | ConcreteStencil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConcreteStencil:
"""StencilFunction The standard concrete specialized function that is returned when using the C or OpenMP backend."""
def finalize(self, tree, entry_name, entry_type, output):
""":param tree: A project node containing any files to be compiled for this specialized fun... | stack_v2_sparse_classes_36k_train_008880 | 25,641 | no_license | [
{
"docstring": ":param tree: A project node containing any files to be compiled for this specialized function. :type tree: Project node :param entry_name: The name of the function that will be the entry point to the compiled project. :type: str :param entry_type: The type signature of the function described by ... | 2 | stack_v2_sparse_classes_30k_train_003889 | Implement the Python class `ConcreteStencil` described below.
Class description:
StencilFunction The standard concrete specialized function that is returned when using the C or OpenMP backend.
Method signatures and docstrings:
- def finalize(self, tree, entry_name, entry_type, output): :param tree: A project node con... | Implement the Python class `ConcreteStencil` described below.
Class description:
StencilFunction The standard concrete specialized function that is returned when using the C or OpenMP backend.
Method signatures and docstrings:
- def finalize(self, tree, entry_name, entry_type, output): :param tree: A project node con... | 87f5d5115587f3362c8ea097900d3d50a3485b1a | <|skeleton|>
class ConcreteStencil:
"""StencilFunction The standard concrete specialized function that is returned when using the C or OpenMP backend."""
def finalize(self, tree, entry_name, entry_type, output):
""":param tree: A project node containing any files to be compiled for this specialized fun... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConcreteStencil:
"""StencilFunction The standard concrete specialized function that is returned when using the C or OpenMP backend."""
def finalize(self, tree, entry_name, entry_type, output):
""":param tree: A project node containing any files to be compiled for this specialized function. :type ... | the_stack_v2_python_sparse | stencil_code/stencil_kernel.py | ucb-sejits/stencil_code | train | 3 |
d2f70ee0a3192edae89735b0f95927983b4e3cfd | [
"assert type(n_bins) is int or n_bins in ('sqrt',)\nassert n_bins > 0\nassert isinstance(bin_boundaries_policy, BinBoundariesPolicy)\nself.n_bins = n_bins\nself.bin_boundaries_policy = bin_boundaries_policy\nsuper().__init__()",
"assert hasattr(model, 'predict_proba')\nassert type(X) is np.ndarray\nassert X.ndim ... | <|body_start_0|>
assert type(n_bins) is int or n_bins in ('sqrt',)
assert n_bins > 0
assert isinstance(bin_boundaries_policy, BinBoundariesPolicy)
self.n_bins = n_bins
self.bin_boundaries_policy = bin_boundaries_policy
super().__init__()
<|end_body_0|>
<|body_start_1|>
... | FixedBinAmountBinningPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixedBinAmountBinningPolicy:
def __init__(self, n_bins, bin_boundaries_policy):
"""Initializes a fixed bin amount binning policy, which sends samples into the n_bins bins created by the bin_boundaries_policy. Args: n_bins: int, number of bins used to divide the interval. bin_boundaries_p... | stack_v2_sparse_classes_36k_train_008881 | 2,092 | permissive | [
{
"docstring": "Initializes a fixed bin amount binning policy, which sends samples into the n_bins bins created by the bin_boundaries_policy. Args: n_bins: int, number of bins used to divide the interval. bin_boundaries_policy: BinBoundariesPolicy, defining how to split the interval into bins.",
"name": "__... | 2 | stack_v2_sparse_classes_30k_train_014410 | Implement the Python class `FixedBinAmountBinningPolicy` described below.
Class description:
Implement the FixedBinAmountBinningPolicy class.
Method signatures and docstrings:
- def __init__(self, n_bins, bin_boundaries_policy): Initializes a fixed bin amount binning policy, which sends samples into the n_bins bins c... | Implement the Python class `FixedBinAmountBinningPolicy` described below.
Class description:
Implement the FixedBinAmountBinningPolicy class.
Method signatures and docstrings:
- def __init__(self, n_bins, bin_boundaries_policy): Initializes a fixed bin amount binning policy, which sends samples into the n_bins bins c... | 9bfa81dd7a39ebe069c5b11b8e7a9bf9017e9350 | <|skeleton|>
class FixedBinAmountBinningPolicy:
def __init__(self, n_bins, bin_boundaries_policy):
"""Initializes a fixed bin amount binning policy, which sends samples into the n_bins bins created by the bin_boundaries_policy. Args: n_bins: int, number of bins used to divide the interval. bin_boundaries_p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FixedBinAmountBinningPolicy:
def __init__(self, n_bins, bin_boundaries_policy):
"""Initializes a fixed bin amount binning policy, which sends samples into the n_bins bins created by the bin_boundaries_policy. Args: n_bins: int, number of bins used to divide the interval. bin_boundaries_policy: BinBoun... | the_stack_v2_python_sparse | explicalib/calibration/evaluation/prototype/binning/primitives.py | euranova/estimating_eces | train | 4 | |
84b77772712d4dffca5bae433571b1147ea2d42f | [
"regex_c = re.compile(regex)\nfound_keys = []\nfor key in self.keys():\n if regex_c.search(key):\n found_keys.append(key)\nreturn found_keys",
"regex_c = re.compile(regex)\nfound_files = []\nfor key, file_ in self.items():\n if regex_c.search(key):\n found_files.append(file_)\nreturn found_fil... | <|body_start_0|>
regex_c = re.compile(regex)
found_keys = []
for key in self.keys():
if regex_c.search(key):
found_keys.append(key)
return found_keys
<|end_body_0|>
<|body_start_1|>
regex_c = re.compile(regex)
found_files = []
for key,... | Class that adds extra functionality to the dictionary containing the TestFileDB, allowing to batch-search for files with regular expressions. | TestFileDBDict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFileDBDict:
"""Class that adds extra functionality to the dictionary containing the TestFileDB, allowing to batch-search for files with regular expressions."""
def search_files(self, regex):
"""Get the list of keys matching a given regular expression. @param self The object point... | stack_v2_sparse_classes_36k_train_008882 | 1,488 | no_license | [
{
"docstring": "Get the list of keys matching a given regular expression. @param self The object pointer. @param regex Regular expression to match to the files in the DB. @return List of keys matching the regex.",
"name": "search_files",
"signature": "def search_files(self, regex)"
},
{
"docstri... | 2 | null | Implement the Python class `TestFileDBDict` described below.
Class description:
Class that adds extra functionality to the dictionary containing the TestFileDB, allowing to batch-search for files with regular expressions.
Method signatures and docstrings:
- def search_files(self, regex): Get the list of keys matching... | Implement the Python class `TestFileDBDict` described below.
Class description:
Class that adds extra functionality to the dictionary containing the TestFileDB, allowing to batch-search for files with regular expressions.
Method signatures and docstrings:
- def search_files(self, regex): Get the list of keys matching... | b22a1dfea5d4d572e318d1e5d05dfb7484da5f3d | <|skeleton|>
class TestFileDBDict:
"""Class that adds extra functionality to the dictionary containing the TestFileDB, allowing to batch-search for files with regular expressions."""
def search_files(self, regex):
"""Get the list of keys matching a given regular expression. @param self The object point... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFileDBDict:
"""Class that adds extra functionality to the dictionary containing the TestFileDB, allowing to batch-search for files with regular expressions."""
def search_files(self, regex):
"""Get the list of keys matching a given regular expression. @param self The object pointer. @param re... | the_stack_v2_python_sparse | DBASE/PRConfig/python/PRConfig/TestFileDBObject.py | kidaak/lhcbsoft | train | 0 |
d9f6a35397f6ce6322b9c00943e454a47cf8b79a | [
"super().__init__()\nself._Z = Z\nself._layers, dim = (nn.ModuleList(), [M + self._Z] + hidden_size)\nfor d_in, d_out in zip(dim[:-1], dim[1:]):\n self._layers.append(nn.Sequential(nn.Linear(d_in, d_out), g))\nlayer = nn.Sequential(nn.Linear(dim[-1], M), nn.Sigmoid())\nself._layers.append(layer)",
"if z is Non... | <|body_start_0|>
super().__init__()
self._Z = Z
self._layers, dim = (nn.ModuleList(), [M + self._Z] + hidden_size)
for d_in, d_out in zip(dim[:-1], dim[1:]):
self._layers.append(nn.Sequential(nn.Linear(d_in, d_out), g))
layer = nn.Sequential(nn.Linear(dim[-1], M), nn.... | MalGAN generator block | Generator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""MalGAN generator block"""
def __init__(self, M: int, Z: int, hidden_size: List[int], g: nn.Module):
"""Generator Constructor :param M: Dimension of the feature vector \\p m :param Z: Dimension of the noise vector \\p z :param hidden_size: Width of the hidden layer(s) :p... | stack_v2_sparse_classes_36k_train_008883 | 2,566 | permissive | [
{
"docstring": "Generator Constructor :param M: Dimension of the feature vector \\\\p m :param Z: Dimension of the noise vector \\\\p z :param hidden_size: Width of the hidden layer(s) :param g: Activation function",
"name": "__init__",
"signature": "def __init__(self, M: int, Z: int, hidden_size: List[... | 2 | stack_v2_sparse_classes_30k_train_013684 | Implement the Python class `Generator` described below.
Class description:
MalGAN generator block
Method signatures and docstrings:
- def __init__(self, M: int, Z: int, hidden_size: List[int], g: nn.Module): Generator Constructor :param M: Dimension of the feature vector \\p m :param Z: Dimension of the noise vector ... | Implement the Python class `Generator` described below.
Class description:
MalGAN generator block
Method signatures and docstrings:
- def __init__(self, M: int, Z: int, hidden_size: List[int], g: nn.Module): Generator Constructor :param M: Dimension of the feature vector \\p m :param Z: Dimension of the noise vector ... | c36647d1b3ba86a9a4e6e1a0bda2a371d8875781 | <|skeleton|>
class Generator:
"""MalGAN generator block"""
def __init__(self, M: int, Z: int, hidden_size: List[int], g: nn.Module):
"""Generator Constructor :param M: Dimension of the feature vector \\p m :param Z: Dimension of the noise vector \\p z :param hidden_size: Width of the hidden layer(s) :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
"""MalGAN generator block"""
def __init__(self, M: int, Z: int, hidden_size: List[int], g: nn.Module):
"""Generator Constructor :param M: Dimension of the feature vector \\p m :param Z: Dimension of the noise vector \\p z :param hidden_size: Width of the hidden layer(s) :param g: Activ... | the_stack_v2_python_sparse | malgan/generator.py | CyberForce/Pesidious | train | 119 |
e55aafdf52b7b9982b0f5674e70b860239166da0 | [
"self.max_batch_size = max_batch_size\nself.device = device\nself.distribution_cls = Categorical if distribution_cls is None else distribution_cls",
"num_samples, max_seq_length = actions.size()\nnumber_batches = (num_samples + self.max_batch_size - 1) // self.max_batch_size\nremaining_samples = num_samples\nlog_... | <|body_start_0|>
self.max_batch_size = max_batch_size
self.device = device
self.distribution_cls = Categorical if distribution_cls is None else distribution_cls
<|end_body_0|>
<|body_start_1|>
num_samples, max_seq_length = actions.size()
number_batches = (num_samples + self.max_... | Action replay for policy-based RL algorithms. Given some actions sampled from a RNN model, will calculate the log probabilities and entropy. | ActionReplay | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionReplay:
"""Action replay for policy-based RL algorithms. Given some actions sampled from a RNN model, will calculate the log probabilities and entropy."""
def __init__(self, max_batch_size, device, distribution_cls: Type[Distribution]=None) -> None:
"""Args: max_batch_size: Max... | stack_v2_sparse_classes_36k_train_008884 | 5,211 | permissive | [
{
"docstring": "Args: max_batch_size: Max. batch size device: cuda | cpu distribution_cls: distribution type to sample from. If None, will be a multinomial distribution.",
"name": "__init__",
"signature": "def __init__(self, max_batch_size, device, distribution_cls: Type[Distribution]=None) -> None"
}... | 3 | null | Implement the Python class `ActionReplay` described below.
Class description:
Action replay for policy-based RL algorithms. Given some actions sampled from a RNN model, will calculate the log probabilities and entropy.
Method signatures and docstrings:
- def __init__(self, max_batch_size, device, distribution_cls: Ty... | Implement the Python class `ActionReplay` described below.
Class description:
Action replay for policy-based RL algorithms. Given some actions sampled from a RNN model, will calculate the log probabilities and entropy.
Method signatures and docstrings:
- def __init__(self, max_batch_size, device, distribution_cls: Ty... | 44d24c53f3acf9266eb2fb06dbff909836549291 | <|skeleton|>
class ActionReplay:
"""Action replay for policy-based RL algorithms. Given some actions sampled from a RNN model, will calculate the log probabilities and entropy."""
def __init__(self, max_batch_size, device, distribution_cls: Type[Distribution]=None) -> None:
"""Args: max_batch_size: Max... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionReplay:
"""Action replay for policy-based RL algorithms. Given some actions sampled from a RNN model, will calculate the log probabilities and entropy."""
def __init__(self, max_batch_size, device, distribution_cls: Type[Distribution]=None) -> None:
"""Args: max_batch_size: Max. batch size ... | the_stack_v2_python_sparse | smiles_lstm_ppo/action_replay.py | BenevolentAI/guacamol_baselines | train | 108 |
69ec434f96503c0302f7f2df946ad3670374e88f | [
"query = DBSession.query(GroupPermAssignment)\nquery = query.join(Group, GroupPermAssignment.group_id == Group.group_id)\nquery = query.filter(Group.group_name == group_name)\nreturn query.all()",
"query = DBSession.query(GroupPermAssignment)\nquery = query.join(Group, GroupPermAssignment.group_id == Group.group_... | <|body_start_0|>
query = DBSession.query(GroupPermAssignment)
query = query.join(Group, GroupPermAssignment.group_id == Group.group_id)
query = query.filter(Group.group_name == group_name)
return query.all()
<|end_body_0|>
<|body_start_1|>
query = DBSession.query(GroupPermAssign... | Arsenal GroupPermAssignment object. | GroupPermAssignment | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupPermAssignment:
"""Arsenal GroupPermAssignment object."""
def get_assignments_by_group(self, group_name):
"""Return a list of permission assignments by group name."""
<|body_0|>
def get_assignments_by_perm(self, perm_name):
"""Return a list of permission ass... | stack_v2_sparse_classes_36k_train_008885 | 14,777 | permissive | [
{
"docstring": "Return a list of permission assignments by group name.",
"name": "get_assignments_by_group",
"signature": "def get_assignments_by_group(self, group_name)"
},
{
"docstring": "Return a list of permission assignments by permission name.",
"name": "get_assignments_by_perm",
"... | 2 | null | Implement the Python class `GroupPermAssignment` described below.
Class description:
Arsenal GroupPermAssignment object.
Method signatures and docstrings:
- def get_assignments_by_group(self, group_name): Return a list of permission assignments by group name.
- def get_assignments_by_perm(self, perm_name): Return a l... | Implement the Python class `GroupPermAssignment` described below.
Class description:
Arsenal GroupPermAssignment object.
Method signatures and docstrings:
- def get_assignments_by_group(self, group_name): Return a list of permission assignments by group name.
- def get_assignments_by_perm(self, perm_name): Return a l... | 5e8584b5805bb5d1603bb251ed8faeceaed31f59 | <|skeleton|>
class GroupPermAssignment:
"""Arsenal GroupPermAssignment object."""
def get_assignments_by_group(self, group_name):
"""Return a list of permission assignments by group name."""
<|body_0|>
def get_assignments_by_perm(self, perm_name):
"""Return a list of permission ass... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupPermAssignment:
"""Arsenal GroupPermAssignment object."""
def get_assignments_by_group(self, group_name):
"""Return a list of permission assignments by group name."""
query = DBSession.query(GroupPermAssignment)
query = query.join(Group, GroupPermAssignment.group_id == Group.... | the_stack_v2_python_sparse | server/arsenalweb/models/common.py | UnblockedByOps/arsenal | train | 5 |
2bab303c7ba245db95e16b2c35c9b0dfb755edd5 | [
"begin = ListNode('begin')\ntmp = begin\nwhile l1 is not None or l2 is not None:\n if l1 is None:\n begin.next = l2\n break\n elif l2 is None:\n begin.next = l1\n break\n elif l1.val < l2.val:\n begin.next = l1\n l1 = l1.next\n begin = begin.next\n else:\... | <|body_start_0|>
begin = ListNode('begin')
tmp = begin
while l1 is not None or l2 is not None:
if l1 is None:
begin.next = l2
break
elif l2 is None:
begin.next = l1
break
elif l1.val < l2.val:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
begin = ... | stack_v2_sparse_classes_36k_train_008886 | 1,261 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
},
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
<|skeleton|>... | ed0316454218c77e6ccabc4c19e35c825ba9ded8 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
begin = ListNode('begin')
tmp = begin
while l1 is not None or l2 is not None:
if l1 is None:
begin.next = l2
break
eli... | the_stack_v2_python_sparse | 23_2.py | Apeoud/LeetCode | train | 0 | |
5264359fa07e9fc8ffe23e5f0d7da1dc1c2c3cd3 | [
"for i, r in enumerate(A):\n r = A[i] = map(int, r)\n for j, c in enumerate(r):\n if i * j * c:\n r[j] = min(A[i - 1][j], r[j - 1], A[i - 1][j - 1]) + 1\nprint(A)\nreturn max(map(max, A + [[0]])) ** 2",
"for ri, r in enumerate(A):\n for ci, c in enumerate(r):\n A[ri][ci] = int(c)... | <|body_start_0|>
for i, r in enumerate(A):
r = A[i] = map(int, r)
for j, c in enumerate(r):
if i * j * c:
r[j] = min(A[i - 1][j], r[j - 1], A[i - 1][j - 1]) + 1
print(A)
return max(map(max, A + [[0]])) ** 2
<|end_body_0|>
<|body_start_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalSquare(self, A):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def rewrite(self, A):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i, r in enumerate(A):
... | stack_v2_sparse_classes_36k_train_008887 | 2,267 | no_license | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquare",
"signature": "def maximalSquare(self, A)"
},
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "rewrite",
"signature": "def rewrite(self, A)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, A): :type matrix: List[List[str]] :rtype: int
- def rewrite(self, A): :type matrix: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, A): :type matrix: List[List[str]] :rtype: int
- def rewrite(self, A): :type matrix: List[List[str]] :rtype: int
<|skeleton|>
class Solution:
def max... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def maximalSquare(self, A):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def rewrite(self, A):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximalSquare(self, A):
""":type matrix: List[List[str]] :rtype: int"""
for i, r in enumerate(A):
r = A[i] = map(int, r)
for j, c in enumerate(r):
if i * j * c:
r[j] = min(A[i - 1][j], r[j - 1], A[i - 1][j - 1]) + 1
... | the_stack_v2_python_sparse | dp/221_Maximal_Square.py | vsdrun/lc_public | train | 6 | |
3fd0f8a80e2687472efde5a91ec8037e95c57006 | [
"data = self.data\nid_ = data['entity']['id']\nreturn f'{PLATFORM_URL}orders/{id_}'",
"available = super().available\ndata = self.data\nfrom_role = data['author_role']\nto_role = data['to_role']\nreturn from_role == 'customer_user' and to_role == 'project_manager' and available"
] | <|body_start_0|>
data = self.data
id_ = data['entity']['id']
return f'{PLATFORM_URL}orders/{id_}'
<|end_body_0|>
<|body_start_1|>
available = super().available
data = self.data
from_role = data['author_role']
to_role = data['to_role']
return from_role == ... | Email to PM on comment created. | CommentCreatedByCustomerToPM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentCreatedByCustomerToPM:
"""Email to PM on comment created."""
def action_url(self) -> str:
"""Action URL."""
<|body_0|>
def available(self) -> bool:
"""Check if this action is available."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data... | stack_v2_sparse_classes_36k_train_008888 | 5,020 | no_license | [
{
"docstring": "Action URL.",
"name": "action_url",
"signature": "def action_url(self) -> str"
},
{
"docstring": "Check if this action is available.",
"name": "available",
"signature": "def available(self) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_014503 | Implement the Python class `CommentCreatedByCustomerToPM` described below.
Class description:
Email to PM on comment created.
Method signatures and docstrings:
- def action_url(self) -> str: Action URL.
- def available(self) -> bool: Check if this action is available. | Implement the Python class `CommentCreatedByCustomerToPM` described below.
Class description:
Email to PM on comment created.
Method signatures and docstrings:
- def action_url(self) -> str: Action URL.
- def available(self) -> bool: Check if this action is available.
<|skeleton|>
class CommentCreatedByCustomerToPM:... | cca179f55ebc3c420426eff59b23d7c8963ca9a3 | <|skeleton|>
class CommentCreatedByCustomerToPM:
"""Email to PM on comment created."""
def action_url(self) -> str:
"""Action URL."""
<|body_0|>
def available(self) -> bool:
"""Check if this action is available."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentCreatedByCustomerToPM:
"""Email to PM on comment created."""
def action_url(self) -> str:
"""Action URL."""
data = self.data
id_ = data['entity']['id']
return f'{PLATFORM_URL}orders/{id_}'
def available(self) -> bool:
"""Check if this action is availabl... | the_stack_v2_python_sparse | src/briefy/choreographer/actions/mail/leica/comment.py | BriefyHQ/briefy.choreographer | train | 0 |
936054a34391e93ef4555ca4a7128eb4bbb8d999 | [
"kwargs = super(Submit_Ticket, self).get_form_kwargs()\nkwargs.update({'request': self.request})\nreturn kwargs",
"form.instance.submitter = Doctor.objects.get(id=self.request.user.id)\ndoc = get_object_or_404(Doctor, id=self.request.user.id)\ndoc_hos = doc.current_hospital\neq = doc_hos.equipment_set.filter(name... | <|body_start_0|>
kwargs = super(Submit_Ticket, self).get_form_kwargs()
kwargs.update({'request': self.request})
return kwargs
<|end_body_0|>
<|body_start_1|>
form.instance.submitter = Doctor.objects.get(id=self.request.user.id)
doc = get_object_or_404(Doctor, id=self.request.use... | Submit_Ticket | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Submit_Ticket:
def get_form_kwargs(self):
"""Return the keyword arguments for instantiating the form."""
<|body_0|>
def form_valid(self, form):
"""If the form is valid, redirect to the supplied URL."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
kw... | stack_v2_sparse_classes_36k_train_008889 | 17,596 | no_license | [
{
"docstring": "Return the keyword arguments for instantiating the form.",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self)"
},
{
"docstring": "If the form is valid, redirect to the supplied URL.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | null | Implement the Python class `Submit_Ticket` described below.
Class description:
Implement the Submit_Ticket class.
Method signatures and docstrings:
- def get_form_kwargs(self): Return the keyword arguments for instantiating the form.
- def form_valid(self, form): If the form is valid, redirect to the supplied URL. | Implement the Python class `Submit_Ticket` described below.
Class description:
Implement the Submit_Ticket class.
Method signatures and docstrings:
- def get_form_kwargs(self): Return the keyword arguments for instantiating the form.
- def form_valid(self, form): If the form is valid, redirect to the supplied URL.
<... | ac3e367b345342e85279c2a82ca0c4c3611cffed | <|skeleton|>
class Submit_Ticket:
def get_form_kwargs(self):
"""Return the keyword arguments for instantiating the form."""
<|body_0|>
def form_valid(self, form):
"""If the form is valid, redirect to the supplied URL."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Submit_Ticket:
def get_form_kwargs(self):
"""Return the keyword arguments for instantiating the form."""
kwargs = super(Submit_Ticket, self).get_form_kwargs()
kwargs.update({'request': self.request})
return kwargs
def form_valid(self, form):
"""If the form is valid... | the_stack_v2_python_sparse | workflow/views.py | RamyMohmed/MSM-ramy | train | 0 | |
3aa7615a81264d3449620b439a546b5722c01974 | [
"self.city = city\nself.country = country\nself.department = department\nself.designation = designation\nself.graph_uuid = graph_uuid\nself.is_mailbox_enabled = is_mailbox_enabled\nself.is_one_drive_enabled = is_one_drive_enabled\nself.mailbox_size = mailbox_size\nself.mailbox_type = mailbox_type\nself.one_drive_id... | <|body_start_0|>
self.city = city
self.country = country
self.department = department
self.designation = designation
self.graph_uuid = graph_uuid
self.is_mailbox_enabled = is_mailbox_enabled
self.is_one_drive_enabled = is_one_drive_enabled
self.mailbox_siz... | Implementation of the 'Office365UserInfo' model. Specifies information about an Office365 user. Attributes: city (string): Specifies the city in which the Office365 user is located. country (string): Specifies the country/region in which the Office365 user is located. department (string): Specifies the department withi... | Office365UserInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Office365UserInfo:
"""Implementation of the 'Office365UserInfo' model. Specifies information about an Office365 user. Attributes: city (string): Specifies the city in which the Office365 user is located. country (string): Specifies the country/region in which the Office365 user is located. depart... | stack_v2_sparse_classes_36k_train_008890 | 4,615 | permissive | [
{
"docstring": "Constructor for the Office365UserInfo class",
"name": "__init__",
"signature": "def __init__(self, city=None, country=None, department=None, designation=None, graph_uuid=None, is_mailbox_enabled=None, is_one_drive_enabled=None, mailbox_size=None, mailbox_type=None, one_drive_id=None, one... | 2 | null | Implement the Python class `Office365UserInfo` described below.
Class description:
Implementation of the 'Office365UserInfo' model. Specifies information about an Office365 user. Attributes: city (string): Specifies the city in which the Office365 user is located. country (string): Specifies the country/region in whic... | Implement the Python class `Office365UserInfo` described below.
Class description:
Implementation of the 'Office365UserInfo' model. Specifies information about an Office365 user. Attributes: city (string): Specifies the city in which the Office365 user is located. country (string): Specifies the country/region in whic... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class Office365UserInfo:
"""Implementation of the 'Office365UserInfo' model. Specifies information about an Office365 user. Attributes: city (string): Specifies the city in which the Office365 user is located. country (string): Specifies the country/region in which the Office365 user is located. depart... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Office365UserInfo:
"""Implementation of the 'Office365UserInfo' model. Specifies information about an Office365 user. Attributes: city (string): Specifies the city in which the Office365 user is located. country (string): Specifies the country/region in which the Office365 user is located. department (string)... | the_stack_v2_python_sparse | cohesity_management_sdk/models/office_365_user_info.py | cohesity/management-sdk-python | train | 24 |
359b15ff803de97b0aeb235956aee0ab54090d39 | [
"self.method = method\nself.field = field\nsuper().__init__(**kwargs)\nself.method_func = METHOD_MAPPING.get(method)",
"field = graph[getattr(Index, self.field.upper())]\nn_field = graph[getattr(Index, f'n_{self.field}'.upper())]\nreturn self.method_func(field, get_segment_indices_from_n(n_field), num_segments=tf... | <|body_start_0|>
self.method = method
self.field = field
super().__init__(**kwargs)
self.method_func = METHOD_MAPPING.get(method)
<|end_body_0|>
<|body_start_1|>
field = graph[getattr(Index, self.field.upper())]
n_field = graph[getattr(Index, f'n_{self.field}'.upper())]
... | Reduce atom or bond attributes into lower dimensional tensors as readout. This could be summing up the atoms or bonds, or taking the mean, etc. | ReduceReadOut | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReduceReadOut:
"""Reduce atom or bond attributes into lower dimensional tensors as readout. This could be summing up the atoms or bonds, or taking the mean, etc."""
def __init__(self, method: str='mean', field='atoms', **kwargs):
"""Args: method (str): method for the reduction field ... | stack_v2_sparse_classes_36k_train_008891 | 8,087 | permissive | [
{
"docstring": "Args: method (str): method for the reduction field (str): the field of MaterialGraph to perform the reduction **kwargs:",
"name": "__init__",
"signature": "def __init__(self, method: str='mean', field='atoms', **kwargs)"
},
{
"docstring": "Args: graph (list): list repr of a Mater... | 3 | stack_v2_sparse_classes_30k_train_005045 | Implement the Python class `ReduceReadOut` described below.
Class description:
Reduce atom or bond attributes into lower dimensional tensors as readout. This could be summing up the atoms or bonds, or taking the mean, etc.
Method signatures and docstrings:
- def __init__(self, method: str='mean', field='atoms', **kwa... | Implement the Python class `ReduceReadOut` described below.
Class description:
Reduce atom or bond attributes into lower dimensional tensors as readout. This could be summing up the atoms or bonds, or taking the mean, etc.
Method signatures and docstrings:
- def __init__(self, method: str='mean', field='atoms', **kwa... | 1f89ecb564b2691c810cd106c3476b15a8699bb7 | <|skeleton|>
class ReduceReadOut:
"""Reduce atom or bond attributes into lower dimensional tensors as readout. This could be summing up the atoms or bonds, or taking the mean, etc."""
def __init__(self, method: str='mean', field='atoms', **kwargs):
"""Args: method (str): method for the reduction field ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReduceReadOut:
"""Reduce atom or bond attributes into lower dimensional tensors as readout. This could be summing up the atoms or bonds, or taking the mean, etc."""
def __init__(self, method: str='mean', field='atoms', **kwargs):
"""Args: method (str): method for the reduction field (str): the fi... | the_stack_v2_python_sparse | m3gnet/layers/_readout.py | materialsvirtuallab/m3gnet | train | 175 |
fe0c8d0196a27f8b7fdb4e6d1283588ee4d11b2d | [
"self.ppm = float(render_pixels_per_meter)\nself.rgb_fps = defaultdict(list)\nself.semantic_fps = defaultdict(list)\nfor scanId in scanIds:\n level = 0\n while True:\n bgr = cv2.imread(FLOORPLAN_DIR + RGB_TEMPLATE % (scanId, level))\n if bgr is None:\n break\n rgb = cv2.cvtColo... | <|body_start_0|>
self.ppm = float(render_pixels_per_meter)
self.rgb_fps = defaultdict(list)
self.semantic_fps = defaultdict(list)
for scanId in scanIds:
level = 0
while True:
bgr = cv2.imread(FLOORPLAN_DIR + RGB_TEMPLATE % (scanId, level))
... | Outputs top-down RGB and semantic renderings of Matterport environments. NOTE: The world coordinates in the returned image are x-right, y-up, z-out, i.e. the world coordinates origin is at the bottom left, and the y-axis is flipped. | Floorplan | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Floorplan:
"""Outputs top-down RGB and semantic renderings of Matterport environments. NOTE: The world coordinates in the returned image are x-right, y-up, z-out, i.e. the world coordinates origin is at the bottom left, and the y-axis is flipped."""
def __init__(self, render_pixels_per_meter... | stack_v2_sparse_classes_36k_train_008892 | 11,519 | permissive | [
{
"docstring": "Args: render_pixels_per_meter: scale factor determining the required output resolution scanIds: list of Matterport environments (which will be pre-loaded)",
"name": "__init__",
"signature": "def __init__(self, render_pixels_per_meter, scanIds)"
},
{
"docstring": "Determine which ... | 4 | stack_v2_sparse_classes_30k_train_006928 | Implement the Python class `Floorplan` described below.
Class description:
Outputs top-down RGB and semantic renderings of Matterport environments. NOTE: The world coordinates in the returned image are x-right, y-up, z-out, i.e. the world coordinates origin is at the bottom left, and the y-axis is flipped.
Method sig... | Implement the Python class `Floorplan` described below.
Class description:
Outputs top-down RGB and semantic renderings of Matterport environments. NOTE: The world coordinates in the returned image are x-right, y-up, z-out, i.e. the world coordinates origin is at the bottom left, and the y-axis is flipped.
Method sig... | f819aea21b94d9d3e23d9b6b9264054ee50c007b | <|skeleton|>
class Floorplan:
"""Outputs top-down RGB and semantic renderings of Matterport environments. NOTE: The world coordinates in the returned image are x-right, y-up, z-out, i.e. the world coordinates origin is at the bottom left, and the y-axis is flipped."""
def __init__(self, render_pixels_per_meter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Floorplan:
"""Outputs top-down RGB and semantic renderings of Matterport environments. NOTE: The world coordinates in the returned image are x-right, y-up, z-out, i.e. the world coordinates origin is at the bottom left, and the y-axis is flipped."""
def __init__(self, render_pixels_per_meter, scanIds):
... | the_stack_v2_python_sparse | tracker/floorplan.py | iCodeIN/vln-chasing-ghosts | train | 0 |
687ba5868b68413c24d3837714840ea14a2e3395 | [
"true_wavelen = float(true_wavelen)\nwrong_wavelen = float(wrong_wavelen)\nfrac_wrong = float(frac_wrong)\nif true_wavelen < 0:\n raise ValueError('true_wavelen must be positive')\nif wrong_wavelen < 0:\n raise ValueError('wrong_wavelen must be positive')\nif frac_wrong < 0 or frac_wrong > 1:\n raise Value... | <|body_start_0|>
true_wavelen = float(true_wavelen)
wrong_wavelen = float(wrong_wavelen)
frac_wrong = float(frac_wrong)
if true_wavelen < 0:
raise ValueError('true_wavelen must be positive')
if wrong_wavelen < 0:
raise ValueError('wrong_wavelen must be pos... | Degrader that simulates emission line confusion. Example: degrader = LineConfusion(true_wavelen=3727, wrong_wavelen=5007, frac_wrong=0.05) is a degrader that misidentifies 5% of OII lines (at 3727 angstroms) as OIII lines (at 5007 angstroms), which results in a larger spectroscopic redshift . Note that when selecting t... | LineConfusion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineConfusion:
"""Degrader that simulates emission line confusion. Example: degrader = LineConfusion(true_wavelen=3727, wrong_wavelen=5007, frac_wrong=0.05) is a degrader that misidentifies 5% of OII lines (at 3727 angstroms) as OIII lines (at 5007 angstroms), which results in a larger spectrosco... | stack_v2_sparse_classes_36k_train_008893 | 4,671 | permissive | [
{
"docstring": "Parameters ---------- true_wavelen : positive float The wavelength of the true emission line. Wavelength unit assumed to be the same as wrong_wavelen. wrong_wavelen : positive float The wavelength of the wrong emission line, which is being confused for the correct emission line. Wavelength unit ... | 2 | stack_v2_sparse_classes_30k_train_008747 | Implement the Python class `LineConfusion` described below.
Class description:
Degrader that simulates emission line confusion. Example: degrader = LineConfusion(true_wavelen=3727, wrong_wavelen=5007, frac_wrong=0.05) is a degrader that misidentifies 5% of OII lines (at 3727 angstroms) as OIII lines (at 5007 angstroms... | Implement the Python class `LineConfusion` described below.
Class description:
Degrader that simulates emission line confusion. Example: degrader = LineConfusion(true_wavelen=3727, wrong_wavelen=5007, frac_wrong=0.05) is a degrader that misidentifies 5% of OII lines (at 3727 angstroms) as OIII lines (at 5007 angstroms... | 3224cd3caef645e10a3dfd346dbee85240979888 | <|skeleton|>
class LineConfusion:
"""Degrader that simulates emission line confusion. Example: degrader = LineConfusion(true_wavelen=3727, wrong_wavelen=5007, frac_wrong=0.05) is a degrader that misidentifies 5% of OII lines (at 3727 angstroms) as OIII lines (at 5007 angstroms), which results in a larger spectrosco... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LineConfusion:
"""Degrader that simulates emission line confusion. Example: degrader = LineConfusion(true_wavelen=3727, wrong_wavelen=5007, frac_wrong=0.05) is a degrader that misidentifies 5% of OII lines (at 3727 angstroms) as OIII lines (at 5007 angstroms), which results in a larger spectroscopic redshift ... | the_stack_v2_python_sparse | rail/creation/degradation/spectroscopic_degraders.py | MarkusMichaelRau/RAIL | train | 0 |
a68d4c07a335bb1c4e1f55f32006464f6a6a3794 | [
"client = test_client.TestClient(context.node['baseurl'])\nwith pytest.raises(xml.parsers.expat.ExpatError):\n client.describe(context.TOKEN, '_invalid_pid_')",
"for object_list in context.slices:\n for object_info in object_list.objectInfo:\n client = test_client.TestClient(context.node['baseurl'])\... | <|body_start_0|>
client = test_client.TestClient(context.node['baseurl'])
with pytest.raises(xml.parsers.expat.ExpatError):
client.describe(context.TOKEN, '_invalid_pid_')
<|end_body_0|>
<|body_start_1|>
for object_list in context.slices:
for object_info in object_list.o... | Test060Describe | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test060Describe:
def test_010_describe_by_invalid_pid(self):
"""404 NotFound when attempting to get description for non-existing object."""
<|body_0|>
def test_020_describe_by_valid_pid(self):
"""Successful describe for known objects. - Verify that required headers a... | stack_v2_sparse_classes_36k_train_008894 | 3,506 | permissive | [
{
"docstring": "404 NotFound when attempting to get description for non-existing object.",
"name": "test_010_describe_by_invalid_pid",
"signature": "def test_010_describe_by_invalid_pid(self)"
},
{
"docstring": "Successful describe for known objects. - Verify that required headers are present. -... | 2 | stack_v2_sparse_classes_30k_train_000099 | Implement the Python class `Test060Describe` described below.
Class description:
Implement the Test060Describe class.
Method signatures and docstrings:
- def test_010_describe_by_invalid_pid(self): 404 NotFound when attempting to get description for non-existing object.
- def test_020_describe_by_valid_pid(self): Suc... | Implement the Python class `Test060Describe` described below.
Class description:
Implement the Test060Describe class.
Method signatures and docstrings:
- def test_010_describe_by_invalid_pid(self): 404 NotFound when attempting to get description for non-existing object.
- def test_020_describe_by_valid_pid(self): Suc... | d72a9461894d9be7d71178fb7310101b8ef9066a | <|skeleton|>
class Test060Describe:
def test_010_describe_by_invalid_pid(self):
"""404 NotFound when attempting to get description for non-existing object."""
<|body_0|>
def test_020_describe_by_valid_pid(self):
"""Successful describe for known objects. - Verify that required headers a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test060Describe:
def test_010_describe_by_invalid_pid(self):
"""404 NotFound when attempting to get description for non-existing object."""
client = test_client.TestClient(context.node['baseurl'])
with pytest.raises(xml.parsers.expat.ExpatError):
client.describe(context.TOK... | the_stack_v2_python_sparse | test_utilities/src/d1_test/stress_tester/projects/_unit_test_bases_for_stress_tests/tier_1_mn_read_describe.py | DataONEorg/d1_python | train | 15 | |
5c38102e821538a42e2c8d5f22731e64dcdcce36 | [
"if mat is None:\n pass\nelif isinstance(mat, sparse.coo.coo_matrix):\n self.coo_data = self.data\n self.rows = self.coo_data.row\n self.cols = self.coo_data.col\n self.vals = self.coo_data.data\nelif isinstance(mat, sparse.csr.csr_matrix) or isinstance(mat, sparse.csc.csc_matrix):\n self.coo_data... | <|body_start_0|>
if mat is None:
pass
elif isinstance(mat, sparse.coo.coo_matrix):
self.coo_data = self.data
self.rows = self.coo_data.row
self.cols = self.coo_data.col
self.vals = self.coo_data.data
elif isinstance(mat, sparse.csr.csr_... | Moves between sparse and dense data | SparseDataConverter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseDataConverter:
"""Moves between sparse and dense data"""
def __init__(self, mat=None):
"""converts mat to sparse data"""
<|body_0|>
def make_coo_mat(self, row, col, val):
"""Makes a coo_matrix from an npz file or a numpy array which is accessible in the row... | stack_v2_sparse_classes_36k_train_008895 | 1,656 | no_license | [
{
"docstring": "converts mat to sparse data",
"name": "__init__",
"signature": "def __init__(self, mat=None)"
},
{
"docstring": "Makes a coo_matrix from an npz file or a numpy array which is accessible in the row,col,val format and assigns to a scipy sparse.coo",
"name": "make_coo_mat",
... | 2 | stack_v2_sparse_classes_30k_train_013742 | Implement the Python class `SparseDataConverter` described below.
Class description:
Moves between sparse and dense data
Method signatures and docstrings:
- def __init__(self, mat=None): converts mat to sparse data
- def make_coo_mat(self, row, col, val): Makes a coo_matrix from an npz file or a numpy array which is ... | Implement the Python class `SparseDataConverter` described below.
Class description:
Moves between sparse and dense data
Method signatures and docstrings:
- def __init__(self, mat=None): converts mat to sparse data
- def make_coo_mat(self, row, col, val): Makes a coo_matrix from an npz file or a numpy array which is ... | 002754d768caf37f240a8e88d475c3b64fcce2e6 | <|skeleton|>
class SparseDataConverter:
"""Moves between sparse and dense data"""
def __init__(self, mat=None):
"""converts mat to sparse data"""
<|body_0|>
def make_coo_mat(self, row, col, val):
"""Makes a coo_matrix from an npz file or a numpy array which is accessible in the row... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparseDataConverter:
"""Moves between sparse and dense data"""
def __init__(self, mat=None):
"""converts mat to sparse data"""
if mat is None:
pass
elif isinstance(mat, sparse.coo.coo_matrix):
self.coo_data = self.data
self.rows = self.coo_data.... | the_stack_v2_python_sparse | lib/sparse_data_converter.py | fabfish/MatrixSketching | train | 1 |
451889ab5189e52f7d163597e870b8db93d815ff | [
"try:\n logger.info('Creating project: %s', project_name)\n response = lookoutvision_client.create_project(ProjectName=project_name)\n project_arn = response['ProjectMetadata']['ProjectArn']\n logger.info('project ARN: %s', project_arn)\nexcept ClientError:\n logger.exception(\"Couldn't create projec... | <|body_start_0|>
try:
logger.info('Creating project: %s', project_name)
response = lookoutvision_client.create_project(ProjectName=project_name)
project_arn = response['ProjectMetadata']['ProjectArn']
logger.info('project ARN: %s', project_arn)
except Clie... | Provides example functions for creating, listing, and deleting Lookout for Vision projects | Projects | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Projects:
"""Provides example functions for creating, listing, and deleting Lookout for Vision projects"""
def create_project(lookoutvision_client, project_name):
"""Creates a new Lookout for Vision project. :param lookoutvision_client: A Boto3 Lookout for Vision client. :param proje... | stack_v2_sparse_classes_36k_train_008896 | 4,466 | permissive | [
{
"docstring": "Creates a new Lookout for Vision project. :param lookoutvision_client: A Boto3 Lookout for Vision client. :param project_name: The name for the new project. :return project_arn: The ARN of the new project.",
"name": "create_project",
"signature": "def create_project(lookoutvision_client,... | 3 | stack_v2_sparse_classes_30k_train_017622 | Implement the Python class `Projects` described below.
Class description:
Provides example functions for creating, listing, and deleting Lookout for Vision projects
Method signatures and docstrings:
- def create_project(lookoutvision_client, project_name): Creates a new Lookout for Vision project. :param lookoutvisio... | Implement the Python class `Projects` described below.
Class description:
Provides example functions for creating, listing, and deleting Lookout for Vision projects
Method signatures and docstrings:
- def create_project(lookoutvision_client, project_name): Creates a new Lookout for Vision project. :param lookoutvisio... | dec41fb589043ac9d8667aac36fb88a53c3abe50 | <|skeleton|>
class Projects:
"""Provides example functions for creating, listing, and deleting Lookout for Vision projects"""
def create_project(lookoutvision_client, project_name):
"""Creates a new Lookout for Vision project. :param lookoutvision_client: A Boto3 Lookout for Vision client. :param proje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Projects:
"""Provides example functions for creating, listing, and deleting Lookout for Vision projects"""
def create_project(lookoutvision_client, project_name):
"""Creates a new Lookout for Vision project. :param lookoutvision_client: A Boto3 Lookout for Vision client. :param project_name: The ... | the_stack_v2_python_sparse | python/example_code/lookoutvision/projects.py | awsdocs/aws-doc-sdk-examples | train | 8,240 |
8bbcdf36c3b07dc491396affd825ba6774eed99a | [
"self.basic_block = basic_block\nself.bb_index = bb_index\nself.il = il\nself.written = {}\nself.read = {}",
"ssa = getSSA()\nwritten, read = il_registers(self.il)\nprint(written, read, self.il, self.il.operation)\nin_variables = copy.deepcopy(in_variables)\nfor r in read:\n if r not in in_variables:\n ... | <|body_start_0|>
self.basic_block = basic_block
self.bb_index = bb_index
self.il = il
self.written = {}
self.read = {}
<|end_body_0|>
<|body_start_1|>
ssa = getSSA()
written, read = il_registers(self.il)
print(written, read, self.il, self.il.operation)
... | A meta-instruction which we do analysis over | InsAnalysis | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InsAnalysis:
"""A meta-instruction which we do analysis over"""
def __init__(self, basic_block, bb_index, il):
"""Constructor for InsAnalysis @param basic_block The BBAnalysis this InsAnalysis belongs to. @param bb_index The index in BBAnalysis of this instruction."""
<|body_... | stack_v2_sparse_classes_36k_train_008897 | 4,768 | permissive | [
{
"docstring": "Constructor for InsAnalysis @param basic_block The BBAnalysis this InsAnalysis belongs to. @param bb_index The index in BBAnalysis of this instruction.",
"name": "__init__",
"signature": "def __init__(self, basic_block, bb_index, il)"
},
{
"docstring": "Takes a dict of identifier... | 2 | stack_v2_sparse_classes_30k_train_009201 | Implement the Python class `InsAnalysis` described below.
Class description:
A meta-instruction which we do analysis over
Method signatures and docstrings:
- def __init__(self, basic_block, bb_index, il): Constructor for InsAnalysis @param basic_block The BBAnalysis this InsAnalysis belongs to. @param bb_index The in... | Implement the Python class `InsAnalysis` described below.
Class description:
A meta-instruction which we do analysis over
Method signatures and docstrings:
- def __init__(self, basic_block, bb_index, il): Constructor for InsAnalysis @param basic_block The BBAnalysis this InsAnalysis belongs to. @param bb_index The in... | d1e51e0226474a81d96de26f36ffc2d39065ba87 | <|skeleton|>
class InsAnalysis:
"""A meta-instruction which we do analysis over"""
def __init__(self, basic_block, bb_index, il):
"""Constructor for InsAnalysis @param basic_block The BBAnalysis this InsAnalysis belongs to. @param bb_index The index in BBAnalysis of this instruction."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InsAnalysis:
"""A meta-instruction which we do analysis over"""
def __init__(self, basic_block, bb_index, il):
"""Constructor for InsAnalysis @param basic_block The BBAnalysis this InsAnalysis belongs to. @param bb_index The index in BBAnalysis of this instruction."""
self.basic_block = b... | the_stack_v2_python_sparse | src/avd/core/sliceEngine/loopDetection.py | bkerler/zeno | train | 1 |
f81d518aee133ee563f6f23fac4d61bf2393d9ca | [
"size = len(nums)\ndp = []\nfor x in range(size):\n low, high = (0, len(dp) - 1)\n while low <= high:\n mid = (low + high) / 2\n if dp[mid] >= nums[x]:\n high = mid - 1\n else:\n low = mid + 1\n if low >= len(dp):\n dp.append(nums[x])\n else:\n dp... | <|body_start_0|>
size = len(nums)
dp = []
for x in range(size):
low, high = (0, len(dp) - 1)
while low <= high:
mid = (low + high) / 2
if dp[mid] >= nums[x]:
high = mid - 1
else:
low =... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def lengthOfLIS3(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_36k_train_008898 | 1,475 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS2",
"signature": "def lengthOfLIS2(self, nums)"
},
{
"docstring": ":type nums: List[int... | 3 | null | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS2(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS3(self, nums): :type nums: Lis... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS2(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS3(self, nums): :type nums: Lis... | 4599634f31d78a0372cf0ff6fb7935d054d5ecb5 | <|skeleton|>
class Solution1:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def lengthOfLIS3(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
size = len(nums)
dp = []
for x in range(size):
low, high = (0, len(dp) - 1)
while low <= high:
mid = (low + high) / 2
if dp[mid] >= nums[x]:
... | the_stack_v2_python_sparse | leetcode_python/201-300/300.py | jhgdike/leetCode | train | 3 | |
d9cf8f7c058b2bc7fc27625ee7e4e5463a2fb2c4 | [
"max_steps = np.ceil(np.log2(max_power)).astype(np.int32)\nif use_numpy:\n original_dtype = matrix.dtype\n matrix = np.asarray(matrix, np.float64)\n buffer = np.zeros((max_steps,) + matrix.shape, np.float64)\n for i in range(max_steps):\n buffer[i] = matrix\n matrix = np.dot(matrix, matrix... | <|body_start_0|>
max_steps = np.ceil(np.log2(max_power)).astype(np.int32)
if use_numpy:
original_dtype = matrix.dtype
matrix = np.asarray(matrix, np.float64)
buffer = np.zeros((max_steps,) + matrix.shape, np.float64)
for i in range(max_steps):
... | Matrix power state that caches powers of two. | CachedMatrixPowerState | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CachedMatrixPowerState:
"""Matrix power state that caches powers of two."""
def precompute(matrix, max_power=100, precision=jax.lax.Precision.DEFAULT, use_numpy=False):
"""Builds state for computing efficient matrix_power vector products. Args: matrix: an [N,N] matrix to compute powe... | stack_v2_sparse_classes_36k_train_008899 | 28,143 | permissive | [
{
"docstring": "Builds state for computing efficient matrix_power vector products. Args: matrix: an [N,N] matrix to compute powers of. max_power: the maximum power to support matrix powers for. precision: precision of matmuls while generating state. use_numpy: if True, will use maximum precision with numpy floa... | 3 | null | Implement the Python class `CachedMatrixPowerState` described below.
Class description:
Matrix power state that caches powers of two.
Method signatures and docstrings:
- def precompute(matrix, max_power=100, precision=jax.lax.Precision.DEFAULT, use_numpy=False): Builds state for computing efficient matrix_power vecto... | Implement the Python class `CachedMatrixPowerState` described below.
Class description:
Matrix power state that caches powers of two.
Method signatures and docstrings:
- def precompute(matrix, max_power=100, precision=jax.lax.Precision.DEFAULT, use_numpy=False): Builds state for computing efficient matrix_power vecto... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class CachedMatrixPowerState:
"""Matrix power state that caches powers of two."""
def precompute(matrix, max_power=100, precision=jax.lax.Precision.DEFAULT, use_numpy=False):
"""Builds state for computing efficient matrix_power vector products. Args: matrix: an [N,N] matrix to compute powe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CachedMatrixPowerState:
"""Matrix power state that caches powers of two."""
def precompute(matrix, max_power=100, precision=jax.lax.Precision.DEFAULT, use_numpy=False):
"""Builds state for computing efficient matrix_power vector products. Args: matrix: an [N,N] matrix to compute powers of. max_po... | the_stack_v2_python_sparse | d3pm/text/model_utils.py | Jimmy-INL/google-research | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.