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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
01d74009f652435a584d412cb72f39071a096ce0 | [
"self._targets_and_priorities = targets_and_priorities\nself._queue_name = queue_name\nsuper(NotificationPikaPoller, self).__init__(pika_engine, batch_size, batch_timeout, prefetch_count, pika_drv_msg.PikaIncomingMessage)",
"queues_to_consume = []\nfor target, priority in self._targets_and_priorities:\n routin... | <|body_start_0|>
self._targets_and_priorities = targets_and_priorities
self._queue_name = queue_name
super(NotificationPikaPoller, self).__init__(pika_engine, batch_size, batch_timeout, prefetch_count, pika_drv_msg.PikaIncomingMessage)
<|end_body_0|>
<|body_start_1|>
queues_to_consume =... | PikaPoller implementation for polling Notification messages. Overrides base functionality according to Notification specific | NotificationPikaPoller | [
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotificationPikaPoller:
"""PikaPoller implementation for polling Notification messages. Overrides base functionality according to Notification specific"""
def __init__(self, pika_engine, targets_and_priorities, batch_size, batch_timeout, prefetch_count, queue_name=None):
"""Adds targ... | stack_v2_sparse_classes_36k_train_014200 | 22,231 | permissive | [
{
"docstring": "Adds targets_and_priorities and queue_name parameter for declaring exchanges and queues used for notification delivery :param pika_engine: PikaEngine, shared object with configuration and shared driver functionality :param targets_and_priorities: list of (target, priority), defines default queue... | 2 | stack_v2_sparse_classes_30k_train_019482 | Implement the Python class `NotificationPikaPoller` described below.
Class description:
PikaPoller implementation for polling Notification messages. Overrides base functionality according to Notification specific
Method signatures and docstrings:
- def __init__(self, pika_engine, targets_and_priorities, batch_size, b... | Implement the Python class `NotificationPikaPoller` described below.
Class description:
PikaPoller implementation for polling Notification messages. Overrides base functionality according to Notification specific
Method signatures and docstrings:
- def __init__(self, pika_engine, targets_and_priorities, batch_size, b... | c01951b33e278de9e769c2d0609c0be61d2cb26b | <|skeleton|>
class NotificationPikaPoller:
"""PikaPoller implementation for polling Notification messages. Overrides base functionality according to Notification specific"""
def __init__(self, pika_engine, targets_and_priorities, batch_size, batch_timeout, prefetch_count, queue_name=None):
"""Adds targ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotificationPikaPoller:
"""PikaPoller implementation for polling Notification messages. Overrides base functionality according to Notification specific"""
def __init__(self, pika_engine, targets_and_priorities, batch_size, batch_timeout, prefetch_count, queue_name=None):
"""Adds targets_and_prior... | the_stack_v2_python_sparse | filesystems/vnx_rootfs_lxc_ubuntu64-16.04-v025-openstack-compute/rootfs/usr/lib/python2.7/dist-packages/oslo_messaging/_drivers/pika_driver/pika_poller.py | juancarlosdiaztorres/Ansible-OpenStack | train | 0 |
3a8fbc3e8585dfbd4fdaedaf81cbb0933eb9c13a | [
"count = 0\nfor i in range(1, m + 1):\n count += min(int(num / i), n)\nreturn count",
"if k == 1:\n return 1\nelif k == m * n:\n return m * n\nelse:\n left = 1\n right = m * n\n while left < right:\n mid = int(left + right >> 1)\n count_smaller_than_mid = self.count_smaller_than_nu... | <|body_start_0|>
count = 0
for i in range(1, m + 1):
count += min(int(num / i), n)
return count
<|end_body_0|>
<|body_start_1|>
if k == 1:
return 1
elif k == m * n:
return m * n
else:
left = 1
right = m * n
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def count_smaller_than_num(self, m, n, num):
""":type m: int :type n: int :type num: int :return: count int"""
<|body_0|>
def findKthNumber_wrong(self, m, n, k):
""":type m: int :type n: int :type k: int :rtype: int"""
<|body_1|>
def findKthNum... | stack_v2_sparse_classes_36k_train_014201 | 2,372 | permissive | [
{
"docstring": ":type m: int :type n: int :type num: int :return: count int",
"name": "count_smaller_than_num",
"signature": "def count_smaller_than_num(self, m, n, num)"
},
{
"docstring": ":type m: int :type n: int :type k: int :rtype: int",
"name": "findKthNumber_wrong",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_002154 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def count_smaller_than_num(self, m, n, num): :type m: int :type n: int :type num: int :return: count int
- def findKthNumber_wrong(self, m, n, k): :type m: int :type n: int :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def count_smaller_than_num(self, m, n, num): :type m: int :type n: int :type num: int :return: count int
- def findKthNumber_wrong(self, m, n, k): :type m: int :type n: int :type... | 4a6d46c179d7f52054c417b2aa21708331ac84c5 | <|skeleton|>
class Solution:
def count_smaller_than_num(self, m, n, num):
""":type m: int :type n: int :type num: int :return: count int"""
<|body_0|>
def findKthNumber_wrong(self, m, n, k):
""":type m: int :type n: int :type k: int :rtype: int"""
<|body_1|>
def findKthNum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def count_smaller_than_num(self, m, n, num):
""":type m: int :type n: int :type num: int :return: count int"""
count = 0
for i in range(1, m + 1):
count += min(int(num / i), n)
return count
def findKthNumber_wrong(self, m, n, k):
""":type m: i... | the_stack_v2_python_sparse | problems/二分/668. 乘法表中第k小的数/kth-smallest-number-in-multiplication-table.py | HannibalXZX/LeetCode | train | 1 | |
4d4350901835a88354cd08ee2efbb21b59bba11e | [
"layer.Layer.__init__(self, inputs, outputs, alpha)\nself.parameters = dict()\nself.deltaparameters = dict()\nself.parameters['weights'] = numpy.random.normal(0.0, 1.0 / numpy.sqrt(self.inputs), (self.outputs, self.inputs))\nself.function = None\nself.functionderivative = None\nself.weightsderivative = None\nself.c... | <|body_start_0|>
layer.Layer.__init__(self, inputs, outputs, alpha)
self.parameters = dict()
self.deltaparameters = dict()
self.parameters['weights'] = numpy.random.normal(0.0, 1.0 / numpy.sqrt(self.inputs), (self.outputs, self.inputs))
self.function = None
self.functiond... | Base Class for Self Organising Feature Maps Mathematically, f(x)(i) = 1.0 if i = argmin(r(i)) = 0.0 otherwise | SelfOrganising | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfOrganising:
"""Base Class for Self Organising Feature Maps Mathematically, f(x)(i) = 1.0 if i = argmin(r(i)) = 0.0 otherwise"""
def __init__(self, inputs, outputs, alpha=None):
"""Constructor : param inputs : dimension of input feature space : param outputs : dimension of output ... | stack_v2_sparse_classes_36k_train_014202 | 5,772 | no_license | [
{
"docstring": "Constructor : param inputs : dimension of input feature space : param outputs : dimension of output feature space : param alpha : learning rate constant hyperparameter",
"name": "__init__",
"signature": "def __init__(self, inputs, outputs, alpha=None)"
},
{
"docstring": "Method t... | 4 | stack_v2_sparse_classes_30k_train_005646 | Implement the Python class `SelfOrganising` described below.
Class description:
Base Class for Self Organising Feature Maps Mathematically, f(x)(i) = 1.0 if i = argmin(r(i)) = 0.0 otherwise
Method signatures and docstrings:
- def __init__(self, inputs, outputs, alpha=None): Constructor : param inputs : dimension of i... | Implement the Python class `SelfOrganising` described below.
Class description:
Base Class for Self Organising Feature Maps Mathematically, f(x)(i) = 1.0 if i = argmin(r(i)) = 0.0 otherwise
Method signatures and docstrings:
- def __init__(self, inputs, outputs, alpha=None): Constructor : param inputs : dimension of i... | 10ee6e2297b7a2e01165ef983ae34097d7178122 | <|skeleton|>
class SelfOrganising:
"""Base Class for Self Organising Feature Maps Mathematically, f(x)(i) = 1.0 if i = argmin(r(i)) = 0.0 otherwise"""
def __init__(self, inputs, outputs, alpha=None):
"""Constructor : param inputs : dimension of input feature space : param outputs : dimension of output ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfOrganising:
"""Base Class for Self Organising Feature Maps Mathematically, f(x)(i) = 1.0 if i = argmin(r(i)) = 0.0 otherwise"""
def __init__(self, inputs, outputs, alpha=None):
"""Constructor : param inputs : dimension of input feature space : param outputs : dimension of output feature space... | the_stack_v2_python_sparse | net/selforganising.py | sunilmallya-work/NET | train | 0 |
610f415dd3004c76f98c52a0069c0ad72d7389a4 | [
"self.stopwords = self.get_stopwords(stopword_filepath)\nself.raker = r.Rake(self.stopwords)\nself.counter = w.WordCounter(self.stopwords)",
"rake_keys = self.extract_rake(text, False)\ntop_keys = self.extract_top(text, True)\nkey_list = {}\nfor rake_key in rake_keys:\n key_list[rake_key[0]] = 0\n key_score... | <|body_start_0|>
self.stopwords = self.get_stopwords(stopword_filepath)
self.raker = r.Rake(self.stopwords)
self.counter = w.WordCounter(self.stopwords)
<|end_body_0|>
<|body_start_1|>
rake_keys = self.extract_rake(text, False)
top_keys = self.extract_top(text, True)
key... | keywords class | KeyWords | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyWords:
"""keywords class"""
def __init__(self, stopword_filepath='SmartStoplist.txt'):
"""Init @param stopword_filepath Filepath for stopwordlist, can be modified"""
<|body_0|>
def extract(self, text, return_amount=10):
"""Does a combined rake and relevant wor... | stack_v2_sparse_classes_36k_train_014203 | 3,760 | no_license | [
{
"docstring": "Init @param stopword_filepath Filepath for stopwordlist, can be modified",
"name": "__init__",
"signature": "def __init__(self, stopword_filepath='SmartStoplist.txt')"
},
{
"docstring": "Does a combined rake and relevant word count of the given string in order to give some releva... | 5 | stack_v2_sparse_classes_30k_train_006752 | Implement the Python class `KeyWords` described below.
Class description:
keywords class
Method signatures and docstrings:
- def __init__(self, stopword_filepath='SmartStoplist.txt'): Init @param stopword_filepath Filepath for stopwordlist, can be modified
- def extract(self, text, return_amount=10): Does a combined ... | Implement the Python class `KeyWords` described below.
Class description:
keywords class
Method signatures and docstrings:
- def __init__(self, stopword_filepath='SmartStoplist.txt'): Init @param stopword_filepath Filepath for stopwordlist, can be modified
- def extract(self, text, return_amount=10): Does a combined ... | 5e67a73cb08165bce415131555f21c4713321b0c | <|skeleton|>
class KeyWords:
"""keywords class"""
def __init__(self, stopword_filepath='SmartStoplist.txt'):
"""Init @param stopword_filepath Filepath for stopwordlist, can be modified"""
<|body_0|>
def extract(self, text, return_amount=10):
"""Does a combined rake and relevant wor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeyWords:
"""keywords class"""
def __init__(self, stopword_filepath='SmartStoplist.txt'):
"""Init @param stopword_filepath Filepath for stopwordlist, can be modified"""
self.stopwords = self.get_stopwords(stopword_filepath)
self.raker = r.Rake(self.stopwords)
self.counter ... | the_stack_v2_python_sparse | media_conversation/keywords.py | linriedi/UvA-Home | train | 0 |
f2d08c1122e64dfe5dbcad1d2e41b211c0d709e8 | [
"student_list = []\nfor std in Student.objects.all():\n deserialized = deserialize_student(std)\n student_list.append(deserialized)\nreturn Response({'student_list': student_list})",
"data = request.data\nif data:\n search = data.get('search')\n courses_studied = data.get('courses_studied')\n if co... | <|body_start_0|>
student_list = []
for std in Student.objects.all():
deserialized = deserialize_student(std)
student_list.append(deserialized)
return Response({'student_list': student_list})
<|end_body_0|>
<|body_start_1|>
data = request.data
if data:
... | StudentListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentListView:
def get(self, request, format=None):
"""' Get list of students"""
<|body_0|>
def post(self, request):
"""' Gives us data based on reasons different reason for diff uses Story sha but it is good for us to use ...for example --> API, with reverse looku... | stack_v2_sparse_classes_36k_train_014204 | 10,002 | no_license | [
{
"docstring": "' Get list of students",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "' Gives us data based on reasons different reason for diff uses Story sha but it is good for us to use ...for example --> API, with reverse lookup.. based on -> courses s... | 2 | stack_v2_sparse_classes_30k_train_014048 | Implement the Python class `StudentListView` described below.
Class description:
Implement the StudentListView class.
Method signatures and docstrings:
- def get(self, request, format=None): ' Get list of students
- def post(self, request): ' Gives us data based on reasons different reason for diff uses Story sha but... | Implement the Python class `StudentListView` described below.
Class description:
Implement the StudentListView class.
Method signatures and docstrings:
- def get(self, request, format=None): ' Get list of students
- def post(self, request): ' Gives us data based on reasons different reason for diff uses Story sha but... | fcbc142c6dd11028819493499d7105b3a0b7995c | <|skeleton|>
class StudentListView:
def get(self, request, format=None):
"""' Get list of students"""
<|body_0|>
def post(self, request):
"""' Gives us data based on reasons different reason for diff uses Story sha but it is good for us to use ...for example --> API, with reverse looku... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StudentListView:
def get(self, request, format=None):
"""' Get list of students"""
student_list = []
for std in Student.objects.all():
deserialized = deserialize_student(std)
student_list.append(deserialized)
return Response({'student_list': student_list... | the_stack_v2_python_sparse | user_profiles/views.py | Jray-Tech/virtual_class_backend | train | 0 | |
82678b581f2e4d50cda3152633fcc27489cde60d | [
"self.A = mat_params['A']\nself.B = mat_params['B']\nself.C = mat_params['C']\nself.thickness = thickness\nself.name = name",
"n = np.sqrt(self.A + self.B * w ** 2 / (w ** 2 - self.C))\nk = 2 * PI * n / w\ntheta = k * self.thickness\nM = np.array([[np.cos(theta), 1j * np.sin(theta) / n], [1j * n * np.sin(theta), ... | <|body_start_0|>
self.A = mat_params['A']
self.B = mat_params['B']
self.C = mat_params['C']
self.thickness = thickness
self.name = name
<|end_body_0|>
<|body_start_1|>
n = np.sqrt(self.A + self.B * w ** 2 / (w ** 2 - self.C))
k = 2 * PI * n / w
theta = k ... | SellmeierLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SellmeierLayer:
def __init__(self, mat_params, thickness, name=None):
"""SellmeierLayer(mat_params, thickness, name=None)"""
<|body_0|>
def matrix(self, w):
"""matrix(w) Generate transmission matrix for layer for wavelength w"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_014205 | 13,406 | no_license | [
{
"docstring": "SellmeierLayer(mat_params, thickness, name=None)",
"name": "__init__",
"signature": "def __init__(self, mat_params, thickness, name=None)"
},
{
"docstring": "matrix(w) Generate transmission matrix for layer for wavelength w",
"name": "matrix",
"signature": "def matrix(sel... | 2 | stack_v2_sparse_classes_30k_train_015130 | Implement the Python class `SellmeierLayer` described below.
Class description:
Implement the SellmeierLayer class.
Method signatures and docstrings:
- def __init__(self, mat_params, thickness, name=None): SellmeierLayer(mat_params, thickness, name=None)
- def matrix(self, w): matrix(w) Generate transmission matrix f... | Implement the Python class `SellmeierLayer` described below.
Class description:
Implement the SellmeierLayer class.
Method signatures and docstrings:
- def __init__(self, mat_params, thickness, name=None): SellmeierLayer(mat_params, thickness, name=None)
- def matrix(self, w): matrix(w) Generate transmission matrix f... | dff2309d3b6809066526d67695a6744e7c4234ff | <|skeleton|>
class SellmeierLayer:
def __init__(self, mat_params, thickness, name=None):
"""SellmeierLayer(mat_params, thickness, name=None)"""
<|body_0|>
def matrix(self, w):
"""matrix(w) Generate transmission matrix for layer for wavelength w"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SellmeierLayer:
def __init__(self, mat_params, thickness, name=None):
"""SellmeierLayer(mat_params, thickness, name=None)"""
self.A = mat_params['A']
self.B = mat_params['B']
self.C = mat_params['C']
self.thickness = thickness
self.name = name
def matrix(se... | the_stack_v2_python_sparse | AGTools/Optics/BraggStackModel.py | ahgibbons/AGTools | train | 0 | |
3c412e9552340c68d175e639ad102dc6b271a9f8 | [
"if not isinstance(job_id, basestring) or len(job_id.strip()) == 0:\n raise InvalidParameterException('jid is invalid')\nelif not isinstance(ret, basestring) or len(ret.strip()) == 0:\n raise InvalidParameterException('ret is invalid')\nelif not isinstance(retcode, int):\n raise InvalidParameterException('... | <|body_start_0|>
if not isinstance(job_id, basestring) or len(job_id.strip()) == 0:
raise InvalidParameterException('jid is invalid')
elif not isinstance(ret, basestring) or len(ret.strip()) == 0:
raise InvalidParameterException('ret is invalid')
elif not isinstance(retco... | This factory instantiates command objects to be sent to a cloud commandbus. | CommandFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandFactory:
"""This factory instantiates command objects to be sent to a cloud commandbus."""
def newJobFinishedCommand(self, job_id, ret, retcode):
"""Generates a new JobFinished command :param job_id: An identifier token for the job :type job_id: string :param ret: Usually the ... | stack_v2_sparse_classes_36k_train_014206 | 4,041 | permissive | [
{
"docstring": "Generates a new JobFinished command :param job_id: An identifier token for the job :type job_id: string :param ret: Usually the stdout of the job :type ret: string :param retcode: The exit code of the job :type ret: int :returns: A JobFinished command object :rtype: JobFinished",
"name": "ne... | 4 | null | Implement the Python class `CommandFactory` described below.
Class description:
This factory instantiates command objects to be sent to a cloud commandbus.
Method signatures and docstrings:
- def newJobFinishedCommand(self, job_id, ret, retcode): Generates a new JobFinished command :param job_id: An identifier token ... | Implement the Python class `CommandFactory` described below.
Class description:
This factory instantiates command objects to be sent to a cloud commandbus.
Method signatures and docstrings:
- def newJobFinishedCommand(self, job_id, ret, retcode): Generates a new JobFinished command :param job_id: An identifier token ... | 48573e170771a251f629f2d13dba7173f010a38c | <|skeleton|>
class CommandFactory:
"""This factory instantiates command objects to be sent to a cloud commandbus."""
def newJobFinishedCommand(self, job_id, ret, retcode):
"""Generates a new JobFinished command :param job_id: An identifier token for the job :type job_id: string :param ret: Usually the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommandFactory:
"""This factory instantiates command objects to be sent to a cloud commandbus."""
def newJobFinishedCommand(self, job_id, ret, retcode):
"""Generates a new JobFinished command :param job_id: An identifier token for the job :type job_id: string :param ret: Usually the stdout of the... | the_stack_v2_python_sparse | strongr/clouddomain/factory/commandfactory.py | bigr-erasmusmc/StrongR | train | 0 |
6127e31d5406d5f2be27b8709e02c0c483edaa7c | [
"PolicyOpt.__init__(self, hyperparams, dX, dU)\nself.dX = dX\nself.dU = dU\nself.epochs = hyperparams['epochs']\nself.param_noise_adaption_interval = hyperparams['param_noise_adaption_interval']\nset_global_seeds(hyperparams['seed'])\nself.pol = DDPG(Actor(dU, network=hyperparams['network'], **hyperparams['network_... | <|body_start_0|>
PolicyOpt.__init__(self, hyperparams, dX, dU)
self.dX = dX
self.dU = dU
self.epochs = hyperparams['epochs']
self.param_noise_adaption_interval = hyperparams['param_noise_adaption_interval']
set_global_seeds(hyperparams['seed'])
self.pol = DDPG(Act... | Policy optimization via DDPG. | DDPG_Policy | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DDPG_Policy:
"""Policy optimization via DDPG."""
def __init__(self, hyperparams, dX, dU):
"""Initializes the policy. Args: hyperparams: Dictionary of hyperparameters. dX: Dimension of state space. dU: Dimension of action space."""
<|body_0|>
def update(self, X, U, cs, **... | stack_v2_sparse_classes_36k_train_014207 | 3,468 | permissive | [
{
"docstring": "Initializes the policy. Args: hyperparams: Dictionary of hyperparameters. dX: Dimension of state space. dU: Dimension of action space.",
"name": "__init__",
"signature": "def __init__(self, hyperparams, dX, dU)"
},
{
"docstring": "Perform DDPG update step.",
"name": "update",... | 3 | stack_v2_sparse_classes_30k_train_009389 | Implement the Python class `DDPG_Policy` described below.
Class description:
Policy optimization via DDPG.
Method signatures and docstrings:
- def __init__(self, hyperparams, dX, dU): Initializes the policy. Args: hyperparams: Dictionary of hyperparameters. dX: Dimension of state space. dU: Dimension of action space.... | Implement the Python class `DDPG_Policy` described below.
Class description:
Policy optimization via DDPG.
Method signatures and docstrings:
- def __init__(self, hyperparams, dX, dU): Initializes the policy. Args: hyperparams: Dictionary of hyperparameters. dX: Dimension of state space. dU: Dimension of action space.... | 1a9279a8d2a5e03e0e603c53dbfc982b433a8f60 | <|skeleton|>
class DDPG_Policy:
"""Policy optimization via DDPG."""
def __init__(self, hyperparams, dX, dU):
"""Initializes the policy. Args: hyperparams: Dictionary of hyperparameters. dX: Dimension of state space. dU: Dimension of action space."""
<|body_0|>
def update(self, X, U, cs, **... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DDPG_Policy:
"""Policy optimization via DDPG."""
def __init__(self, hyperparams, dX, dU):
"""Initializes the policy. Args: hyperparams: Dictionary of hyperparameters. dX: Dimension of state space. dU: Dimension of action space."""
PolicyOpt.__init__(self, hyperparams, dX, dU)
self... | the_stack_v2_python_sparse | gps/algorithm/baselines/ddpg.py | Cybernetics-Lab-Aachen/InPulS | train | 1 |
8707e5e042858e7983afaffd4b79b1750bc7684e | [
"self._reader = FileReader([], None)\nself._smiles_list = self._reader.read_delimited_file(configuration.input_smiles_path, standardize=configuration.standardize)\nself._output_model_path = configuration.output_model_path\nself._num_layers = configuration.num_layers\nself._layer_size = configuration.layer_size\nsel... | <|body_start_0|>
self._reader = FileReader([], None)
self._smiles_list = self._reader.read_delimited_file(configuration.input_smiles_path, standardize=configuration.standardize)
self._output_model_path = configuration.output_model_path
self._num_layers = configuration.num_layers
... | CreateModelRunner | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateModelRunner:
def __init__(self, configuration: CreateModelConfiguration, logger: BaseCreateModelLogger):
"""Creates a CreateModelRunner."""
<|body_0|>
def run(self):
"""Carries out the creation of the model."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_014208 | 2,121 | permissive | [
{
"docstring": "Creates a CreateModelRunner.",
"name": "__init__",
"signature": "def __init__(self, configuration: CreateModelConfiguration, logger: BaseCreateModelLogger)"
},
{
"docstring": "Carries out the creation of the model.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021377 | Implement the Python class `CreateModelRunner` described below.
Class description:
Implement the CreateModelRunner class.
Method signatures and docstrings:
- def __init__(self, configuration: CreateModelConfiguration, logger: BaseCreateModelLogger): Creates a CreateModelRunner.
- def run(self): Carries out the creati... | Implement the Python class `CreateModelRunner` described below.
Class description:
Implement the CreateModelRunner class.
Method signatures and docstrings:
- def __init__(self, configuration: CreateModelConfiguration, logger: BaseCreateModelLogger): Creates a CreateModelRunner.
- def run(self): Carries out the creati... | b7324d222a49d18b08335a01649abdb0ac66a734 | <|skeleton|>
class CreateModelRunner:
def __init__(self, configuration: CreateModelConfiguration, logger: BaseCreateModelLogger):
"""Creates a CreateModelRunner."""
<|body_0|>
def run(self):
"""Carries out the creation of the model."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateModelRunner:
def __init__(self, configuration: CreateModelConfiguration, logger: BaseCreateModelLogger):
"""Creates a CreateModelRunner."""
self._reader = FileReader([], None)
self._smiles_list = self._reader.read_delimited_file(configuration.input_smiles_path, standardize=config... | the_stack_v2_python_sparse | running_modes/create_model/create_model.py | MolecularAI/Reinvent | train | 306 | |
753882777d8fbffd46dde4a29d4a63e94196bdd7 | [
"self.make_program = make_program\nif self.make_program is None:\n self.make_program = get_make_tool()",
"if generator is None:\n generator = DEFAULT_CMAKE_GENERATORS.get(self.make_program, 'Unix Makefiles')\ncmake = get_cmake_tool()\nif cmake is None:\n logging.error('No CMake found in Path. Install all... | <|body_start_0|>
self.make_program = make_program
if self.make_program is None:
self.make_program = get_make_tool()
<|end_body_0|>
<|body_start_1|>
if generator is None:
generator = DEFAULT_CMAKE_GENERATORS.get(self.make_program, 'Unix Makefiles')
cmake = get_cma... | Unit test tool to: - prepare build directory - create makefiles - build unit tests - run unit tests - generate code coverage reports | UnitTestTool | [
"SGI-B-1.1",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"MPL-2.0",
"BSD-3-Clause",
"BSD-4-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitTestTool:
"""Unit test tool to: - prepare build directory - create makefiles - build unit tests - run unit tests - generate code coverage reports"""
def __init__(self, make_program=None):
"""Constructor Keyword arguments: make_program - Make tool to use"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_014209 | 6,980 | permissive | [
{
"docstring": "Constructor Keyword arguments: make_program - Make tool to use",
"name": "__init__",
"signature": "def __init__(self, make_program=None)"
},
{
"docstring": "Create Makefiles and prepare targets with CMake. Keyword arguments: path_to_src - Path to source directory generator - Type... | 6 | stack_v2_sparse_classes_30k_train_009717 | Implement the Python class `UnitTestTool` described below.
Class description:
Unit test tool to: - prepare build directory - create makefiles - build unit tests - run unit tests - generate code coverage reports
Method signatures and docstrings:
- def __init__(self, make_program=None): Constructor Keyword arguments: m... | Implement the Python class `UnitTestTool` described below.
Class description:
Unit test tool to: - prepare build directory - create makefiles - build unit tests - run unit tests - generate code coverage reports
Method signatures and docstrings:
- def __init__(self, make_program=None): Constructor Keyword arguments: m... | bf07820e47131a4b72889086692224f5ecc0ddd7 | <|skeleton|>
class UnitTestTool:
"""Unit test tool to: - prepare build directory - create makefiles - build unit tests - run unit tests - generate code coverage reports"""
def __init__(self, make_program=None):
"""Constructor Keyword arguments: make_program - Make tool to use"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnitTestTool:
"""Unit test tool to: - prepare build directory - create makefiles - build unit tests - run unit tests - generate code coverage reports"""
def __init__(self, make_program=None):
"""Constructor Keyword arguments: make_program - Make tool to use"""
self.make_program = make_pro... | the_stack_v2_python_sparse | UNITTESTS/unit_test/test.py | jeromecoutant/mbed | train | 2 |
1cf0c7496dd65a76e2ca3a2cf871e6a1843adb46 | [
"invitation = InvitationService.find_invitation_by_id(invitation_id)\nif invitation is None:\n response, status = ({'message': 'The requested invitation could not be found.'}, http_status.HTTP_404_NOT_FOUND)\nelse:\n response, status = (invitation.as_dict(), http_status.HTTP_200_OK)\nreturn (response, status)... | <|body_start_0|>
invitation = InvitationService.find_invitation_by_id(invitation_id)
if invitation is None:
response, status = ({'message': 'The requested invitation could not be found.'}, http_status.HTTP_404_NOT_FOUND)
else:
response, status = (invitation.as_dict(), htt... | Resource for managing a single invitation. | Invitation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Invitation:
"""Resource for managing a single invitation."""
def get(invitation_id):
"""Get the invitation specified by the provided id."""
<|body_0|>
def patch(invitation_id):
"""Update the invitation specified by the provided id as retried."""
<|body_1|... | stack_v2_sparse_classes_36k_train_014210 | 6,644 | permissive | [
{
"docstring": "Get the invitation specified by the provided id.",
"name": "get",
"signature": "def get(invitation_id)"
},
{
"docstring": "Update the invitation specified by the provided id as retried.",
"name": "patch",
"signature": "def patch(invitation_id)"
},
{
"docstring": "... | 3 | null | Implement the Python class `Invitation` described below.
Class description:
Resource for managing a single invitation.
Method signatures and docstrings:
- def get(invitation_id): Get the invitation specified by the provided id.
- def patch(invitation_id): Update the invitation specified by the provided id as retried.... | Implement the Python class `Invitation` described below.
Class description:
Resource for managing a single invitation.
Method signatures and docstrings:
- def get(invitation_id): Get the invitation specified by the provided id.
- def patch(invitation_id): Update the invitation specified by the provided id as retried.... | 923cb8a3ee88dcbaf0fe800ca70022b3c13c1d01 | <|skeleton|>
class Invitation:
"""Resource for managing a single invitation."""
def get(invitation_id):
"""Get the invitation specified by the provided id."""
<|body_0|>
def patch(invitation_id):
"""Update the invitation specified by the provided id as retried."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Invitation:
"""Resource for managing a single invitation."""
def get(invitation_id):
"""Get the invitation specified by the provided id."""
invitation = InvitationService.find_invitation_by_id(invitation_id)
if invitation is None:
response, status = ({'message': 'The r... | the_stack_v2_python_sparse | auth-api/src/auth_api/resources/invitation.py | bcgov/sbc-auth | train | 13 |
942141b19900eda88e50fa78cdad2de0a173b99c | [
"self.client = xmlrpc.client.ServerProxy(server_url)\nself.user = user\nself.destination = destination\nself._running = False\nself._message_reader = threading.Thread(target=self._read_messages)\nself.lock = threading.Lock()\nself.logger = QChatLogger('QChatCLIRPCClient-{}'.format(user))",
"print('Hello, this is ... | <|body_start_0|>
self.client = xmlrpc.client.ServerProxy(server_url)
self.user = user
self.destination = destination
self._running = False
self._message_reader = threading.Thread(target=self._read_messages)
self.lock = threading.Lock()
self.logger = QChatLogger('Q... | Simple RPC client that sends messages to an RPCServer | QChatCLIRPCClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QChatCLIRPCClient:
"""Simple RPC client that sends messages to an RPCServer"""
def __init__(self, user, destination, server_url):
"""Initializes the RPC client :param user: str The user we wish to send a message as :param destination: str The peer we wish to send a message to :param ... | stack_v2_sparse_classes_36k_train_014211 | 5,230 | permissive | [
{
"docstring": "Initializes the RPC client :param user: str The user we wish to send a message as :param destination: str The peer we wish to send a message to :param server_url: str The RPCServer url to connect to, eg. http://127.0.0.1:6666",
"name": "__init__",
"signature": "def __init__(self, user, d... | 4 | stack_v2_sparse_classes_30k_train_007673 | Implement the Python class `QChatCLIRPCClient` described below.
Class description:
Simple RPC client that sends messages to an RPCServer
Method signatures and docstrings:
- def __init__(self, user, destination, server_url): Initializes the RPC client :param user: str The user we wish to send a message as :param desti... | Implement the Python class `QChatCLIRPCClient` described below.
Class description:
Simple RPC client that sends messages to an RPCServer
Method signatures and docstrings:
- def __init__(self, user, destination, server_url): Initializes the RPC client :param user: str The user we wish to send a message as :param desti... | a393d530b9d289ba2a75682cd1d4a07d40776785 | <|skeleton|>
class QChatCLIRPCClient:
"""Simple RPC client that sends messages to an RPCServer"""
def __init__(self, user, destination, server_url):
"""Initializes the RPC client :param user: str The user we wish to send a message as :param destination: str The peer we wish to send a message to :param ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QChatCLIRPCClient:
"""Simple RPC client that sends messages to an RPCServer"""
def __init__(self, user, destination, server_url):
"""Initializes the RPC client :param user: str The user we wish to send a message as :param destination: str The peer we wish to send a message to :param server_url: s... | the_stack_v2_python_sparse | qchat/rpc.py | mdskrzypczyk/QChat | train | 4 |
9f77000fba4809829eb5dd4e313488b10c14cf5f | [
"self.lifespan = 0\nself.hidden = hyperparameters['hidden_dim']\nself.env = evo_gym.make(hyperparameters['environment'])\nself.env_state = self.env.reset()\nself.discrete_action = type(self.env.action_space) is evo_gym.spaces.Discrete\nself.network = RecurrentNeuralNetwork(hidden=self.hidden, output_dim=self.env.ac... | <|body_start_0|>
self.lifespan = 0
self.hidden = hyperparameters['hidden_dim']
self.env = evo_gym.make(hyperparameters['environment'])
self.env_state = self.env.reset()
self.discrete_action = type(self.env.action_space) is evo_gym.spaces.Discrete
self.network = RecurrentN... | Individual self-replication structure | Replicator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Replicator:
"""Individual self-replication structure"""
def __init__(self, hyperparameters):
"""Initialize replicator :param hyperparameters: (dict) dictionary of hyperparameters"""
<|body_0|>
def reset(self):
"""Reset internal parameters and environment :return:... | stack_v2_sparse_classes_36k_train_014212 | 8,990 | permissive | [
{
"docstring": "Initialize replicator :param hyperparameters: (dict) dictionary of hyperparameters",
"name": "__init__",
"signature": "def __init__(self, hyperparameters)"
},
{
"docstring": "Reset internal parameters and environment :return: None",
"name": "reset",
"signature": "def rese... | 4 | stack_v2_sparse_classes_30k_train_008550 | Implement the Python class `Replicator` described below.
Class description:
Individual self-replication structure
Method signatures and docstrings:
- def __init__(self, hyperparameters): Initialize replicator :param hyperparameters: (dict) dictionary of hyperparameters
- def reset(self): Reset internal parameters and... | Implement the Python class `Replicator` described below.
Class description:
Individual self-replication structure
Method signatures and docstrings:
- def __init__(self, hyperparameters): Initialize replicator :param hyperparameters: (dict) dictionary of hyperparameters
- def reset(self): Reset internal parameters and... | 1a6f8225378b59423a97b439b56710bbed2754e9 | <|skeleton|>
class Replicator:
"""Individual self-replication structure"""
def __init__(self, hyperparameters):
"""Initialize replicator :param hyperparameters: (dict) dictionary of hyperparameters"""
<|body_0|>
def reset(self):
"""Reset internal parameters and environment :return:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Replicator:
"""Individual self-replication structure"""
def __init__(self, hyperparameters):
"""Initialize replicator :param hyperparameters: (dict) dictionary of hyperparameters"""
self.lifespan = 0
self.hidden = hyperparameters['hidden_dim']
self.env = evo_gym.make(hyper... | the_stack_v2_python_sparse | evo_replicators/evolutionary_replicator.py | SamuelSchmidgall/EvolutionarySelfReplication | train | 14 |
f7e48aca3024b9b2e9cf6ffed92ca46a6118459b | [
"keys = [key for key in self.settings.keys()]\nurls = ['http://scrape-target:8888']\nfor url in urls:\n yield scrapy.Request(url=url, callback=self.parse, errback=self.on_error, meta={'year': 2018})",
"year = response.meta.get('year', {})\nfor href in response.css('.doc-page-link::attr(\"href\")').extract():\n... | <|body_start_0|>
keys = [key for key in self.settings.keys()]
urls = ['http://scrape-target:8888']
for url in urls:
yield scrapy.Request(url=url, callback=self.parse, errback=self.on_error, meta={'year': 2018})
<|end_body_0|>
<|body_start_1|>
year = response.meta.get('year',... | AcmeSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AcmeSpider:
def start_requests(self):
"""This sets up the urls to scrape for each years."""
<|body_0|>
def parse(self, response):
"""Parse the articles listing page and go to the next one. @url http://apps.who.int/iris/discover?rpp=3 @returns items 0 0 @returns reque... | stack_v2_sparse_classes_36k_train_014213 | 2,850 | permissive | [
{
"docstring": "This sets up the urls to scrape for each years.",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "Parse the articles listing page and go to the next one. @url http://apps.who.int/iris/discover?rpp=3 @returns items 0 0 @returns requests 3 4",
... | 3 | null | Implement the Python class `AcmeSpider` described below.
Class description:
Implement the AcmeSpider class.
Method signatures and docstrings:
- def start_requests(self): This sets up the urls to scrape for each years.
- def parse(self, response): Parse the articles listing page and go to the next one. @url http://app... | Implement the Python class `AcmeSpider` described below.
Class description:
Implement the AcmeSpider class.
Method signatures and docstrings:
- def start_requests(self): This sets up the urls to scrape for each years.
- def parse(self, response): Parse the articles listing page and go to the next one. @url http://app... | 1aa42c7d8aaf0a91d033af8448a33f37563b0365 | <|skeleton|>
class AcmeSpider:
def start_requests(self):
"""This sets up the urls to scrape for each years."""
<|body_0|>
def parse(self, response):
"""Parse the articles listing page and go to the next one. @url http://apps.who.int/iris/discover?rpp=3 @returns items 0 0 @returns reque... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AcmeSpider:
def start_requests(self):
"""This sets up the urls to scrape for each years."""
keys = [key for key in self.settings.keys()]
urls = ['http://scrape-target:8888']
for url in urls:
yield scrapy.Request(url=url, callback=self.parse, errback=self.on_error, m... | the_stack_v2_python_sparse | pipeline/reach-scraper/wsf_scraping/spiders/acme_spider.py | wellcometrust/reach | train | 12 | |
0bfa1d803ddc38d6018d8abdcf117b8b6caf3f35 | [
"self.__mailer = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))\nself.__app_url = os.environ.get('APP_URL')\nself.__from_email = os.environ.get('SENDGRID_USERNAME')",
"title = '[NgPy-Accounts-Manager] Reminder: ' + max_level\nhtml = self.build_template('emails/reminder.html', title, reminde... | <|body_start_0|>
self.__mailer = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
self.__app_url = os.environ.get('APP_URL')
self.__from_email = os.environ.get('SENDGRID_USERNAME')
<|end_body_0|>
<|body_start_1|>
title = '[NgPy-Accounts-Manager] Reminder: ' + max_le... | The notification service class that defines all business operations. | NotificationService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotificationService:
"""The notification service class that defines all business operations."""
def __init__(self):
"""Constructor"""
<|body_0|>
def send_reminder(self, max_level: str, notifications: List[Notification], user_email: str) -> None:
"""Sends a list o... | stack_v2_sparse_classes_36k_train_014214 | 2,775 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Sends a list of notifications as email to a provided email address. :param max_level: the max level :param notifications: the list of notifications :param user_email: the user email",
"name... | 4 | null | Implement the Python class `NotificationService` described below.
Class description:
The notification service class that defines all business operations.
Method signatures and docstrings:
- def __init__(self): Constructor
- def send_reminder(self, max_level: str, notifications: List[Notification], user_email: str) ->... | Implement the Python class `NotificationService` described below.
Class description:
The notification service class that defines all business operations.
Method signatures and docstrings:
- def __init__(self): Constructor
- def send_reminder(self, max_level: str, notifications: List[Notification], user_email: str) ->... | b49396f6552567fe1d2c4bcb2f14e5ec44f7dc3b | <|skeleton|>
class NotificationService:
"""The notification service class that defines all business operations."""
def __init__(self):
"""Constructor"""
<|body_0|>
def send_reminder(self, max_level: str, notifications: List[Notification], user_email: str) -> None:
"""Sends a list o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotificationService:
"""The notification service class that defines all business operations."""
def __init__(self):
"""Constructor"""
self.__mailer = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
self.__app_url = os.environ.get('APP_URL')
self.__fro... | the_stack_v2_python_sparse | ngpy-accounts-manager-api/api/domain/services/notification_service.py | egoettelmann/ngpy-accounts-manager | train | 0 |
a6a6a6648111f73d25432ea79cb7956e909786e5 | [
"self._source = source\nself._time_provider = time_provider\nself._storage_engine = storage_engine",
"if inbox_task.archived:\n return\nasync with self._storage_engine.get_unit_of_work() as uow:\n inbox_task = inbox_task.mark_archived(self._source, self._time_provider.get_current_time())\n await uow.inbo... | <|body_start_0|>
self._source = source
self._time_provider = time_provider
self._storage_engine = storage_engine
<|end_body_0|>
<|body_start_1|>
if inbox_task.archived:
return
async with self._storage_engine.get_unit_of_work() as uow:
inbox_task = inbox_t... | Shared service for archiving an inbox task. | InboxTaskArchiveService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InboxTaskArchiveService:
"""Shared service for archiving an inbox task."""
def __init__(self, source: EventSource, time_provider: TimeProvider, storage_engine: DomainStorageEngine) -> None:
"""Constructor."""
<|body_0|>
async def do_it(self, progress_reporter: ProgressRe... | stack_v2_sparse_classes_36k_train_014215 | 1,457 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, source: EventSource, time_provider: TimeProvider, storage_engine: DomainStorageEngine) -> None"
},
{
"docstring": "Execute the service's action.",
"name": "do_it",
"signature": "async def do_it(self, prog... | 2 | stack_v2_sparse_classes_30k_train_014510 | Implement the Python class `InboxTaskArchiveService` described below.
Class description:
Shared service for archiving an inbox task.
Method signatures and docstrings:
- def __init__(self, source: EventSource, time_provider: TimeProvider, storage_engine: DomainStorageEngine) -> None: Constructor.
- async def do_it(sel... | Implement the Python class `InboxTaskArchiveService` described below.
Class description:
Shared service for archiving an inbox task.
Method signatures and docstrings:
- def __init__(self, source: EventSource, time_provider: TimeProvider, storage_engine: DomainStorageEngine) -> None: Constructor.
- async def do_it(sel... | 911ecd560142a9b4e57498f2b090f9469a0718a1 | <|skeleton|>
class InboxTaskArchiveService:
"""Shared service for archiving an inbox task."""
def __init__(self, source: EventSource, time_provider: TimeProvider, storage_engine: DomainStorageEngine) -> None:
"""Constructor."""
<|body_0|>
async def do_it(self, progress_reporter: ProgressRe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InboxTaskArchiveService:
"""Shared service for archiving an inbox task."""
def __init__(self, source: EventSource, time_provider: TimeProvider, storage_engine: DomainStorageEngine) -> None:
"""Constructor."""
self._source = source
self._time_provider = time_provider
self._... | the_stack_v2_python_sparse | src/core/jupiter/core/domain/inbox_tasks/service/archive_service.py | horia141/jupiter | train | 16 |
5b19dc84638981ff751eca5106c63a5b28d5c25c | [
"if request.dbsession is None:\n raise DBAPIError\nreturn request.dbsession.query(cls).get(pk)",
"if request.dbsession is None:\n raise DBAPIError\nportfolio = cls(**kwargs)\nrequest.dbsession.add(portfolio)\nreturn request.dbsession.query(cls).filter(cls.name == kwargs['name']).one_or_none()"
] | <|body_start_0|>
if request.dbsession is None:
raise DBAPIError
return request.dbsession.query(cls).get(pk)
<|end_body_0|>
<|body_start_1|>
if request.dbsession is None:
raise DBAPIError
portfolio = cls(**kwargs)
request.dbsession.add(portfolio)
r... | Creates a new portfolio and DB table. | Portfolio | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Portfolio:
"""Creates a new portfolio and DB table."""
def one(cls, request=None, pk=None):
"""Retrieve a single instance from the database by the primary key for that record"""
<|body_0|>
def new(cls, request, **kwargs):
"""Create a single new instance of the Po... | stack_v2_sparse_classes_36k_train_014216 | 1,416 | permissive | [
{
"docstring": "Retrieve a single instance from the database by the primary key for that record",
"name": "one",
"signature": "def one(cls, request=None, pk=None)"
},
{
"docstring": "Create a single new instance of the Portfolio class",
"name": "new",
"signature": "def new(cls, request, ... | 2 | stack_v2_sparse_classes_30k_train_010581 | Implement the Python class `Portfolio` described below.
Class description:
Creates a new portfolio and DB table.
Method signatures and docstrings:
- def one(cls, request=None, pk=None): Retrieve a single instance from the database by the primary key for that record
- def new(cls, request, **kwargs): Create a single n... | Implement the Python class `Portfolio` described below.
Class description:
Creates a new portfolio and DB table.
Method signatures and docstrings:
- def one(cls, request=None, pk=None): Retrieve a single instance from the database by the primary key for that record
- def new(cls, request, **kwargs): Create a single n... | 1e5993f72d70d55ccab65034c0b2512e96ad57cc | <|skeleton|>
class Portfolio:
"""Creates a new portfolio and DB table."""
def one(cls, request=None, pk=None):
"""Retrieve a single instance from the database by the primary key for that record"""
<|body_0|>
def new(cls, request, **kwargs):
"""Create a single new instance of the Po... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Portfolio:
"""Creates a new portfolio and DB table."""
def one(cls, request=None, pk=None):
"""Retrieve a single instance from the database by the primary key for that record"""
if request.dbsession is None:
raise DBAPIError
return request.dbsession.query(cls).get(pk)
... | the_stack_v2_python_sparse | stocks_api/models/portfolio.py | SeattleChris/stocks_api | train | 0 |
0160ecab36ea1f07c00b55ee03c26049ae9cd383 | [
"@lru_cache(None)\ndef word_break(i):\n if i == len(s):\n return [[]]\n ret = []\n for j in range(i + 1, len(s) + 1):\n if s[i:j] in words:\n ret.extend([[s[i:j]] + l for l in word_break(j)])\n return ret\nwords = set(wordDict)\ns = s\nreturn [' '.join(x) for x in word_break(0)]... | <|body_start_0|>
@lru_cache(None)
def word_break(i):
if i == len(s):
return [[]]
ret = []
for j in range(i + 1, len(s) + 1):
if s[i:j] in words:
ret.extend([[s[i:j]] + l for l in word_break(j)])
return re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
"""Oct 23, 2018 06:43"""
<|body_0|>
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
"""Mar 05, 2023 13:22"""
<|body_1|>
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
"""M... | stack_v2_sparse_classes_36k_train_014217 | 3,077 | no_license | [
{
"docstring": "Oct 23, 2018 06:43",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
},
{
"docstring": "Mar 05, 2023 13:22",
"name": "wordBreak",
"signature": "def wordBreak(self, s: str, wordDict: List[str]) -> List[str]"
},
{
"docstring": "Mar 05, 2023 13:2... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): Oct 23, 2018 06:43
- def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: Mar 05, 2023 13:22
- def wordBreak(self, s: str, wordDict: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): Oct 23, 2018 06:43
- def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: Mar 05, 2023 13:22
- def wordBreak(self, s: str, wordDict: L... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
"""Oct 23, 2018 06:43"""
<|body_0|>
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
"""Mar 05, 2023 13:22"""
<|body_1|>
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
"""M... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak(self, s, wordDict):
"""Oct 23, 2018 06:43"""
@lru_cache(None)
def word_break(i):
if i == len(s):
return [[]]
ret = []
for j in range(i + 1, len(s) + 1):
if s[i:j] in words:
r... | the_stack_v2_python_sparse | leetcode/solved/140_Word_Break_II/solution.py | sungminoh/algorithms | train | 0 | |
b98820ba43e5b66c5148548ba6cce33dea99eae1 | [
"url = reverse('create_drone')\ndata = {'battery': '5.0'}\nresponse = self.client.post(url, data, format='json', **header)\nself.assertEqual(response.status_code, status.HTTP_201_CREATED)\nself.assertEqual(Drone.objects.count(), 1)\nself.assertEqual(json.loads(response.content), {'success': drone_created})",
"url... | <|body_start_0|>
url = reverse('create_drone')
data = {'battery': '5.0'}
response = self.client.post(url, data, format='json', **header)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Drone.objects.count(), 1)
self.assertEqual(json.loads(... | CreateDroneTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateDroneTest:
def test_drone_create_0(self):
"""Ensure we can create a drone when warehouse is not passed"""
<|body_0|>
def test_create_drone_1(self):
"""Ensure we can create a drone when warehouse is passed"""
<|body_1|>
def test_create_drone_2(self)... | stack_v2_sparse_classes_36k_train_014218 | 8,074 | no_license | [
{
"docstring": "Ensure we can create a drone when warehouse is not passed",
"name": "test_drone_create_0",
"signature": "def test_drone_create_0(self)"
},
{
"docstring": "Ensure we can create a drone when warehouse is passed",
"name": "test_create_drone_1",
"signature": "def test_create_... | 4 | stack_v2_sparse_classes_30k_train_019670 | Implement the Python class `CreateDroneTest` described below.
Class description:
Implement the CreateDroneTest class.
Method signatures and docstrings:
- def test_drone_create_0(self): Ensure we can create a drone when warehouse is not passed
- def test_create_drone_1(self): Ensure we can create a drone when warehous... | Implement the Python class `CreateDroneTest` described below.
Class description:
Implement the CreateDroneTest class.
Method signatures and docstrings:
- def test_drone_create_0(self): Ensure we can create a drone when warehouse is not passed
- def test_create_drone_1(self): Ensure we can create a drone when warehous... | 7538efd2edb6b1d80c63b645a953372491ccff81 | <|skeleton|>
class CreateDroneTest:
def test_drone_create_0(self):
"""Ensure we can create a drone when warehouse is not passed"""
<|body_0|>
def test_create_drone_1(self):
"""Ensure we can create a drone when warehouse is passed"""
<|body_1|>
def test_create_drone_2(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateDroneTest:
def test_drone_create_0(self):
"""Ensure we can create a drone when warehouse is not passed"""
url = reverse('create_drone')
data = {'battery': '5.0'}
response = self.client.post(url, data, format='json', **header)
self.assertEqual(response.status_code,... | the_stack_v2_python_sparse | api/logistics/logistics/drone/tests.py | dev1911/drone_plus_plus | train | 2 | |
d6d013ecf9167030c28e20f045494d47640981d2 | [
"n = len(nums)\nans = 0\nfor i in range(n):\n prod = 1\n for j in range(i, n):\n prod *= nums[j]\n if prod >= k:\n continue\n else:\n ans += 1\nreturn ans",
"if k <= 1:\n return 0\nn = len(nums)\nl = 0\nprod = 1\nans = 0\nfor r in range(n):\n prod *= nums[r]\... | <|body_start_0|>
n = len(nums)
ans = 0
for i in range(n):
prod = 1
for j in range(i, n):
prod *= nums[j]
if prod >= k:
continue
else:
ans += 1
return ans
<|end_body_0|>
<|body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
"""Brute Force, Time: O(n^2), Space: O(1)"""
<|body_0|>
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
"""Sliding Window, Time: O(n), Space: O(1)"""
<|bod... | stack_v2_sparse_classes_36k_train_014219 | 1,521 | no_license | [
{
"docstring": "Brute Force, Time: O(n^2), Space: O(1)",
"name": "numSubarrayProductLessThanK",
"signature": "def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int"
},
{
"docstring": "Sliding Window, Time: O(n), Space: O(1)",
"name": "numSubarrayProductLessThanK",
"signat... | 2 | stack_v2_sparse_classes_30k_train_016827 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: Brute Force, Time: O(n^2), Space: O(1)
- def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: Brute Force, Time: O(n^2), Space: O(1)
- def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> ... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
"""Brute Force, Time: O(n^2), Space: O(1)"""
<|body_0|>
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
"""Sliding Window, Time: O(n), Space: O(1)"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
"""Brute Force, Time: O(n^2), Space: O(1)"""
n = len(nums)
ans = 0
for i in range(n):
prod = 1
for j in range(i, n):
prod *= nums[j]
if prod ... | the_stack_v2_python_sparse | python/713-Subarray Product Less Than K.py | cwza/leetcode | train | 0 | |
e9a234d6d46f2c4b41916a646ac1060904b6d993 | [
"self.readers = [Reader(datapath=path, groupname=group) for path, group in zip(inpaths, ingroups)]\nfor reader in self.readers:\n reader.get_info()\nassert len(np.unique([r.size for r in self.readers])) == 1, 'not all input arrays have equal size'\nself.weights = weights\nif not self.weights is None:\n assert... | <|body_start_0|>
self.readers = [Reader(datapath=path, groupname=group) for path, group in zip(inpaths, ingroups)]
for reader in self.readers:
reader.get_info()
assert len(np.unique([r.size for r in self.readers])) == 1, 'not all input arrays have equal size'
self.weights = w... | Designed to merge already pre-processed netcdf files (daily values) It opens multiple readers and a single writer. Possible to supply weights when averaging | DataMerger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataMerger:
"""Designed to merge already pre-processed netcdf files (daily values) It opens multiple readers and a single writer. Possible to supply weights when averaging"""
def __init__(self, inpaths: list, ingroups: list, outpath: Path, outvarname: str, region: Region, weights: list=None)... | stack_v2_sparse_classes_36k_train_014220 | 22,921 | no_license | [
{
"docstring": "Needs a list of inpaths, a list of ingroups and a single outpath, potentially a list of weights with the same size There is no constrained on the weight values as these are processed in np.ma.average as: avg = sum(a * weights) / sum(weights) Initializer also checks the information of arrays at i... | 2 | stack_v2_sparse_classes_30k_train_011454 | Implement the Python class `DataMerger` described below.
Class description:
Designed to merge already pre-processed netcdf files (daily values) It opens multiple readers and a single writer. Possible to supply weights when averaging
Method signatures and docstrings:
- def __init__(self, inpaths: list, ingroups: list,... | Implement the Python class `DataMerger` described below.
Class description:
Designed to merge already pre-processed netcdf files (daily values) It opens multiple readers and a single writer. Possible to supply weights when averaging
Method signatures and docstrings:
- def __init__(self, inpaths: list, ingroups: list,... | 8d8f8d5bbe39ab6ffc8a71acfbba8b89e001579b | <|skeleton|>
class DataMerger:
"""Designed to merge already pre-processed netcdf files (daily values) It opens multiple readers and a single writer. Possible to supply weights when averaging"""
def __init__(self, inpaths: list, ingroups: list, outpath: Path, outvarname: str, region: Region, weights: list=None)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataMerger:
"""Designed to merge already pre-processed netcdf files (daily values) It opens multiple readers and a single writer. Possible to supply weights when averaging"""
def __init__(self, inpaths: list, ingroups: list, outpath: Path, outvarname: str, region: Region, weights: list=None):
"""... | the_stack_v2_python_sparse | Weave/downloaders.py | chiemvs/Weave | train | 2 |
1b6ac686ffcae1ec157f3904d6ddf975298a264c | [
"super(RPN, self).__init__()\nstride = 1\npadding = 1\nbias = True\nself.num_anchors = len(ratios) * len(scales)\nself.RPN_conv = nn.Conv2d(input_depth, output_depth, size, stride, padding, bias=bias)\nself.ncls_out = self.num_anchors\nself.RPN_cls_score = nn.Conv2d(output_depth, self.ncls_out, 1, 1)\nself.RPN_cls_... | <|body_start_0|>
super(RPN, self).__init__()
stride = 1
padding = 1
bias = True
self.num_anchors = len(ratios) * len(scales)
self.RPN_conv = nn.Conv2d(input_depth, output_depth, size, stride, padding, bias=bias)
self.ncls_out = self.num_anchors
self.RPN_cl... | RPN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RPN:
def __init__(self, input_depth, output_depth, ratios, scales, size=3):
"""Initialize a region Proposal network :param input_depth: number of filters coming out of the backbone :param size: window size of RPN (kernel)"""
<|body_0|>
def forward(self, feature_map):
... | stack_v2_sparse_classes_36k_train_014221 | 1,812 | no_license | [
{
"docstring": "Initialize a region Proposal network :param input_depth: number of filters coming out of the backbone :param size: window size of RPN (kernel)",
"name": "__init__",
"signature": "def __init__(self, input_depth, output_depth, ratios, scales, size=3)"
},
{
"docstring": "process the... | 2 | stack_v2_sparse_classes_30k_train_005361 | Implement the Python class `RPN` described below.
Class description:
Implement the RPN class.
Method signatures and docstrings:
- def __init__(self, input_depth, output_depth, ratios, scales, size=3): Initialize a region Proposal network :param input_depth: number of filters coming out of the backbone :param size: wi... | Implement the Python class `RPN` described below.
Class description:
Implement the RPN class.
Method signatures and docstrings:
- def __init__(self, input_depth, output_depth, ratios, scales, size=3): Initialize a region Proposal network :param input_depth: number of filters coming out of the backbone :param size: wi... | 225acd5dcde2ab225761ce83f5c9b42e33fdd27c | <|skeleton|>
class RPN:
def __init__(self, input_depth, output_depth, ratios, scales, size=3):
"""Initialize a region Proposal network :param input_depth: number of filters coming out of the backbone :param size: window size of RPN (kernel)"""
<|body_0|>
def forward(self, feature_map):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RPN:
def __init__(self, input_depth, output_depth, ratios, scales, size=3):
"""Initialize a region Proposal network :param input_depth: number of filters coming out of the backbone :param size: window size of RPN (kernel)"""
super(RPN, self).__init__()
stride = 1
padding = 1
... | the_stack_v2_python_sparse | model/rpn/rpn.py | UW-COSMOS/mmmask-rcnn | train | 2 | |
888fe82b483a24c97ff26a521d7bd8dca6e887ab | [
"if not new_frame.is_from_camera:\n frame_difference = float(abs(new_frame.framePos - old_frame.framePos))\n time_difference = frame_difference * float(1 / new_frame.fps)\nelse:\n return 0\npixel_difference = float(abs(new_car.centerx - old_car.centerx))\nratio = Classyfication.get_ratio()\nmeters_differen... | <|body_start_0|>
if not new_frame.is_from_camera:
frame_difference = float(abs(new_frame.framePos - old_frame.framePos))
time_difference = frame_difference * float(1 / new_frame.fps)
else:
return 0
pixel_difference = float(abs(new_car.centerx - old_car.centerx... | Klasa dokonująca pomiaru prędkości. | SpeedMeasurment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpeedMeasurment:
"""Klasa dokonująca pomiaru prędkości."""
def calculate_speed(new_car: Vehicle, new_frame: Frame, old_car: Vehicle, old_frame: Frame):
"""Oblicza prędkość wykretego pojazdu. :param Vehicle new_car: Samochód opuszczający w pole detekcji. :param Frame new_frame: Ramka ... | stack_v2_sparse_classes_36k_train_014222 | 14,920 | no_license | [
{
"docstring": "Oblicza prędkość wykretego pojazdu. :param Vehicle new_car: Samochód opuszczający w pole detekcji. :param Frame new_frame: Ramka obrazu przechwycona podczas opuszczania przez pojazd pola detekcji. :param Vehicle old_car: Samochód wjeżdżający w pole detekcji. :param Frame old_frame: Ramka obrazu ... | 2 | stack_v2_sparse_classes_30k_train_011655 | Implement the Python class `SpeedMeasurment` described below.
Class description:
Klasa dokonująca pomiaru prędkości.
Method signatures and docstrings:
- def calculate_speed(new_car: Vehicle, new_frame: Frame, old_car: Vehicle, old_frame: Frame): Oblicza prędkość wykretego pojazdu. :param Vehicle new_car: Samochód opu... | Implement the Python class `SpeedMeasurment` described below.
Class description:
Klasa dokonująca pomiaru prędkości.
Method signatures and docstrings:
- def calculate_speed(new_car: Vehicle, new_frame: Frame, old_car: Vehicle, old_frame: Frame): Oblicza prędkość wykretego pojazdu. :param Vehicle new_car: Samochód opu... | c8d6be403f12e01d3a2c0ea671363f20eeb08ce4 | <|skeleton|>
class SpeedMeasurment:
"""Klasa dokonująca pomiaru prędkości."""
def calculate_speed(new_car: Vehicle, new_frame: Frame, old_car: Vehicle, old_frame: Frame):
"""Oblicza prędkość wykretego pojazdu. :param Vehicle new_car: Samochód opuszczający w pole detekcji. :param Frame new_frame: Ramka ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpeedMeasurment:
"""Klasa dokonująca pomiaru prędkości."""
def calculate_speed(new_car: Vehicle, new_frame: Frame, old_car: Vehicle, old_frame: Frame):
"""Oblicza prędkość wykretego pojazdu. :param Vehicle new_car: Samochód opuszczający w pole detekcji. :param Frame new_frame: Ramka obrazu przech... | the_stack_v2_python_sparse | src/classify.py | djgrasss/videodetection | train | 0 |
56eeab54fb6d4321ce648423f995a933bbec8eda | [
"self.city = city\nself.state = state\nself.country = country\nself.postal_code = postal_code\nself.address_line_1 = address_line_1\nself.address_line_2 = address_line_2\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\ncity = dictionary.get('city')\nstate = dictionar... | <|body_start_0|>
self.city = city
self.state = state
self.country = country
self.postal_code = postal_code
self.address_line_1 = address_line_1
self.address_line_2 = address_line_2
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>... | Implementation of the 'Institution Address' model. The address for the financial institution Attributes: city (string): The city of the institution’s headquarters state (string): Two-letter code for the state of the institution’s headquarters country (string): The country of the institution’s headquarters postal_code (... | InstitutionAddress | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstitutionAddress:
"""Implementation of the 'Institution Address' model. The address for the financial institution Attributes: city (string): The city of the institution’s headquarters state (string): Two-letter code for the state of the institution’s headquarters country (string): The country o... | stack_v2_sparse_classes_36k_train_014223 | 3,105 | permissive | [
{
"docstring": "Constructor for the InstitutionAddress class",
"name": "__init__",
"signature": "def __init__(self, city=None, state=None, country=None, postal_code=None, address_line_1=None, address_line_2=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model fro... | 2 | null | Implement the Python class `InstitutionAddress` described below.
Class description:
Implementation of the 'Institution Address' model. The address for the financial institution Attributes: city (string): The city of the institution’s headquarters state (string): Two-letter code for the state of the institution’s headq... | Implement the Python class `InstitutionAddress` described below.
Class description:
Implementation of the 'Institution Address' model. The address for the financial institution Attributes: city (string): The city of the institution’s headquarters state (string): Two-letter code for the state of the institution’s headq... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class InstitutionAddress:
"""Implementation of the 'Institution Address' model. The address for the financial institution Attributes: city (string): The city of the institution’s headquarters state (string): Two-letter code for the state of the institution’s headquarters country (string): The country o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstitutionAddress:
"""Implementation of the 'Institution Address' model. The address for the financial institution Attributes: city (string): The city of the institution’s headquarters state (string): Two-letter code for the state of the institution’s headquarters country (string): The country of the institu... | the_stack_v2_python_sparse | finicityapi/models/institution_address.py | monarchmoney/finicity-python | train | 0 |
98db034bcef575d979fd1bcbf9d53896af0819c0 | [
"super().__init__(logger)\nself.HEARTBEAT_MESSAGES = None\nself.DEVICE_MESSAGES = None",
"super().on_channel_open(channel)\nself.HEARTBEAT_MESSAGES = HeartbeatMessage(self._connection, self._channel)\nself.DEVICE_MESSAGES = DeviceMessage(self._channel)",
"self.HEARTBEAT_MESSAGES.set_stopping(True)\nself.DEVICE_... | <|body_start_0|>
super().__init__(logger)
self.HEARTBEAT_MESSAGES = None
self.DEVICE_MESSAGES = None
<|end_body_0|>
<|body_start_1|>
super().on_channel_open(channel)
self.HEARTBEAT_MESSAGES = HeartbeatMessage(self._connection, self._channel)
self.DEVICE_MESSAGES = Device... | Communicate with Devices via RabbitMQ. | DeviceReceiver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceReceiver:
"""Communicate with Devices via RabbitMQ."""
def __init__(self, logger):
"""Overwrite the Receiver __init__."""
<|body_0|>
def on_channel_open(self, channel):
"""Overwrite the on_channel_open method. Run all of the normal on_channel_open commands,... | stack_v2_sparse_classes_36k_train_014224 | 9,633 | permissive | [
{
"docstring": "Overwrite the Receiver __init__.",
"name": "__init__",
"signature": "def __init__(self, logger)"
},
{
"docstring": "Overwrite the on_channel_open method. Run all of the normal on_channel_open commands, then create the HEARTBEAT_MESSAGES and DEVICE_MESSAGES objects.",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_005116 | Implement the Python class `DeviceReceiver` described below.
Class description:
Communicate with Devices via RabbitMQ.
Method signatures and docstrings:
- def __init__(self, logger): Overwrite the Receiver __init__.
- def on_channel_open(self, channel): Overwrite the on_channel_open method. Run all of the normal on_c... | Implement the Python class `DeviceReceiver` described below.
Class description:
Communicate with Devices via RabbitMQ.
Method signatures and docstrings:
- def __init__(self, logger): Overwrite the Receiver __init__.
- def on_channel_open(self, channel): Overwrite the on_channel_open method. Run all of the normal on_c... | 7d37690a8c42091a5892aa45518bfe6003728a18 | <|skeleton|>
class DeviceReceiver:
"""Communicate with Devices via RabbitMQ."""
def __init__(self, logger):
"""Overwrite the Receiver __init__."""
<|body_0|>
def on_channel_open(self, channel):
"""Overwrite the on_channel_open method. Run all of the normal on_channel_open commands,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeviceReceiver:
"""Communicate with Devices via RabbitMQ."""
def __init__(self, logger):
"""Overwrite the Receiver __init__."""
super().__init__(logger)
self.HEARTBEAT_MESSAGES = None
self.DEVICE_MESSAGES = None
def on_channel_open(self, channel):
"""Overwrite... | the_stack_v2_python_sparse | server/fm_server/device/service.py | nstoik/farm_monitor | train | 0 |
f09dd69e18fc59438972ed00cbcfcd8371a56b91 | [
"self.path = os.path.realpath(os.path.dirname(os.path.dirname(__file__))) + dirName\nself.encoding = encoding\nself.config = configparser.ConfigParser()\nself.keys = MyConfig('token_keys').config",
"self.config.add_section(node)\nself.config.set(node, self.keys, content)\nwith open(self.path, 'at', encoding=self.... | <|body_start_0|>
self.path = os.path.realpath(os.path.dirname(os.path.dirname(__file__))) + dirName
self.encoding = encoding
self.config = configparser.ConfigParser()
self.keys = MyConfig('token_keys').config
<|end_body_0|>
<|body_start_1|>
self.config.add_section(node)
... | ConfigParameter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigParameter:
def __init__(self, dirName='/BrowserToken.ini', encoding='utf-8'):
"""初始化"""
<|body_0|>
def write_ini(self, content, node='session'):
"""将信息写入配置文件"""
<|body_1|>
def read_ini(self, node='session'):
"""读取配置文件中的信息"""
<|body_... | stack_v2_sparse_classes_36k_train_014225 | 1,323 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self, dirName='/BrowserToken.ini', encoding='utf-8')"
},
{
"docstring": "将信息写入配置文件",
"name": "write_ini",
"signature": "def write_ini(self, content, node='session')"
},
{
"docstring": "读取配置文件中的信息",
"name": "... | 4 | null | Implement the Python class `ConfigParameter` described below.
Class description:
Implement the ConfigParameter class.
Method signatures and docstrings:
- def __init__(self, dirName='/BrowserToken.ini', encoding='utf-8'): 初始化
- def write_ini(self, content, node='session'): 将信息写入配置文件
- def read_ini(self, node='session'... | Implement the Python class `ConfigParameter` described below.
Class description:
Implement the ConfigParameter class.
Method signatures and docstrings:
- def __init__(self, dirName='/BrowserToken.ini', encoding='utf-8'): 初始化
- def write_ini(self, content, node='session'): 将信息写入配置文件
- def read_ini(self, node='session'... | 86bb051e62abdf2ed5bbdbea4c9008a6c1f49060 | <|skeleton|>
class ConfigParameter:
def __init__(self, dirName='/BrowserToken.ini', encoding='utf-8'):
"""初始化"""
<|body_0|>
def write_ini(self, content, node='session'):
"""将信息写入配置文件"""
<|body_1|>
def read_ini(self, node='session'):
"""读取配置文件中的信息"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigParameter:
def __init__(self, dirName='/BrowserToken.ini', encoding='utf-8'):
"""初始化"""
self.path = os.path.realpath(os.path.dirname(os.path.dirname(__file__))) + dirName
self.encoding = encoding
self.config = configparser.ConfigParser()
self.keys = MyConfig('toke... | the_stack_v2_python_sparse | model/MyConfig.py | yushu1987/UI | train | 0 | |
316cd858d0908703d5cc90ab28cd29a3b62c7694 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SynchronizationQuarantine()",
"from .quarantine_reason import QuarantineReason\nfrom .synchronization_error import SynchronizationError\nfrom .quarantine_reason import QuarantineReason\nfrom .synchronization_error import Synchronizatio... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SynchronizationQuarantine()
<|end_body_0|>
<|body_start_1|>
from .quarantine_reason import QuarantineReason
from .synchronization_error import SynchronizationError
from .quaranti... | SynchronizationQuarantine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SynchronizationQuarantine:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationQuarantine:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and c... | stack_v2_sparse_classes_36k_train_014226 | 5,065 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: SynchronizationQuarantine",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrim... | 3 | null | Implement the Python class `SynchronizationQuarantine` described below.
Class description:
Implement the SynchronizationQuarantine class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationQuarantine: Creates a new instance of the appropriat... | Implement the Python class `SynchronizationQuarantine` described below.
Class description:
Implement the SynchronizationQuarantine class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationQuarantine: Creates a new instance of the appropriat... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SynchronizationQuarantine:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationQuarantine:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SynchronizationQuarantine:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationQuarantine:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | the_stack_v2_python_sparse | msgraph/generated/models/synchronization_quarantine.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
2d308dbdbedd4f39e0a5b2cccc2f7ee6480e4be2 | [
"status = BuildResult()\npath = Path(path)\noutput_file = Path(output_file)\nif output_file.suffix != ZIPREPORT_FILE_EXTENSION:\n output_file = output_file.parent / (output_file.name + ZIPREPORT_FILE_EXTENSION)\nconsole.write('\\n== Building Report {} ==\\n'.format(output_file))\nif not path.exists():\n retur... | <|body_start_0|>
status = BuildResult()
path = Path(path)
output_file = Path(output_file)
if output_file.suffix != ZIPREPORT_FILE_EXTENSION:
output_file = output_file.parent / (output_file.name + ZIPREPORT_FILE_EXTENSION)
console.write('\n== Building Report {} ==\n'.f... | Report building object | ReportFileBuilder | [
"MIT",
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportFileBuilder:
"""Report building object"""
def build_file(path: str, output_file: str, console=sys.stdout, overwrite: bool=False) -> BuildResult:
"""Assemble a report file from a specific path :param path: report dir path :param output_file: destination report file :param consol... | stack_v2_sparse_classes_36k_train_014227 | 5,827 | permissive | [
{
"docstring": "Assemble a report file from a specific path :param path: report dir path :param output_file: destination report file :param console: console writer :param overwrite: if True, overwrite destination if exists :return: BuildResult",
"name": "build_file",
"signature": "def build_file(path: s... | 3 | stack_v2_sparse_classes_30k_train_017696 | Implement the Python class `ReportFileBuilder` described below.
Class description:
Report building object
Method signatures and docstrings:
- def build_file(path: str, output_file: str, console=sys.stdout, overwrite: bool=False) -> BuildResult: Assemble a report file from a specific path :param path: report dir path ... | Implement the Python class `ReportFileBuilder` described below.
Class description:
Report building object
Method signatures and docstrings:
- def build_file(path: str, output_file: str, console=sys.stdout, overwrite: bool=False) -> BuildResult: Assemble a report file from a specific path :param path: report dir path ... | 50341161951fd2f9cc3fbb4dcdf2dc1eeae5922a | <|skeleton|>
class ReportFileBuilder:
"""Report building object"""
def build_file(path: str, output_file: str, console=sys.stdout, overwrite: bool=False) -> BuildResult:
"""Assemble a report file from a specific path :param path: report dir path :param output_file: destination report file :param consol... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReportFileBuilder:
"""Report building object"""
def build_file(path: str, output_file: str, console=sys.stdout, overwrite: bool=False) -> BuildResult:
"""Assemble a report file from a specific path :param path: report dir path :param output_file: destination report file :param console: console wr... | the_stack_v2_python_sparse | zipreport/report/builder.py | prashanthhulimajjigi-agi/zipreport | train | 0 |
cb1d212b910ea79590f24b94688c37d533801cc9 | [
"if not isinstance(kernel, ScaleKernel):\n base_kernel = kernel\n outputscale = torch.tensor(1.0, dtype=base_kernel.lengthscale.dtype, device=base_kernel.lengthscale.device)\nelse:\n base_kernel = kernel.base_kernel\n outputscale = kernel.outputscale.detach().clone()\nif not isinstance(base_kernel, (Mat... | <|body_start_0|>
if not isinstance(kernel, ScaleKernel):
base_kernel = kernel
outputscale = torch.tensor(1.0, dtype=base_kernel.lengthscale.dtype, device=base_kernel.lengthscale.device)
else:
base_kernel = kernel.base_kernel
outputscale = kernel.outputscal... | A class that represents Random Fourier Features. | RandomFourierFeatures | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomFourierFeatures:
"""A class that represents Random Fourier Features."""
def __init__(self, kernel: Kernel, input_dim: int, num_rff_features: int, sample_shape: Optional[torch.Size]=None) -> None:
"""Initialize RandomFourierFeatures. Args: kernel: The GP kernel. input_dim: The i... | stack_v2_sparse_classes_36k_train_014228 | 20,040 | permissive | [
{
"docstring": "Initialize RandomFourierFeatures. Args: kernel: The GP kernel. input_dim: The input dimension to the GP kernel. num_rff_features: The number of Fourier features. sample_shape: The shape of a single sample. For a single-element `torch.Size` object, this is simply the number of RFF draws.",
"n... | 4 | null | Implement the Python class `RandomFourierFeatures` described below.
Class description:
A class that represents Random Fourier Features.
Method signatures and docstrings:
- def __init__(self, kernel: Kernel, input_dim: int, num_rff_features: int, sample_shape: Optional[torch.Size]=None) -> None: Initialize RandomFouri... | Implement the Python class `RandomFourierFeatures` described below.
Class description:
A class that represents Random Fourier Features.
Method signatures and docstrings:
- def __init__(self, kernel: Kernel, input_dim: int, num_rff_features: int, sample_shape: Optional[torch.Size]=None) -> None: Initialize RandomFouri... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class RandomFourierFeatures:
"""A class that represents Random Fourier Features."""
def __init__(self, kernel: Kernel, input_dim: int, num_rff_features: int, sample_shape: Optional[torch.Size]=None) -> None:
"""Initialize RandomFourierFeatures. Args: kernel: The GP kernel. input_dim: The i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomFourierFeatures:
"""A class that represents Random Fourier Features."""
def __init__(self, kernel: Kernel, input_dim: int, num_rff_features: int, sample_shape: Optional[torch.Size]=None) -> None:
"""Initialize RandomFourierFeatures. Args: kernel: The GP kernel. input_dim: The input dimensio... | the_stack_v2_python_sparse | botorch/utils/gp_sampling.py | pytorch/botorch | train | 2,891 |
24ce92ad39ea479a508759f2e5bb501bff00f551 | [
"super(ActionMemberAdminForm, self).__init__(*args, **kwargs)\nmember = self.instance\nif member and member.action:\n action = member.action\n message = 'Specify the number of points to award. '\n if not action.point_value:\n message += 'This default points for this action should be between %d and %... | <|body_start_0|>
super(ActionMemberAdminForm, self).__init__(*args, **kwargs)
member = self.instance
if member and member.action:
action = member.action
message = 'Specify the number of points to award. '
if not action.point_value:
message += '... | Activity Member admin. | ActionMemberAdminForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionMemberAdminForm:
"""Activity Member admin."""
def __init__(self, *args, **kwargs):
"""Override to dynamically change the form if the activity specifies a point range.."""
<|body_0|>
def clean(self):
"""Custom validator that checks values for variable point ... | stack_v2_sparse_classes_36k_train_014229 | 31,229 | permissive | [
{
"docstring": "Override to dynamically change the form if the activity specifies a point range..",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Custom validator that checks values for variable point activities.",
"name": "clean",
"signature":... | 2 | null | Implement the Python class `ActionMemberAdminForm` described below.
Class description:
Activity Member admin.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Override to dynamically change the form if the activity specifies a point range..
- def clean(self): Custom validator that checks value... | Implement the Python class `ActionMemberAdminForm` described below.
Class description:
Activity Member admin.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Override to dynamically change the form if the activity specifies a point range..
- def clean(self): Custom validator that checks value... | 4b7dd685012ec64758affe0ecee3103596d16aa7 | <|skeleton|>
class ActionMemberAdminForm:
"""Activity Member admin."""
def __init__(self, *args, **kwargs):
"""Override to dynamically change the form if the activity specifies a point range.."""
<|body_0|>
def clean(self):
"""Custom validator that checks values for variable point ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionMemberAdminForm:
"""Activity Member admin."""
def __init__(self, *args, **kwargs):
"""Override to dynamically change the form if the activity specifies a point range.."""
super(ActionMemberAdminForm, self).__init__(*args, **kwargs)
member = self.instance
if member an... | the_stack_v2_python_sparse | makahiki/apps/widgets/smartgrid/admin.py | justinslee/Wai-Not-Makahiki | train | 1 |
240fcfdf0380ba6c92c5198e6b2b539eebfbae43 | [
"self.cap = capacity\nself.max_idx = -1\nself.stack_arr = []\nself.h = []",
"if self.h:\n index = heappop(self.h)\n self.stack_arr[index].append(val)\n return\nif self.max_idx == -1 or len(self.stack_arr[self.max_idx]) == self.cap:\n self.max_idx += 1\n self.stack_arr.append(deque())\nself.stack_ar... | <|body_start_0|>
self.cap = capacity
self.max_idx = -1
self.stack_arr = []
self.h = []
<|end_body_0|>
<|body_start_1|>
if self.h:
index = heappop(self.h)
self.stack_arr[index].append(val)
return
if self.max_idx == -1 or len(self.stack_... | DinnerPlates | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DinnerPlates:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def push(self, val):
""":type val: int :rtype: None"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def popAtStack(self, index):
""":t... | stack_v2_sparse_classes_36k_train_014230 | 1,570 | permissive | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type val: int :rtype: None",
"name": "push",
"signature": "def push(self, val)"
},
{
"docstring": ":rtype: int",
"name": "pop",
"signature": "def pop(... | 4 | stack_v2_sparse_classes_30k_train_013598 | Implement the Python class `DinnerPlates` described below.
Class description:
Implement the DinnerPlates class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def push(self, val): :type val: int :rtype: None
- def pop(self): :rtype: int
- def popAtStack(self, index): :type ind... | Implement the Python class `DinnerPlates` described below.
Class description:
Implement the DinnerPlates class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def push(self, val): :type val: int :rtype: None
- def pop(self): :rtype: int
- def popAtStack(self, index): :type ind... | fc5b1744af7be93f4dd01d6ad58d2bd12f7ed33f | <|skeleton|>
class DinnerPlates:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def push(self, val):
""":type val: int :rtype: None"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def popAtStack(self, index):
""":t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DinnerPlates:
def __init__(self, capacity):
""":type capacity: int"""
self.cap = capacity
self.max_idx = -1
self.stack_arr = []
self.h = []
def push(self, val):
""":type val: int :rtype: None"""
if self.h:
index = heappop(self.h)
... | the_stack_v2_python_sparse | 1172.Dinner-Plate-Stacks.py | mickey0524/leetcode | train | 27 | |
fca30438264e9d7a46ef929081c82b97cf1328ed | [
"cache_key = calendar_year\nif cache_key not in UpstreamMethods._cache:\n start_years = np.atleast_1d(UpstreamMethods._data['start_year'])\n if len(start_years[start_years <= calendar_year]) > 0:\n calendar_year = max(start_years[start_years <= calendar_year])\n method = UpstreamMethods._data['u... | <|body_start_0|>
cache_key = calendar_year
if cache_key not in UpstreamMethods._cache:
start_years = np.atleast_1d(UpstreamMethods._data['start_year'])
if len(start_years[start_years <= calendar_year]) > 0:
calendar_year = max(start_years[start_years <= calendar_y... | **Loads and provides access to upstream calculation methods by start year.** | UpstreamMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpstreamMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def get_upstream_method(calendar_year):
"""Get the cert upstream calculation function for the given calendar year. Args: calendar_year (int): the calendar year to get the function for ... | stack_v2_sparse_classes_36k_train_014231 | 8,672 | no_license | [
{
"docstring": "Get the cert upstream calculation function for the given calendar year. Args: calendar_year (int): the calendar year to get the function for Returns: A callable python function used to calculate upstream cert emissions for the given calendar year",
"name": "get_upstream_method",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_016144 | Implement the Python class `UpstreamMethods` described below.
Class description:
**Loads and provides access to upstream calculation methods by start year.**
Method signatures and docstrings:
- def get_upstream_method(calendar_year): Get the cert upstream calculation function for the given calendar year. Args: calend... | Implement the Python class `UpstreamMethods` described below.
Class description:
**Loads and provides access to upstream calculation methods by start year.**
Method signatures and docstrings:
- def get_upstream_method(calendar_year): Get the cert upstream calculation function for the given calendar year. Args: calend... | afe912c57383b9de90ef30820f7977c3367a30c4 | <|skeleton|>
class UpstreamMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def get_upstream_method(calendar_year):
"""Get the cert upstream calculation function for the given calendar year. Args: calendar_year (int): the calendar year to get the function for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpstreamMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def get_upstream_method(calendar_year):
"""Get the cert upstream calculation function for the given calendar year. Args: calendar_year (int): the calendar year to get the function for Returns: A ca... | the_stack_v2_python_sparse | omega_model/policy/upstream_methods.py | USEPA/EPA_OMEGA_Model | train | 17 |
e6995681ae24f5ea5fb495be6bb114307e58f853 | [
"QtCore.QThread.__init__(self, parent)\nself.day = args[0]\nself.month = args[1]\nself.year = args[2][2:]\nself.hour = args[3]\nself.minute = args[4]\nself.log_interval = args[5]\nif len(self.day) == 1:\n self.day = '0' + self.day\nif len(self.month) == 1:\n self.month = '0' + self.month\nif len(self.hour) ==... | <|body_start_0|>
QtCore.QThread.__init__(self, parent)
self.day = args[0]
self.month = args[1]
self.year = args[2][2:]
self.hour = args[3]
self.minute = args[4]
self.log_interval = args[5]
if len(self.day) == 1:
self.day = '0' + self.day
... | PURPOSE: Thread to handle starting a new log. | NewLogThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewLogThread:
"""PURPOSE: Thread to handle starting a new log."""
def __init__(self, args, parent=None):
"""Initializes Thread."""
<|body_0|>
def run(self):
"""What to do when start is called."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
QtCo... | stack_v2_sparse_classes_36k_train_014232 | 11,010 | no_license | [
{
"docstring": "Initializes Thread.",
"name": "__init__",
"signature": "def __init__(self, args, parent=None)"
},
{
"docstring": "What to do when start is called.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004201 | Implement the Python class `NewLogThread` described below.
Class description:
PURPOSE: Thread to handle starting a new log.
Method signatures and docstrings:
- def __init__(self, args, parent=None): Initializes Thread.
- def run(self): What to do when start is called. | Implement the Python class `NewLogThread` described below.
Class description:
PURPOSE: Thread to handle starting a new log.
Method signatures and docstrings:
- def __init__(self, args, parent=None): Initializes Thread.
- def run(self): What to do when start is called.
<|skeleton|>
class NewLogThread:
"""PURPOSE:... | 898bda85308f37fd19568f37fe277f93951981ec | <|skeleton|>
class NewLogThread:
"""PURPOSE: Thread to handle starting a new log."""
def __init__(self, args, parent=None):
"""Initializes Thread."""
<|body_0|>
def run(self):
"""What to do when start is called."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewLogThread:
"""PURPOSE: Thread to handle starting a new log."""
def __init__(self, args, parent=None):
"""Initializes Thread."""
QtCore.QThread.__init__(self, parent)
self.day = args[0]
self.month = args[1]
self.year = args[2][2:]
self.hour = args[3]
... | the_stack_v2_python_sparse | src/startnewlog.py | LightingResearchCenter/PythonDaysimeter12Client | train | 0 |
114ac1d7c4a5a98b9735a3be7aedeb19da133ae0 | [
"if hasattr(self, 'get_context_data'):\n data = self.get_context_data(**kwargs)\nelse:\n data = kwargs\nreturn data",
"assert self.render_type in self.renders\nrender = self.renders[self.render_type]\nif collect_render_data:\n kwargs = self.get_render_data(**kwargs)\nreturn render.render(request, **kwarg... | <|body_start_0|>
if hasattr(self, 'get_context_data'):
data = self.get_context_data(**kwargs)
else:
data = kwargs
return data
<|end_body_0|>
<|body_start_1|>
assert self.render_type in self.renders
render = self.renders[self.render_type]
if collec... | Base view for all Views. This is a class based view that uses render classes to handle the preparation of an response. Render classes are classes that return a response of some kind from a view, such as a HttpResponse object or a string. The only requirement is that they have a render method that takes a request and ke... | BaseView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseView:
"""Base view for all Views. This is a class based view that uses render classes to handle the preparation of an response. Render classes are classes that return a response of some kind from a view, such as a HttpResponse object or a string. The only requirement is that they have a rende... | stack_v2_sparse_classes_36k_train_014233 | 28,738 | permissive | [
{
"docstring": "Because of the way mixin inheritance works we can't have a default implementation of get_context_data on the this class, so this calls that method if available and returns the resulting context.",
"name": "get_render_data",
"signature": "def get_render_data(self, **kwargs)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_018483 | Implement the Python class `BaseView` described below.
Class description:
Base view for all Views. This is a class based view that uses render classes to handle the preparation of an response. Render classes are classes that return a response of some kind from a view, such as a HttpResponse object or a string. The onl... | Implement the Python class `BaseView` described below.
Class description:
Base view for all Views. This is a class based view that uses render classes to handle the preparation of an response. Render classes are classes that return a response of some kind from a view, such as a HttpResponse object or a string. The onl... | 9f5ac28618059eef99152214c7a90ad78151629e | <|skeleton|>
class BaseView:
"""Base view for all Views. This is a class based view that uses render classes to handle the preparation of an response. Render classes are classes that return a response of some kind from a view, such as a HttpResponse object or a string. The only requirement is that they have a rende... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseView:
"""Base view for all Views. This is a class based view that uses render classes to handle the preparation of an response. Render classes are classes that return a response of some kind from a view, such as a HttpResponse object or a string. The only requirement is that they have a render method that... | the_stack_v2_python_sparse | scarlet/cms/base_views.py | markmiscavage/scarlet | train | 1 |
630b340ce45b136165437c6b2e1bef0cf9b0dfd2 | [
"if not nums:\n return\nself.sums = nums[:]\nfor i in range(1, len(nums)):\n self.sums[i] += self.sums[i - 1]",
"if i == 0:\n return self.sums[j]\nreturn self.sums[j] - self.sums[i - 1]"
] | <|body_start_0|>
if not nums:
return
self.sums = nums[:]
for i in range(1, len(nums)):
self.sums[i] += self.sums[i - 1]
<|end_body_0|>
<|body_start_1|>
if i == 0:
return self.sums[j]
return self.sums[j] - self.sums[i - 1]
<|end_body_1|>
| NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return
self.sums = nums[:]... | stack_v2_sparse_classes_36k_train_014234 | 1,488 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | eca21324d5d2db0addfa0efdf09fc0ffbd9a09e6 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
if not nums:
return
self.sums = nums[:]
for i in range(1, len(nums)):
self.sums[i] += self.sums[i - 1]
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
... | the_stack_v2_python_sparse | dynamic_programming/303.py | zangkhun/leepy | train | 0 | |
c6f36b9a2b1157e5ee8e2383873d9b3ce9df03ab | [
"result = super(AzurePerformanceTierDecoder, cls)._GetOptionDecoderConstructions()\nresult.update({'compute_units': (option_decoders.IntDecoder, {'min': 50}), 'tier': (option_decoders.EnumDecoder, {'valid_values': azure_flags.VALID_TIERS})})\nreturn result",
"if flag_values['azure_tier'].present:\n config_valu... | <|body_start_0|>
result = super(AzurePerformanceTierDecoder, cls)._GetOptionDecoderConstructions()
result.update({'compute_units': (option_decoders.IntDecoder, {'min': 50}), 'tier': (option_decoders.EnumDecoder, {'valid_values': azure_flags.VALID_TIERS})})
return result
<|end_body_0|>
<|body_st... | Properties of a An Azure custom machine type. Attributes: compute_units: int. Number of compute units. tier: Basic, Standard or Premium | AzurePerformanceTierDecoder | [
"Classpath-exception-2.0",
"BSD-3-Clause",
"AGPL-3.0-only",
"MIT",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AzurePerformanceTierDecoder:
"""Properties of a An Azure custom machine type. Attributes: compute_units: int. Number of compute units. tier: Basic, Standard or Premium"""
def _GetOptionDecoderConstructions(cls):
"""Gets decoder classes and constructor args for each configurable optio... | stack_v2_sparse_classes_36k_train_014235 | 8,250 | permissive | [
{
"docstring": "Gets decoder classes and constructor args for each configurable option. Returns: dict. Maps option name string to a (ConfigOptionDecoder class, dict) pair. The pair specifies a decoder class and its __init__() keyword arguments to construct in order to decode the named option.",
"name": "_Ge... | 2 | null | Implement the Python class `AzurePerformanceTierDecoder` described below.
Class description:
Properties of a An Azure custom machine type. Attributes: compute_units: int. Number of compute units. tier: Basic, Standard or Premium
Method signatures and docstrings:
- def _GetOptionDecoderConstructions(cls): Gets decoder... | Implement the Python class `AzurePerformanceTierDecoder` described below.
Class description:
Properties of a An Azure custom machine type. Attributes: compute_units: int. Number of compute units. tier: Basic, Standard or Premium
Method signatures and docstrings:
- def _GetOptionDecoderConstructions(cls): Gets decoder... | d0699f32998898757b036704fba39e5471641f01 | <|skeleton|>
class AzurePerformanceTierDecoder:
"""Properties of a An Azure custom machine type. Attributes: compute_units: int. Number of compute units. tier: Basic, Standard or Premium"""
def _GetOptionDecoderConstructions(cls):
"""Gets decoder classes and constructor args for each configurable optio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AzurePerformanceTierDecoder:
"""Properties of a An Azure custom machine type. Attributes: compute_units: int. Number of compute units. tier: Basic, Standard or Premium"""
def _GetOptionDecoderConstructions(cls):
"""Gets decoder classes and constructor args for each configurable option. Returns: d... | the_stack_v2_python_sparse | perfkitbenchmarker/custom_virtual_machine_spec.py | GoogleCloudPlatform/PerfKitBenchmarker | train | 1,923 |
8069024d9d1d5f147d08036042cf22bc7b3eb099 | [
"for i in range(len(nums)):\n if nums[i] != 0:\n back_cursor = i\n while back_cursor > 0 and nums[back_cursor - 1] == 0:\n temp = nums[back_cursor]\n nums[back_cursor] = 0\n nums[back_cursor - 1] = temp\n back_cursor -= 1\nreturn nums",
"j = 0\nfor i in... | <|body_start_0|>
for i in range(len(nums)):
if nums[i] != 0:
back_cursor = i
while back_cursor > 0 and nums[back_cursor - 1] == 0:
temp = nums[back_cursor]
nums[back_cursor] = 0
nums[back_cursor - 1] = temp
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes_1(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes_2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.... | stack_v2_sparse_classes_36k_train_014236 | 983 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "moveZeroes_1",
"signature": "def moveZeroes_1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name":... | 2 | stack_v2_sparse_classes_30k_train_011149 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes_1(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def moveZeroes_2(self, nums): :type nums: List[int] :rtyp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes_1(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def moveZeroes_2(self, nums): :type nums: List[int] :rtyp... | f0fa1f0af9613914c12f45a218500a75f9ba3c1a | <|skeleton|>
class Solution:
def moveZeroes_1(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes_2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def moveZeroes_1(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
for i in range(len(nums)):
if nums[i] != 0:
back_cursor = i
while back_cursor > 0 and nums[back_cursor - 1] == 0:
... | the_stack_v2_python_sparse | Array_and_String/Move_Zeroes.py | ncturoger/LeetCodePractice | train | 0 | |
84d52641a70fb865858c84977b323ec029d93806 | [
"res = []\nif root:\n res += self.preorder(root.left)\n res.append(root.val)\n res += self.preorder(root.right)\nreturn res",
"numbers = self.preorder(root)\nleft, right = (0, len(numbers) - 1)\nwhile left < right:\n if numbers[left] + numbers[right] == k:\n return True\n elif numbers[left] ... | <|body_start_0|>
res = []
if root:
res += self.preorder(root.left)
res.append(root.val)
res += self.preorder(root.right)
return res
<|end_body_0|>
<|body_start_1|>
numbers = self.preorder(root)
left, right = (0, len(numbers) - 1)
while... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorder(self, root):
""":type root: TreeNode :type k: int :rtype: bool"""
<|body_0|>
def findTarget(self, root, k):
""":type root: TreeNode :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
if ... | stack_v2_sparse_classes_36k_train_014237 | 831 | no_license | [
{
"docstring": ":type root: TreeNode :type k: int :rtype: bool",
"name": "preorder",
"signature": "def preorder(self, root)"
},
{
"docstring": ":type root: TreeNode :type k: int :rtype: bool",
"name": "findTarget",
"signature": "def findTarget(self, root, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorder(self, root): :type root: TreeNode :type k: int :rtype: bool
- def findTarget(self, root, k): :type root: TreeNode :type k: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorder(self, root): :type root: TreeNode :type k: int :rtype: bool
- def findTarget(self, root, k): :type root: TreeNode :type k: int :rtype: bool
<|skeleton|>
class Solut... | 9bd2d706f014ce84356ba38fc7801da0285a91d3 | <|skeleton|>
class Solution:
def preorder(self, root):
""":type root: TreeNode :type k: int :rtype: bool"""
<|body_0|>
def findTarget(self, root, k):
""":type root: TreeNode :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def preorder(self, root):
""":type root: TreeNode :type k: int :rtype: bool"""
res = []
if root:
res += self.preorder(root.left)
res.append(root.val)
res += self.preorder(root.right)
return res
def findTarget(self, root, k):
... | the_stack_v2_python_sparse | leetcode/findTarget-653.py | pittcat/Algorithm_Practice | train | 0 | |
d336d4c865b9a950a4ec2f949bb16eac456f1ea3 | [
"native_project_info.NativeProjectInfo.modules_info = None\nnative_project_info.NativeProjectInfo._init_modules_info()\nself.assertEqual(mock_mod_info.call_count, 1)\nnative_project_info.NativeProjectInfo._init_modules_info()\nself.assertEqual(mock_mod_info.call_count, 1)",
"target = 'libui'\nconfig = mock.Mock()... | <|body_start_0|>
native_project_info.NativeProjectInfo.modules_info = None
native_project_info.NativeProjectInfo._init_modules_info()
self.assertEqual(mock_mod_info.call_count, 1)
native_project_info.NativeProjectInfo._init_modules_info()
self.assertEqual(mock_mod_info.call_count... | Unit tests for native_project_info.py | NativeProjectInfoUnittests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NativeProjectInfoUnittests:
"""Unit tests for native_project_info.py"""
def test_init_modules_info(self, mock_mod_info):
"""Test initializing the class attribute: modules_info."""
<|body_0|>
def test_generate_projects(self, mock_get_inst, mock_mod_info, mock_get_need, mo... | stack_v2_sparse_classes_36k_train_014238 | 3,972 | no_license | [
{
"docstring": "Test initializing the class attribute: modules_info.",
"name": "test_init_modules_info",
"signature": "def test_init_modules_info(self, mock_mod_info)"
},
{
"docstring": "Test initializing NativeProjectInfo woth different conditions.",
"name": "test_generate_projects",
"s... | 3 | null | Implement the Python class `NativeProjectInfoUnittests` described below.
Class description:
Unit tests for native_project_info.py
Method signatures and docstrings:
- def test_init_modules_info(self, mock_mod_info): Test initializing the class attribute: modules_info.
- def test_generate_projects(self, mock_get_inst, ... | Implement the Python class `NativeProjectInfoUnittests` described below.
Class description:
Unit tests for native_project_info.py
Method signatures and docstrings:
- def test_init_modules_info(self, mock_mod_info): Test initializing the class attribute: modules_info.
- def test_generate_projects(self, mock_get_inst, ... | 78a61ca023cbf1a0cecfef8b97df2b274ac3a988 | <|skeleton|>
class NativeProjectInfoUnittests:
"""Unit tests for native_project_info.py"""
def test_init_modules_info(self, mock_mod_info):
"""Test initializing the class attribute: modules_info."""
<|body_0|>
def test_generate_projects(self, mock_get_inst, mock_mod_info, mock_get_need, mo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NativeProjectInfoUnittests:
"""Unit tests for native_project_info.py"""
def test_init_modules_info(self, mock_mod_info):
"""Test initializing the class attribute: modules_info."""
native_project_info.NativeProjectInfo.modules_info = None
native_project_info.NativeProjectInfo._init... | the_stack_v2_python_sparse | tools/asuite/aidegen/lib/native_project_info_unittest.py | ZYHGOD-1/Aosp11 | train | 0 |
f3ae5aefb6ea0af57d4dce5ce3a6253f691c4fbe | [
"self.optimizer = optimizer\nself.intermediate_resampler = intermediate_resampler\nsuper(OptimizedPointCloud, self).__init__(name=name)",
"float_n_particles = tf.cast(state.n_particles, float)\nuniform_log_weights = -tf.math.log(float_n_particles) * tf.ones_like(state.log_weights)\nuniform_weights = tf.ones_like(... | <|body_start_0|>
self.optimizer = optimizer
self.intermediate_resampler = intermediate_resampler
super(OptimizedPointCloud, self).__init__(name=name)
<|end_body_0|>
<|body_start_1|>
float_n_particles = tf.cast(state.n_particles, float)
uniform_log_weights = -tf.math.log(float_n_... | Optimized Point Cloud - docstring to come. | OptimizedPointCloud | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizedPointCloud:
"""Optimized Point Cloud - docstring to come."""
def __init__(self, optimizer: OptimizerBase, intermediate_resampler: ResamplerBase, name='OptimizedPointCloud'):
"""Constructor :param optimizer: OptimizerBase a tf.Module that takes (log_w_x, w_x, x, log_w_y, w_y,... | stack_v2_sparse_classes_36k_train_014239 | 2,271 | permissive | [
{
"docstring": "Constructor :param optimizer: OptimizerBase a tf.Module that takes (log_w_x, w_x, x, log_w_y, w_y, y) and optimizes a loss w.r.t. x :param intermediate_resampler: ResamplerBase Provides the initial point cloud to optimize",
"name": "__init__",
"signature": "def __init__(self, optimizer: ... | 2 | stack_v2_sparse_classes_30k_val_000778 | Implement the Python class `OptimizedPointCloud` described below.
Class description:
Optimized Point Cloud - docstring to come.
Method signatures and docstrings:
- def __init__(self, optimizer: OptimizerBase, intermediate_resampler: ResamplerBase, name='OptimizedPointCloud'): Constructor :param optimizer: OptimizerBa... | Implement the Python class `OptimizedPointCloud` described below.
Class description:
Optimized Point Cloud - docstring to come.
Method signatures and docstrings:
- def __init__(self, optimizer: OptimizerBase, intermediate_resampler: ResamplerBase, name='OptimizedPointCloud'): Constructor :param optimizer: OptimizerBa... | 5d8300ba247c4c17e1a301a22560c24fd0670bfe | <|skeleton|>
class OptimizedPointCloud:
"""Optimized Point Cloud - docstring to come."""
def __init__(self, optimizer: OptimizerBase, intermediate_resampler: ResamplerBase, name='OptimizedPointCloud'):
"""Constructor :param optimizer: OptimizerBase a tf.Module that takes (log_w_x, w_x, x, log_w_y, w_y,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptimizedPointCloud:
"""Optimized Point Cloud - docstring to come."""
def __init__(self, optimizer: OptimizerBase, intermediate_resampler: ResamplerBase, name='OptimizedPointCloud'):
"""Constructor :param optimizer: OptimizerBase a tf.Module that takes (log_w_x, w_x, x, log_w_y, w_y, y) and optim... | the_stack_v2_python_sparse | filterflow/resampling/differentiable/optimized.py | JTT94/filterflow | train | 39 |
9e982ddf1c7047c538f70e63b8d6c17f44cf8c5d | [
"cf_status = response.status == 503\ncf_headers = response.headers.get('Server', '').startswith(b'cloudflare')\ncf_text = 'jschl_vc' in response.text and 'jschl_answer' in response.text\nreturn cf_status and cf_headers and cf_text",
"if not self.is_cloudflare(response):\n return response\nspider.logger.info('C... | <|body_start_0|>
cf_status = response.status == 503
cf_headers = response.headers.get('Server', '').startswith(b'cloudflare')
cf_text = 'jschl_vc' in response.text and 'jschl_answer' in response.text
return cf_status and cf_headers and cf_text
<|end_body_0|>
<|body_start_1|>
if ... | Scrapy middleware to bypass the CloudFlare anti-bot protection Taken from https://github.com/clemfromspace/scrapy-cloudflare-middleware | CloudFlareMiddleware | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudFlareMiddleware:
"""Scrapy middleware to bypass the CloudFlare anti-bot protection Taken from https://github.com/clemfromspace/scrapy-cloudflare-middleware"""
def is_cloudflare(response):
"""Test if the given response contains the CloudFlare anti-bot protection"""
<|body... | stack_v2_sparse_classes_36k_train_014240 | 1,661 | permissive | [
{
"docstring": "Test if the given response contains the CloudFlare anti-bot protection",
"name": "is_cloudflare",
"signature": "def is_cloudflare(response)"
},
{
"docstring": "If we can identify a CloudFlare check on this page then use cfscrape to get the cookies",
"name": "process_response"... | 2 | stack_v2_sparse_classes_30k_train_013265 | Implement the Python class `CloudFlareMiddleware` described below.
Class description:
Scrapy middleware to bypass the CloudFlare anti-bot protection Taken from https://github.com/clemfromspace/scrapy-cloudflare-middleware
Method signatures and docstrings:
- def is_cloudflare(response): Test if the given response cont... | Implement the Python class `CloudFlareMiddleware` described below.
Class description:
Scrapy middleware to bypass the CloudFlare anti-bot protection Taken from https://github.com/clemfromspace/scrapy-cloudflare-middleware
Method signatures and docstrings:
- def is_cloudflare(response): Test if the given response cont... | 578fe203b8f4135dd223854d57eb961b977ca145 | <|skeleton|>
class CloudFlareMiddleware:
"""Scrapy middleware to bypass the CloudFlare anti-bot protection Taken from https://github.com/clemfromspace/scrapy-cloudflare-middleware"""
def is_cloudflare(response):
"""Test if the given response contains the CloudFlare anti-bot protection"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloudFlareMiddleware:
"""Scrapy middleware to bypass the CloudFlare anti-bot protection Taken from https://github.com/clemfromspace/scrapy-cloudflare-middleware"""
def is_cloudflare(response):
"""Test if the given response contains the CloudFlare anti-bot protection"""
cf_status = respons... | the_stack_v2_python_sparse | misinformation/middlewares/cloudflaremiddleware.py | alan-turing-institute/misinformation-crawler | train | 6 |
d7de809cb6ec6c52b1835df62a2df121ee02c79e | [
"author = g.user\nnote = NoteModel.query.get(note_id)\nif not note:\n abort(404, error=f'Note with id={note_id} not found')\nif note.author != author:\n abort(403, error=f'Access denied to note with id={note_id}')\nreturn (note, 200)",
"author = g.user\nnote = NoteModel.query.get(note_id)\nif not note:\n ... | <|body_start_0|>
author = g.user
note = NoteModel.query.get(note_id)
if not note:
abort(404, error=f'Note with id={note_id} not found')
if note.author != author:
abort(403, error=f'Access denied to note with id={note_id}')
return (note, 200)
<|end_body_0|>... | NoteResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoteResource:
def get(self, note_id):
"""Возвращает заметку пользователя. Требуется аутентификация. :param note_id: id заметки :return: замтку"""
<|body_0|>
def put(self, note_id, **kwargs):
"""Меняет заметку пользователя. Требуется аутентификация. :param note_id: id... | stack_v2_sparse_classes_36k_train_014241 | 11,305 | no_license | [
{
"docstring": "Возвращает заметку пользователя. Требуется аутентификация. :param note_id: id заметки :return: замтку",
"name": "get",
"signature": "def get(self, note_id)"
},
{
"docstring": "Меняет заметку пользователя. Требуется аутентификация. :param note_id: id заметки :param kwargs: парамет... | 3 | stack_v2_sparse_classes_30k_train_001161 | Implement the Python class `NoteResource` described below.
Class description:
Implement the NoteResource class.
Method signatures and docstrings:
- def get(self, note_id): Возвращает заметку пользователя. Требуется аутентификация. :param note_id: id заметки :return: замтку
- def put(self, note_id, **kwargs): Меняет з... | Implement the Python class `NoteResource` described below.
Class description:
Implement the NoteResource class.
Method signatures and docstrings:
- def get(self, note_id): Возвращает заметку пользователя. Требуется аутентификация. :param note_id: id заметки :return: замтку
- def put(self, note_id, **kwargs): Меняет з... | adb9a3f4524ab76e8ba656344e2ed452e87b577c | <|skeleton|>
class NoteResource:
def get(self, note_id):
"""Возвращает заметку пользователя. Требуется аутентификация. :param note_id: id заметки :return: замтку"""
<|body_0|>
def put(self, note_id, **kwargs):
"""Меняет заметку пользователя. Требуется аутентификация. :param note_id: id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoteResource:
def get(self, note_id):
"""Возвращает заметку пользователя. Требуется аутентификация. :param note_id: id заметки :return: замтку"""
author = g.user
note = NoteModel.query.get(note_id)
if not note:
abort(404, error=f'Note with id={note_id} not found')
... | the_stack_v2_python_sparse | api/resources/note.py | UshakovAleksandr/Blog | train | 1 | |
263e5959b31cfd1fd36b06df83e75abccae02e17 | [
"assumptions = [set(preorder) == set(inorder), len(preorder) == len(set(preorder)), len(inorder) == len(set(inorder))]\nif not all(assumptions):\n raise ValueError('both traversals must have same length, and no duplicates')\nreturn self.build_tree_recursive(preorder, inorder)",
"if len(preorder) == len(inorder... | <|body_start_0|>
assumptions = [set(preorder) == set(inorder), len(preorder) == len(set(preorder)), len(inorder) == len(set(inorder))]
if not all(assumptions):
raise ValueError('both traversals must have same length, and no duplicates')
return self.build_tree_recursive(preorder, inor... | Solution for Leetcode problem 105: Bin Tree from Inorder & Preorder. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Solution for Leetcode problem 105: Bin Tree from Inorder & Preorder."""
def build_tree(self, preorder, inorder):
"""Build a binary tree from inorder and postorder traversals. :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_014242 | 1,780 | no_license | [
{
"docstring": "Build a binary tree from inorder and postorder traversals. :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode",
"name": "build_tree",
"signature": "def build_tree(self, preorder, inorder)"
},
{
"docstring": "Bin Tree from Inorder-Preorder: recursive solution.",
... | 2 | stack_v2_sparse_classes_30k_train_007575 | Implement the Python class `Solution` described below.
Class description:
Solution for Leetcode problem 105: Bin Tree from Inorder & Preorder.
Method signatures and docstrings:
- def build_tree(self, preorder, inorder): Build a binary tree from inorder and postorder traversals. :type preorder: List[int] :type inorder... | Implement the Python class `Solution` described below.
Class description:
Solution for Leetcode problem 105: Bin Tree from Inorder & Preorder.
Method signatures and docstrings:
- def build_tree(self, preorder, inorder): Build a binary tree from inorder and postorder traversals. :type preorder: List[int] :type inorder... | e11bfc454789e716055b80873af0817ec8588aea | <|skeleton|>
class Solution:
"""Solution for Leetcode problem 105: Bin Tree from Inorder & Preorder."""
def build_tree(self, preorder, inorder):
"""Build a binary tree from inorder and postorder traversals. :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Solution for Leetcode problem 105: Bin Tree from Inorder & Preorder."""
def build_tree(self, preorder, inorder):
"""Build a binary tree from inorder and postorder traversals. :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
assumptions = [set(preorder) =... | the_stack_v2_python_sparse | p105/problem105.py | stanl3y/leetcode | train | 0 |
f51e1d097372a31ab33b82037a7d422a477cf4e6 | [
"sensor_type = self.get_type()\nif sensor_type is self.TYPE_CONTACT:\n return [DisplayCategory.CONTACT_SENSOR]\nif sensor_type is self.TYPE_MOTION:\n return [DisplayCategory.MOTION_SENSOR]\nif sensor_type is self.TYPE_PRESENCE:\n return [DisplayCategory.CAMERA]\nreturn None",
"sensor_type = self.get_type... | <|body_start_0|>
sensor_type = self.get_type()
if sensor_type is self.TYPE_CONTACT:
return [DisplayCategory.CONTACT_SENSOR]
if sensor_type is self.TYPE_MOTION:
return [DisplayCategory.MOTION_SENSOR]
if sensor_type is self.TYPE_PRESENCE:
return [Display... | Class to represent BinarySensor capabilities. | BinarySensorCapabilities | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinarySensorCapabilities:
"""Class to represent BinarySensor capabilities."""
def default_display_categories(self) -> list[str] | None:
"""Return the display categories for this entity."""
<|body_0|>
def interfaces(self) -> Generator[AlexaCapability, None, None]:
... | stack_v2_sparse_classes_36k_train_014243 | 35,310 | permissive | [
{
"docstring": "Return the display categories for this entity.",
"name": "default_display_categories",
"signature": "def default_display_categories(self) -> list[str] | None"
},
{
"docstring": "Yield the supported interfaces.",
"name": "interfaces",
"signature": "def interfaces(self) -> ... | 3 | null | Implement the Python class `BinarySensorCapabilities` described below.
Class description:
Class to represent BinarySensor capabilities.
Method signatures and docstrings:
- def default_display_categories(self) -> list[str] | None: Return the display categories for this entity.
- def interfaces(self) -> Generator[Alexa... | Implement the Python class `BinarySensorCapabilities` described below.
Class description:
Class to represent BinarySensor capabilities.
Method signatures and docstrings:
- def default_display_categories(self) -> list[str] | None: Return the display categories for this entity.
- def interfaces(self) -> Generator[Alexa... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class BinarySensorCapabilities:
"""Class to represent BinarySensor capabilities."""
def default_display_categories(self) -> list[str] | None:
"""Return the display categories for this entity."""
<|body_0|>
def interfaces(self) -> Generator[AlexaCapability, None, None]:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinarySensorCapabilities:
"""Class to represent BinarySensor capabilities."""
def default_display_categories(self) -> list[str] | None:
"""Return the display categories for this entity."""
sensor_type = self.get_type()
if sensor_type is self.TYPE_CONTACT:
return [Displ... | the_stack_v2_python_sparse | homeassistant/components/alexa/entities.py | home-assistant/core | train | 35,501 |
a26659093be29bf01d959ebb83c840f44e33725a | [
"super().__init__()\nself.MLP = nn.Sequential()\nself.conditional = conditional\nif self.conditional:\n input_size = latent_size + num_labels\nelse:\n input_size = latent_size\nfor i, (in_size, out_size) in enumerate(zip([input_size] + layer_sizes[:-1], layer_sizes)):\n self.MLP.add_module(name='L{:d}'.for... | <|body_start_0|>
super().__init__()
self.MLP = nn.Sequential()
self.conditional = conditional
if self.conditional:
input_size = latent_size + num_labels
else:
input_size = latent_size
for i, (in_size, out_size) in enumerate(zip([input_size] + layer... | Decoder Class | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Decoder Class"""
def __init__(self, layer_sizes, latent_size, conditional, num_labels):
"""Initialization"""
<|body_0|>
def forward(self, z, c):
"""Forward Process"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
... | stack_v2_sparse_classes_36k_train_014244 | 4,298 | no_license | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, layer_sizes, latent_size, conditional, num_labels)"
},
{
"docstring": "Forward Process",
"name": "forward",
"signature": "def forward(self, z, c)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000718 | Implement the Python class `Decoder` described below.
Class description:
Decoder Class
Method signatures and docstrings:
- def __init__(self, layer_sizes, latent_size, conditional, num_labels): Initialization
- def forward(self, z, c): Forward Process | Implement the Python class `Decoder` described below.
Class description:
Decoder Class
Method signatures and docstrings:
- def __init__(self, layer_sizes, latent_size, conditional, num_labels): Initialization
- def forward(self, z, c): Forward Process
<|skeleton|>
class Decoder:
"""Decoder Class"""
def __in... | 21c0bf459388bd616a64afc1a34441123b1f41fe | <|skeleton|>
class Decoder:
"""Decoder Class"""
def __init__(self, layer_sizes, latent_size, conditional, num_labels):
"""Initialization"""
<|body_0|>
def forward(self, z, c):
"""Forward Process"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""Decoder Class"""
def __init__(self, layer_sizes, latent_size, conditional, num_labels):
"""Initialization"""
super().__init__()
self.MLP = nn.Sequential()
self.conditional = conditional
if self.conditional:
input_size = latent_size + num_lab... | the_stack_v2_python_sparse | Reconstruction/models/CVAE.py | CHOcho-quan/CS385ML | train | 1 |
63f7d5aad2958e30dfecca4ff91c06ca00036e8c | [
"super().__init__(self.PARAMS, parameters)\nself.summary_name = parameters['summary_name']\nself.summary_filename = parameters['summary_filename']\nself.append_timecode = parameters.get('append_timecode', False)",
"df_new = df.copy()\nsummary = dispatcher.summary_dicts.get(self.summary_name, None)\nif not summary... | <|body_start_0|>
super().__init__(self.PARAMS, parameters)
self.summary_name = parameters['summary_name']
self.summary_filename = parameters['summary_filename']
self.append_timecode = parameters.get('append_timecode', False)
<|end_body_0|>
<|body_start_1|>
df_new = df.copy()
... | Summarize the column names in a collection of tabular files. Required remodeling parameters: - **summary_name** (*str*) The name of the summary. - **summary_filename** (*str*) Base filename of the summary. The purpose is to check that all of the tabular files have the same columns in same order. | SummarizeColumnNamesOp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SummarizeColumnNamesOp:
"""Summarize the column names in a collection of tabular files. Required remodeling parameters: - **summary_name** (*str*) The name of the summary. - **summary_filename** (*str*) Base filename of the summary. The purpose is to check that all of the tabular files have the s... | stack_v2_sparse_classes_36k_train_014245 | 6,458 | permissive | [
{
"docstring": "Constructor for summarize column names operation. Parameters: parameters (dict): Dictionary with the parameter values for required and optional parameters. :raises KeyError: - If a required parameter is missing. - If an unexpected parameter is provided. :raises TypeError: - If a parameter has th... | 2 | stack_v2_sparse_classes_30k_train_003270 | Implement the Python class `SummarizeColumnNamesOp` described below.
Class description:
Summarize the column names in a collection of tabular files. Required remodeling parameters: - **summary_name** (*str*) The name of the summary. - **summary_filename** (*str*) Base filename of the summary. The purpose is to check t... | Implement the Python class `SummarizeColumnNamesOp` described below.
Class description:
Summarize the column names in a collection of tabular files. Required remodeling parameters: - **summary_name** (*str*) The name of the summary. - **summary_filename** (*str*) Base filename of the summary. The purpose is to check t... | b871cae44bdf0ee68c688562c3b0af50b93343f5 | <|skeleton|>
class SummarizeColumnNamesOp:
"""Summarize the column names in a collection of tabular files. Required remodeling parameters: - **summary_name** (*str*) The name of the summary. - **summary_filename** (*str*) Base filename of the summary. The purpose is to check that all of the tabular files have the s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SummarizeColumnNamesOp:
"""Summarize the column names in a collection of tabular files. Required remodeling parameters: - **summary_name** (*str*) The name of the summary. - **summary_filename** (*str*) Base filename of the summary. The purpose is to check that all of the tabular files have the same columns i... | the_stack_v2_python_sparse | hed/tools/remodeling/operations/summarize_column_names_op.py | hed-standard/hed-python | train | 5 |
e654c31a5d0f0947ddfbd53ec68de3df613fa569 | [
"self.min_alias_length: Optional[int]\nself.max_alias_length: Optional[int]\nassert context.segment.is_type('select_statement')\nchildren = FunctionalContext(context).segment.children()\nfrom_expression_elements = children.recursive_crawl('from_expression_element')\nreturn self._lint_aliases(from_expression_element... | <|body_start_0|>
self.min_alias_length: Optional[int]
self.max_alias_length: Optional[int]
assert context.segment.is_type('select_statement')
children = FunctionalContext(context).segment.children()
from_expression_elements = children.recursive_crawl('from_expression_element')
... | Enforce table alias lengths in from clauses and join conditions. **Anti-pattern** In this example, alias ``o`` is used for the orders table. .. code-block:: sql SELECT SUM(o.amount) as order_amount, FROM orders as o **Best practice** Avoid aliases. Avoid short aliases when aliases are necessary. See also: :class:`Rule_... | Rule_AL06 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule_AL06:
"""Enforce table alias lengths in from clauses and join conditions. **Anti-pattern** In this example, alias ``o`` is used for the orders table. .. code-block:: sql SELECT SUM(o.amount) as order_amount, FROM orders as o **Best practice** Avoid aliases. Avoid short aliases when aliases a... | stack_v2_sparse_classes_36k_train_014246 | 4,131 | permissive | [
{
"docstring": "Identify aliases in from clause and join conditions. Find base table, table expressions in join, and other expressions in select clause and decide if it's needed to report them.",
"name": "_eval",
"signature": "def _eval(self, context: RuleContext) -> Optional[List[LintResult]]"
},
{... | 2 | stack_v2_sparse_classes_30k_train_002230 | Implement the Python class `Rule_AL06` described below.
Class description:
Enforce table alias lengths in from clauses and join conditions. **Anti-pattern** In this example, alias ``o`` is used for the orders table. .. code-block:: sql SELECT SUM(o.amount) as order_amount, FROM orders as o **Best practice** Avoid alia... | Implement the Python class `Rule_AL06` described below.
Class description:
Enforce table alias lengths in from clauses and join conditions. **Anti-pattern** In this example, alias ``o`` is used for the orders table. .. code-block:: sql SELECT SUM(o.amount) as order_amount, FROM orders as o **Best practice** Avoid alia... | a66da908907ee1eaf09d88a731025da29e7fca07 | <|skeleton|>
class Rule_AL06:
"""Enforce table alias lengths in from clauses and join conditions. **Anti-pattern** In this example, alias ``o`` is used for the orders table. .. code-block:: sql SELECT SUM(o.amount) as order_amount, FROM orders as o **Best practice** Avoid aliases. Avoid short aliases when aliases a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rule_AL06:
"""Enforce table alias lengths in from clauses and join conditions. **Anti-pattern** In this example, alias ``o`` is used for the orders table. .. code-block:: sql SELECT SUM(o.amount) as order_amount, FROM orders as o **Best practice** Avoid aliases. Avoid short aliases when aliases are necessary.... | the_stack_v2_python_sparse | src/sqlfluff/rules/aliasing/AL06.py | sqlfluff/sqlfluff | train | 5,931 |
8a30ba6e68dc719469a8af019d57f78a9fc009a4 | [
"TextProduct.__init__(self, text, utcnow=utcnow)\nself.data = None\nself.issue = None\nself.do_parsing()",
"shef = SHEFRE.search(self.text)\nif shef is None:\n self.warnings.append('Failed to find SHEF variable!')\n return\ngroup = shef.groupdict()\nself.issue = datetime.strptime(group['date'][-6:], '%y%m%d... | <|body_start_0|>
TextProduct.__init__(self, text, utcnow=utcnow)
self.data = None
self.issue = None
self.do_parsing()
<|end_body_0|>
<|body_start_1|>
shef = SHEFRE.search(self.text)
if shef is None:
self.warnings.append('Failed to find SHEF variable!')
... | Class representing a FFG Product | FFGProduct | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FFGProduct:
"""Class representing a FFG Product"""
def __init__(self, text, utcnow=None):
"""Constructor Args: text (str): text to parse"""
<|body_0|>
def do_parsing(self):
"""Process this file and save data"""
<|body_1|>
def sql(self, txn):
... | stack_v2_sparse_classes_36k_train_014247 | 3,878 | permissive | [
{
"docstring": "Constructor Args: text (str): text to parse",
"name": "__init__",
"signature": "def __init__(self, text, utcnow=None)"
},
{
"docstring": "Process this file and save data",
"name": "do_parsing",
"signature": "def do_parsing(self)"
},
{
"docstring": "Do the necessar... | 3 | null | Implement the Python class `FFGProduct` described below.
Class description:
Class representing a FFG Product
Method signatures and docstrings:
- def __init__(self, text, utcnow=None): Constructor Args: text (str): text to parse
- def do_parsing(self): Process this file and save data
- def sql(self, txn): Do the neces... | Implement the Python class `FFGProduct` described below.
Class description:
Class representing a FFG Product
Method signatures and docstrings:
- def __init__(self, text, utcnow=None): Constructor Args: text (str): text to parse
- def do_parsing(self): Process this file and save data
- def sql(self, txn): Do the neces... | 460f44394be05e1b655111595a3d7de3f7e47757 | <|skeleton|>
class FFGProduct:
"""Class representing a FFG Product"""
def __init__(self, text, utcnow=None):
"""Constructor Args: text (str): text to parse"""
<|body_0|>
def do_parsing(self):
"""Process this file and save data"""
<|body_1|>
def sql(self, txn):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FFGProduct:
"""Class representing a FFG Product"""
def __init__(self, text, utcnow=None):
"""Constructor Args: text (str): text to parse"""
TextProduct.__init__(self, text, utcnow=utcnow)
self.data = None
self.issue = None
self.do_parsing()
def do_parsing(self... | the_stack_v2_python_sparse | src/pyiem/nws/products/ffg.py | akrherz/pyIEM | train | 38 |
ff770cdc4a6effd0f1e7b72593e6691ed5ac43ba | [
"home = []\nbed = Bed('Bedroom')\nsofa = Sofa('Living Room')\nhome.append(bed)\nhome.append(sofa)\nmap_home = map_the_home(home)\nexpected = {bed.room: [bed], sofa.room: [sofa]}\nobserved = map_home\nself.assertDictEqual(expected, observed)",
"home = []\nhome.append(Bed('Bedroom'))\nhome.append(Sofa('Living Room'... | <|body_start_0|>
home = []
bed = Bed('Bedroom')
sofa = Sofa('Living Room')
home.append(bed)
home.append(sofa)
map_home = map_the_home(home)
expected = {bed.room: [bed], sofa.room: [sofa]}
observed = map_home
self.assertDictEqual(expected, observed)... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def test_map_the_home(self):
"""Test map_the_home function returns a dictionary"""
<|body_0|>
def test_counter(self):
"""Test counter function returns object and count for each objects"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
home = []
... | stack_v2_sparse_classes_36k_train_014248 | 979 | no_license | [
{
"docstring": "Test map_the_home function returns a dictionary",
"name": "test_map_the_home",
"signature": "def test_map_the_home(self)"
},
{
"docstring": "Test counter function returns object and count for each objects",
"name": "test_counter",
"signature": "def test_counter(self)"
}... | 2 | null | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_map_the_home(self): Test map_the_home function returns a dictionary
- def test_counter(self): Test counter function returns object and count for each objects | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_map_the_home(self): Test map_the_home function returns a dictionary
- def test_counter(self): Test counter function returns object and count for each objects
<|skeleton|>
class... | 7c62095b3b1829b9018431d26a6095ad777d72c0 | <|skeleton|>
class Test:
def test_map_the_home(self):
"""Test map_the_home function returns a dictionary"""
<|body_0|>
def test_counter(self):
"""Test counter function returns object and count for each objects"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
def test_map_the_home(self):
"""Test map_the_home function returns a dictionary"""
home = []
bed = Bed('Bedroom')
sofa = Sofa('Living Room')
home.append(bed)
home.append(sofa)
map_home = map_the_home(home)
expected = {bed.room: [bed], sofa.... | the_stack_v2_python_sparse | python_3/homework/Python3_Homework07/src/test_furnishings.py | cbabil/python-classes | train | 1 | |
7c511a6602f391e3bffb9781f6f1a91ddf583559 | [
"if x is None or x == 'None':\n return False\nreturn True",
"if x is None or x == 'None':\n return False\nreturn True",
"if x is None or x == 'None':\n return False\nreturn True",
"if x is None or x == 'None':\n return False\nreturn True",
"if x is None or x == 'None':\n return False\nreturn ... | <|body_start_0|>
if x is None or x == 'None':
return False
return True
<|end_body_0|>
<|body_start_1|>
if x is None or x == 'None':
return False
return True
<|end_body_1|>
<|body_start_2|>
if x is None or x == 'None':
return False
ret... | MDF_Person_validator_nonstandard_geocodes | [
"LicenseRef-scancode-public-domain",
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MDF_Person_validator_nonstandard_geocodes:
def is_valid_TABBLKST(self, x):
"""2020 Tabulation State (FIPS)"""
<|body_0|>
def is_valid_TABBLKCOU(self, x):
"""2020 Tabulation County (FIPS)"""
<|body_1|>
def is_valid_TABTRACTCE(self, x):
"""2020 Tab... | stack_v2_sparse_classes_36k_train_014249 | 23,123 | permissive | [
{
"docstring": "2020 Tabulation State (FIPS)",
"name": "is_valid_TABBLKST",
"signature": "def is_valid_TABBLKST(self, x)"
},
{
"docstring": "2020 Tabulation County (FIPS)",
"name": "is_valid_TABBLKCOU",
"signature": "def is_valid_TABBLKCOU(self, x)"
},
{
"docstring": "2020 Tabula... | 5 | stack_v2_sparse_classes_30k_train_000872 | Implement the Python class `MDF_Person_validator_nonstandard_geocodes` described below.
Class description:
Implement the MDF_Person_validator_nonstandard_geocodes class.
Method signatures and docstrings:
- def is_valid_TABBLKST(self, x): 2020 Tabulation State (FIPS)
- def is_valid_TABBLKCOU(self, x): 2020 Tabulation ... | Implement the Python class `MDF_Person_validator_nonstandard_geocodes` described below.
Class description:
Implement the MDF_Person_validator_nonstandard_geocodes class.
Method signatures and docstrings:
- def is_valid_TABBLKST(self, x): 2020 Tabulation State (FIPS)
- def is_valid_TABBLKCOU(self, x): 2020 Tabulation ... | 7f7ba44055da15d13b191180249e656e1bd398c6 | <|skeleton|>
class MDF_Person_validator_nonstandard_geocodes:
def is_valid_TABBLKST(self, x):
"""2020 Tabulation State (FIPS)"""
<|body_0|>
def is_valid_TABBLKCOU(self, x):
"""2020 Tabulation County (FIPS)"""
<|body_1|>
def is_valid_TABTRACTCE(self, x):
"""2020 Tab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MDF_Person_validator_nonstandard_geocodes:
def is_valid_TABBLKST(self, x):
"""2020 Tabulation State (FIPS)"""
if x is None or x == 'None':
return False
return True
def is_valid_TABBLKCOU(self, x):
"""2020 Tabulation County (FIPS)"""
if x is None or x ==... | the_stack_v2_python_sparse | das_decennial/programs/writer/cef_2020/mdf_validator_classes_nonstandard_geocodes.py | p-b-j/uscb-das-container-public | train | 1 | |
ff93c8852ea34cfdf10d78378c9f6386f1eaeb4b | [
"self.policy_network = policy_network\nself.value_network = value_network or policy_network\nself.estimate_q = estimate_q\nself.initial_state = None\nself.pdtype = make_pdtype(self.policy_network.output_shape, ac_space, init_scale=0.01)\nif estimate_q:\n self.value_fc = fc_build(self.value_network.output_shape, ... | <|body_start_0|>
self.policy_network = policy_network
self.value_network = value_network or policy_network
self.estimate_q = estimate_q
self.initial_state = None
self.pdtype = make_pdtype(self.policy_network.output_shape, ac_space, init_scale=0.01)
if estimate_q:
... | Encapsulates fields and methods for RL policy and value function estimation with shared parameters | PolicyWithValue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolicyWithValue:
"""Encapsulates fields and methods for RL policy and value function estimation with shared parameters"""
def __init__(self, ac_space, policy_network, value_network=None, estimate_q=False):
"""Parameters: ---------- ac_space action space policy_network keras network f... | stack_v2_sparse_classes_36k_train_014250 | 7,724 | no_license | [
{
"docstring": "Parameters: ---------- ac_space action space policy_network keras network for policy value_network keras network for value estimate_q q value or v value",
"name": "__init__",
"signature": "def __init__(self, ac_space, policy_network, value_network=None, estimate_q=False)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_test_000145 | Implement the Python class `PolicyWithValue` described below.
Class description:
Encapsulates fields and methods for RL policy and value function estimation with shared parameters
Method signatures and docstrings:
- def __init__(self, ac_space, policy_network, value_network=None, estimate_q=False): Parameters: ------... | Implement the Python class `PolicyWithValue` described below.
Class description:
Encapsulates fields and methods for RL policy and value function estimation with shared parameters
Method signatures and docstrings:
- def __init__(self, ac_space, policy_network, value_network=None, estimate_q=False): Parameters: ------... | 9a36f0955c90c7514444c42a81ca800772b7ef19 | <|skeleton|>
class PolicyWithValue:
"""Encapsulates fields and methods for RL policy and value function estimation with shared parameters"""
def __init__(self, ac_space, policy_network, value_network=None, estimate_q=False):
"""Parameters: ---------- ac_space action space policy_network keras network f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PolicyWithValue:
"""Encapsulates fields and methods for RL policy and value function estimation with shared parameters"""
def __init__(self, ac_space, policy_network, value_network=None, estimate_q=False):
"""Parameters: ---------- ac_space action space policy_network keras network for policy val... | the_stack_v2_python_sparse | common/policies.py | mjbigdel/tf2_grf | train | 0 |
6712e59568d483626d91a004a089d77daa8a0e74 | [
"grade_results = list(iter_program_course_grades(self.program_uuid, self.course_key, self.paginate_queryset))\nserializer = ProgramCourseGradeSerializer(grade_results, many=True)\nresponse_code = self._calc_response_code(grade_results)\nreturn self.get_paginated_response(serializer.data, status_code=response_code)"... | <|body_start_0|>
grade_results = list(iter_program_course_grades(self.program_uuid, self.course_key, self.paginate_queryset))
serializer = ProgramCourseGradeSerializer(grade_results, many=True)
response_code = self._calc_response_code(grade_results)
return self.get_paginated_response(ser... | A view for retrieving a paginated list of grades for all students enrolled in a given courserun through a given program. Path: ``/api/program_enrollments/v1/programs/{program_uuid}/courses/{course_id}/grades/`` Accepts: [GET] For GET requests, the path can contain an optional `page_size?=N` query parameter. The default... | ProgramCourseGradesView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgramCourseGradesView:
"""A view for retrieving a paginated list of grades for all students enrolled in a given courserun through a given program. Path: ``/api/program_enrollments/v1/programs/{program_uuid}/courses/{course_id}/grades/`` Accepts: [GET] For GET requests, the path can contain an o... | stack_v2_sparse_classes_36k_train_014251 | 41,703 | permissive | [
{
"docstring": "Defines the GET list endpoint for ProgramCourseGrade objects.",
"name": "get",
"signature": "def get(self, request, program_uuid=None, course_id=None)"
},
{
"docstring": "Returns HTTP status code appropriate for list of results, which may be grades or errors. Arguments: enrollmen... | 2 | null | Implement the Python class `ProgramCourseGradesView` described below.
Class description:
A view for retrieving a paginated list of grades for all students enrolled in a given courserun through a given program. Path: ``/api/program_enrollments/v1/programs/{program_uuid}/courses/{course_id}/grades/`` Accepts: [GET] For ... | Implement the Python class `ProgramCourseGradesView` described below.
Class description:
A view for retrieving a paginated list of grades for all students enrolled in a given courserun through a given program. Path: ``/api/program_enrollments/v1/programs/{program_uuid}/courses/{course_id}/grades/`` Accepts: [GET] For ... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class ProgramCourseGradesView:
"""A view for retrieving a paginated list of grades for all students enrolled in a given courserun through a given program. Path: ``/api/program_enrollments/v1/programs/{program_uuid}/courses/{course_id}/grades/`` Accepts: [GET] For GET requests, the path can contain an o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProgramCourseGradesView:
"""A view for retrieving a paginated list of grades for all students enrolled in a given courserun through a given program. Path: ``/api/program_enrollments/v1/programs/{program_uuid}/courses/{course_id}/grades/`` Accepts: [GET] For GET requests, the path can contain an optional `page... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/program_enrollments/rest_api/v1/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
1c6315bf1ee497701ab03a0319aa9cf1024b13f0 | [
"url = '/map/'\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.status_code, 200)",
"url = '/map/'\nself.client.login(username=self.adminUN, password='pass')\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.status_code, 200)",
"url = ... | <|body_start_0|>
url = '/map/'
response = self.client.get(url, HTTP_HOST='website.domain')
self.assertEqual(response.status_code, 200)
<|end_body_0|>
<|body_start_1|>
url = '/map/'
self.client.login(username=self.adminUN, password='pass')
response = self.client.get(url, ... | MapTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MapTestCase:
def test_not_logged_in(self):
"""Test that the map view will load whilst not logged in."""
<|body_0|>
def test_logged_in_admin(self):
"""Test that the map view will load whilst logged in as admin."""
<|body_1|>
def test_logged_in_non_admin(s... | stack_v2_sparse_classes_36k_train_014252 | 26,818 | permissive | [
{
"docstring": "Test that the map view will load whilst not logged in.",
"name": "test_not_logged_in",
"signature": "def test_not_logged_in(self)"
},
{
"docstring": "Test that the map view will load whilst logged in as admin.",
"name": "test_logged_in_admin",
"signature": "def test_logge... | 3 | null | Implement the Python class `MapTestCase` described below.
Class description:
Implement the MapTestCase class.
Method signatures and docstrings:
- def test_not_logged_in(self): Test that the map view will load whilst not logged in.
- def test_logged_in_admin(self): Test that the map view will load whilst logged in as ... | Implement the Python class `MapTestCase` described below.
Class description:
Implement the MapTestCase class.
Method signatures and docstrings:
- def test_not_logged_in(self): Test that the map view will load whilst not logged in.
- def test_logged_in_admin(self): Test that the map view will load whilst logged in as ... | 37d2942efcbdaad072f7a06ac876a40e0f69f702 | <|skeleton|>
class MapTestCase:
def test_not_logged_in(self):
"""Test that the map view will load whilst not logged in."""
<|body_0|>
def test_logged_in_admin(self):
"""Test that the map view will load whilst logged in as admin."""
<|body_1|>
def test_logged_in_non_admin(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MapTestCase:
def test_not_logged_in(self):
"""Test that the map view will load whilst not logged in."""
url = '/map/'
response = self.client.get(url, HTTP_HOST='website.domain')
self.assertEqual(response.status_code, 200)
def test_logged_in_admin(self):
"""Test tha... | the_stack_v2_python_sparse | mooring/test_views.py | dbca-wa/moorings | train | 0 | |
0d165e964441b323d680d2ffe8e2133785632579 | [
"if cls._jwt_token is None or time() + 30 > cls._exp:\n cls.update_authentication_token()\nreturn Authentication._jwt_token",
"if cls._credentials.access_key is None:\n raise UnauthorizedException('Environment variable smc_api_key is not set')\nelif cls._credentials.secret_access_key is None:\n raise Una... | <|body_start_0|>
if cls._jwt_token is None or time() + 30 > cls._exp:
cls.update_authentication_token()
return Authentication._jwt_token
<|end_body_0|>
<|body_start_1|>
if cls._credentials.access_key is None:
raise UnauthorizedException('Environment variable smc_api_key ... | Class to retrieve authentication token (jwt token). | Authentication | [
"MIT",
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Authentication:
"""Class to retrieve authentication token (jwt token)."""
def get_authentication_token(cls) -> str:
"""get a valid jwt token return: jwt-token"""
<|body_0|>
def update_authentication_token(cls) -> None:
"""update the jwt token (store the info in _... | stack_v2_sparse_classes_36k_train_014253 | 4,257 | permissive | [
{
"docstring": "get a valid jwt token return: jwt-token",
"name": "get_authentication_token",
"signature": "def get_authentication_token(cls) -> str"
},
{
"docstring": "update the jwt token (store the info in _jwt_token and _exp) :return: -",
"name": "update_authentication_token",
"signa... | 2 | stack_v2_sparse_classes_30k_train_014684 | Implement the Python class `Authentication` described below.
Class description:
Class to retrieve authentication token (jwt token).
Method signatures and docstrings:
- def get_authentication_token(cls) -> str: get a valid jwt token return: jwt-token
- def update_authentication_token(cls) -> None: update the jwt token... | Implement the Python class `Authentication` described below.
Class description:
Class to retrieve authentication token (jwt token).
Method signatures and docstrings:
- def get_authentication_token(cls) -> str: get a valid jwt token return: jwt-token
- def update_authentication_token(cls) -> None: update the jwt token... | 30f3b6c1fd80e5cfa5ce11e1daa08a09ab1e4e9b | <|skeleton|>
class Authentication:
"""Class to retrieve authentication token (jwt token)."""
def get_authentication_token(cls) -> str:
"""get a valid jwt token return: jwt-token"""
<|body_0|>
def update_authentication_token(cls) -> None:
"""update the jwt token (store the info in _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Authentication:
"""Class to retrieve authentication token (jwt token)."""
def get_authentication_token(cls) -> str:
"""get a valid jwt token return: jwt-token"""
if cls._jwt_token is None or time() + 30 > cls._exp:
cls.update_authentication_token()
return Authenticatio... | the_stack_v2_python_sparse | swift_cloud_py/authentication/authentication.py | stijnfleuren/SwiftCloudApi | train | 3 |
d35b2558f07eea0ae3caa126e359e075200f4e16 | [
"freq = defaultdict(lambda: 0)\nfor num in nums:\n freq[num] += 1\nreturn list(reversed(sorted(freq.keys(), key=lambda k: freq[k])))[:k]",
"freq = defaultdict(lambda: 0)\nfor num in nums:\n freq[num] += 1\nmax_heap = [(-val, key) for key, val in freq.items()]\nheapq.heapify(max_heap)\nres = []\nfor i in ran... | <|body_start_0|>
freq = defaultdict(lambda: 0)
for num in nums:
freq[num] += 1
return list(reversed(sorted(freq.keys(), key=lambda k: freq[k])))[:k]
<|end_body_0|>
<|body_start_1|>
freq = defaultdict(lambda: 0)
for num in nums:
freq[num] += 1
max_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_014254 | 1,619 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "topKFrequent",
"signature": "def topKFrequent(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "topKFrequent",
"signature": "def topKFrequent(self, nums, k)"
... | 2 | stack_v2_sparse_classes_30k_train_003725 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
<|s... | 860590239da0618c52967a55eda8d6bbe00bfa96 | <|skeleton|>
class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
freq = defaultdict(lambda: 0)
for num in nums:
freq[num] += 1
return list(reversed(sorted(freq.keys(), key=lambda k: freq[k])))[:k]
def topKFrequent(self, nums... | the_stack_v2_python_sparse | LeetCode/p0347/I/top-k-frequent-elements.py | Ynjxsjmh/PracticeMakesPerfect | train | 0 | |
3cc6e79333dd2a82241c0c3c15bf68772b8b5367 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.customTimeZone'.casefold():\n from .cust... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | TimeZoneBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeZoneBase:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeZoneBase:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_36k_train_014255 | 3,072 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TimeZoneBase",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | null | Implement the Python class `TimeZoneBase` described below.
Class description:
Implement the TimeZoneBase class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeZoneBase: Creates a new instance of the appropriate class based on discriminator value Ar... | Implement the Python class `TimeZoneBase` described below.
Class description:
Implement the TimeZoneBase class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeZoneBase: Creates a new instance of the appropriate class based on discriminator value Ar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TimeZoneBase:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeZoneBase:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeZoneBase:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeZoneBase:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TimeZoneBase""... | the_stack_v2_python_sparse | msgraph/generated/models/time_zone_base.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
a10f3896840863e9656d8ad04f0e9e7df978fbda | [
"end = len(nums) - 1\nif end < 0:\n return -1\nreturn self.search_with_rotated(nums, 0, end, target)",
"if end < begin:\n return -1\nif end == begin:\n if nums[end] == target:\n return end\n else:\n return -1\nmid = begin + (end - begin) / 2\nif nums[mid] == target:\n return mid\nif n... | <|body_start_0|>
end = len(nums) - 1
if end < 0:
return -1
return self.search_with_rotated(nums, 0, end, target)
<|end_body_0|>
<|body_start_1|>
if end < begin:
return -1
if end == begin:
if nums[end] == target:
return end
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search_with_rotated(self, nums, begin, end, target):
""":param nums: :param begin: :param end: :param target: :return:"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_014256 | 2,034 | permissive | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": ":param nums: :param begin: :param end: :param target: :return:",
"name": "search_with_rotated",
"signature": "def search_with_rotated(s... | 2 | stack_v2_sparse_classes_30k_train_012187 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search_with_rotated(self, nums, begin, end, target): :param nums: :param begin: :param e... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search_with_rotated(self, nums, begin, end, target): :param nums: :param begin: :param e... | 6ddba1f3b86c40639a8203cbc3373d52301c1b1f | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search_with_rotated(self, nums, begin, end, target):
""":param nums: :param begin: :param end: :param target: :return:"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
end = len(nums) - 1
if end < 0:
return -1
return self.search_with_rotated(nums, 0, end, target)
def search_with_rotated(self, nums, begin, end, target):
... | the_stack_v2_python_sparse | algorithms/python/leetcode/SearchinRotatedSortedArray.py | ytjia/leetcode | train | 0 | |
fdb50205a57c8de20eb19adcb651da8e3713f673 | [
"if self._context is None:\n context = {}\ncontext = dict(self._context or {})\ncontext.update({'create_company': True})\nself.with_context(context)\nreturn super(ResUsers, self).create(vals)",
"context = dict(self._context or {})\ncontext.update({'create_company': True})\nself.with_context(context)\nreturn su... | <|body_start_0|>
if self._context is None:
context = {}
context = dict(self._context or {})
context.update({'create_company': True})
self.with_context(context)
return super(ResUsers, self).create(vals)
<|end_body_0|>
<|body_start_1|>
context = dict(self._cont... | ResUsers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResUsers:
def create(self, vals):
"""To create a new record, adds a Boolean field to true indicates that the partner is a company"""
<|body_0|>
def write(self, values):
"""To write a new record, adds a Boolean field to true indicates that the partner is a company"""
... | stack_v2_sparse_classes_36k_train_014257 | 887 | no_license | [
{
"docstring": "To create a new record, adds a Boolean field to true indicates that the partner is a company",
"name": "create",
"signature": "def create(self, vals)"
},
{
"docstring": "To write a new record, adds a Boolean field to true indicates that the partner is a company",
"name": "wri... | 2 | null | Implement the Python class `ResUsers` described below.
Class description:
Implement the ResUsers class.
Method signatures and docstrings:
- def create(self, vals): To create a new record, adds a Boolean field to true indicates that the partner is a company
- def write(self, values): To write a new record, adds a Bool... | Implement the Python class `ResUsers` described below.
Class description:
Implement the ResUsers class.
Method signatures and docstrings:
- def create(self, vals): To create a new record, adds a Boolean field to true indicates that the partner is a company
- def write(self, values): To write a new record, adds a Bool... | b95909d0689fc787185290565f0873040a6027cf | <|skeleton|>
class ResUsers:
def create(self, vals):
"""To create a new record, adds a Boolean field to true indicates that the partner is a company"""
<|body_0|>
def write(self, values):
"""To write a new record, adds a Boolean field to true indicates that the partner is a company"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResUsers:
def create(self, vals):
"""To create a new record, adds a Boolean field to true indicates that the partner is a company"""
if self._context is None:
context = {}
context = dict(self._context or {})
context.update({'create_company': True})
self.with... | the_stack_v2_python_sparse | localizacion_metromed/l10n_ve_fiscal_requirements/model/res_users.py | Tysamncaweb/produccion2 | train | 1 | |
9b8bbcf2053666678ce9d62ef5a440122e522087 | [
"self.position_x = x\nself.position_y = y\nself.display_radius = r\nself.real_radius = r\nself.health = 5\nself.color = 0",
"if self.color == 0:\n arcade.draw_rectangle_filled(self.position_x, self.position_y, self.display_radius * 2, self.display_radius * 2, arcade.color.BLUE)\nelse:\n arcade.draw_rectangl... | <|body_start_0|>
self.position_x = x
self.position_y = y
self.display_radius = r
self.real_radius = r
self.health = 5
self.color = 0
<|end_body_0|>
<|body_start_1|>
if self.color == 0:
arcade.draw_rectangle_filled(self.position_x, self.position_y, sel... | Destructible | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Destructible:
def __init__(self, x, y, r):
"""A class to store all datas of a specific destructible obstacle"""
<|body_0|>
def draw(self):
"""draw the obstacle"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.position_x = x
self.position... | stack_v2_sparse_classes_36k_train_014258 | 2,776 | no_license | [
{
"docstring": "A class to store all datas of a specific destructible obstacle",
"name": "__init__",
"signature": "def __init__(self, x, y, r)"
},
{
"docstring": "draw the obstacle",
"name": "draw",
"signature": "def draw(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000206 | Implement the Python class `Destructible` described below.
Class description:
Implement the Destructible class.
Method signatures and docstrings:
- def __init__(self, x, y, r): A class to store all datas of a specific destructible obstacle
- def draw(self): draw the obstacle | Implement the Python class `Destructible` described below.
Class description:
Implement the Destructible class.
Method signatures and docstrings:
- def __init__(self, x, y, r): A class to store all datas of a specific destructible obstacle
- def draw(self): draw the obstacle
<|skeleton|>
class Destructible:
def... | 610e31aaf29fb7ee731600b959d9a4bd1d4f6458 | <|skeleton|>
class Destructible:
def __init__(self, x, y, r):
"""A class to store all datas of a specific destructible obstacle"""
<|body_0|>
def draw(self):
"""draw the obstacle"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Destructible:
def __init__(self, x, y, r):
"""A class to store all datas of a specific destructible obstacle"""
self.position_x = x
self.position_y = y
self.display_radius = r
self.real_radius = r
self.health = 5
self.color = 0
def draw(self):
... | the_stack_v2_python_sparse | Final project/Resource/Obstacles/Main.py | StRobertCHSCS/final-project-arcadenoobs | train | 0 | |
2204969031f66f48eea7643de0824395bf19ef04 | [
"Drawable.__init__(self, RIDE_SPRITE)\nself.start, self.end = (start, end)\nself.start_time, self.end_time = (times[0], times[1])",
"if time == self.start_time:\n return (self.start.get_position(time)[0], self.start.get_position(time)[1])\nelif time == self.end_time:\n return (self.end.get_position(time)[0]... | <|body_start_0|>
Drawable.__init__(self, RIDE_SPRITE)
self.start, self.end = (start, end)
self.start_time, self.end_time = (times[0], times[1])
<|end_body_0|>
<|body_start_1|>
if time == self.start_time:
return (self.start.get_position(time)[0], self.start.get_position(time)... | A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time - start_time - end_time >= timedelta(minutes = 1) (that is the sh... | Ride | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time - start_time - end_time >= timede... | stack_v2_sparse_classes_36k_train_014259 | 6,235 | no_license | [
{
"docstring": "Initialize a ride object with the given start and end information.",
"name": "__init__",
"signature": "def __init__(self, start: Station, end: Station, times: Tuple[datetime, datetime]) -> None"
},
{
"docstring": "Return the (long, lat) position of this ride for the given time. A... | 2 | stack_v2_sparse_classes_30k_train_018216 | Implement the Python class `Ride` described below.
Class description:
A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end... | Implement the Python class `Ride` described below.
Class description:
A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end... | ce720ce6a151c8bdf355096d9e86e421121a4793 | <|skeleton|>
class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time - start_time - end_time >= timede... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time - start_time - end_time >= timedelta(minutes =... | the_stack_v2_python_sparse | assignments/a1/bikeshare.py | ousmane-amadou/csc148-work | train | 2 |
401ae408ef9ecfbd03b7d9820b54d215e86c10cc | [
"tokens = SocialToken.objects.filter(app__provider=Provider.github.name).select_related('account__user')\nfor token in tokens:\n user = token.account.user\n try:\n GithubRepo.refresh_for_user(user, token)\n except Exception:\n logger.warning('Exception while refreshing GitHub repos for user',... | <|body_start_0|>
tokens = SocialToken.objects.filter(app__provider=Provider.github.name).select_related('account__user')
for token in tokens:
user = token.account.user
try:
GithubRepo.refresh_for_user(user, token)
except Exception:
logg... | A GitHub repository that a user has access to. A list of GitHub repos is maintained for each user that has a linked GitHub account. This makes it much faster for users to be able to search through a list when adding a GitHub source to a project. | GithubRepo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GithubRepo:
"""A GitHub repository that a user has access to. A list of GitHub repos is maintained for each user that has a linked GitHub account. This makes it much faster for users to be able to search through a list when adding a GitHub source to a project."""
def refresh_for_all_users():... | stack_v2_sparse_classes_36k_train_014260 | 4,620 | permissive | [
{
"docstring": "Refresh the list of repos for all users with a GitHub token.",
"name": "refresh_for_all_users",
"signature": "def refresh_for_all_users()"
},
{
"docstring": "Refresh the list of repos for the user.",
"name": "refresh_for_user",
"signature": "def refresh_for_user(user: Use... | 2 | stack_v2_sparse_classes_30k_train_017227 | Implement the Python class `GithubRepo` described below.
Class description:
A GitHub repository that a user has access to. A list of GitHub repos is maintained for each user that has a linked GitHub account. This makes it much faster for users to be able to search through a list when adding a GitHub source to a projec... | Implement the Python class `GithubRepo` described below.
Class description:
A GitHub repository that a user has access to. A list of GitHub repos is maintained for each user that has a linked GitHub account. This makes it much faster for users to be able to search through a list when adding a GitHub source to a projec... | b0edf060f4cc5494eef81fce62a563bd5b4e8e31 | <|skeleton|>
class GithubRepo:
"""A GitHub repository that a user has access to. A list of GitHub repos is maintained for each user that has a linked GitHub account. This makes it much faster for users to be able to search through a list when adding a GitHub source to a project."""
def refresh_for_all_users():... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GithubRepo:
"""A GitHub repository that a user has access to. A list of GitHub repos is maintained for each user that has a linked GitHub account. This makes it much faster for users to be able to search through a list when adding a GitHub source to a project."""
def refresh_for_all_users():
"""R... | the_stack_v2_python_sparse | manager/projects/models/providers.py | stencila/hub | train | 31 |
35aca5e55f14c8710c26c818a1e7781e9723ba00 | [
"self.env = env.copy()\nself.body = env.get('wsgi.input', None)\nself.headers = wsgiref.headers.Headers([])\nfor k, v in env.items():\n if 'HTTP' in k:\n key = k.replace('HTTP_', '').lower().replace('_', '-')\n self.headers[key] = v\nself.method = env['REQUEST_METHOD']\nself.server_protocol = env['... | <|body_start_0|>
self.env = env.copy()
self.body = env.get('wsgi.input', None)
self.headers = wsgiref.headers.Headers([])
for k, v in env.items():
if 'HTTP' in k:
key = k.replace('HTTP_', '').lower().replace('_', '-')
self.headers[key] = v
... | Request wrapper class. | Request | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Request:
"""Request wrapper class."""
def __init__(self, env):
"""Constructor for the Request wrapper class. Parses the HTTP headers and sets request attributes. @param env: wsgi environ dict @type env: dict"""
<|body_0|>
def read(self):
"""Reads the request payl... | stack_v2_sparse_classes_36k_train_014261 | 29,611 | permissive | [
{
"docstring": "Constructor for the Request wrapper class. Parses the HTTP headers and sets request attributes. @param env: wsgi environ dict @type env: dict",
"name": "__init__",
"signature": "def __init__(self, env)"
},
{
"docstring": "Reads the request payload, if available.",
"name": "re... | 2 | stack_v2_sparse_classes_30k_train_017863 | Implement the Python class `Request` described below.
Class description:
Request wrapper class.
Method signatures and docstrings:
- def __init__(self, env): Constructor for the Request wrapper class. Parses the HTTP headers and sets request attributes. @param env: wsgi environ dict @type env: dict
- def read(self): R... | Implement the Python class `Request` described below.
Class description:
Request wrapper class.
Method signatures and docstrings:
- def __init__(self, env): Constructor for the Request wrapper class. Parses the HTTP headers and sets request attributes. @param env: wsgi environ dict @type env: dict
- def read(self): R... | 69f9c870369085f4440033201e2fb263a463a523 | <|skeleton|>
class Request:
"""Request wrapper class."""
def __init__(self, env):
"""Constructor for the Request wrapper class. Parses the HTTP headers and sets request attributes. @param env: wsgi environ dict @type env: dict"""
<|body_0|>
def read(self):
"""Reads the request payl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Request:
"""Request wrapper class."""
def __init__(self, env):
"""Constructor for the Request wrapper class. Parses the HTTP headers and sets request attributes. @param env: wsgi environ dict @type env: dict"""
self.env = env.copy()
self.body = env.get('wsgi.input', None)
... | the_stack_v2_python_sparse | WebBrickLibs/brisa/core/webserver.py | AndyThirtover/wb_gateway | train | 0 |
8f7658cb4a77c491ad3afd2a95b6b72e8a6b9f9d | [
"try:\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)\n log.debug('Bind {}:{}'.format(self.listen_host, self.listen_port))\n self.sock.bind((self.listen_host, self.listen_port))\n self.sock.listen(1)\n self.sock.settimeout(10)\nexcept Exception as e:\n log.excep... | <|body_start_0|>
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
log.debug('Bind {}:{}'.format(self.listen_host, self.listen_port))
self.sock.bind((self.listen_host, self.listen_port))
self.sock.listen(1)
self.soc... | TCPSocketListener | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TCPSocketListener:
def start(self):
"""Spin up the TCP listener :return: None"""
<|body_0|>
def handle_connection(self, conn, addr):
"""Creates a new connection handler thread using the specified protocol :param conn: Incoming connection :param addr: Source address :... | stack_v2_sparse_classes_36k_train_014262 | 6,867 | no_license | [
{
"docstring": "Spin up the TCP listener :return: None",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "Creates a new connection handler thread using the specified protocol :param conn: Incoming connection :param addr: Source address :return: None",
"name": "handle_connec... | 2 | stack_v2_sparse_classes_30k_train_020803 | Implement the Python class `TCPSocketListener` described below.
Class description:
Implement the TCPSocketListener class.
Method signatures and docstrings:
- def start(self): Spin up the TCP listener :return: None
- def handle_connection(self, conn, addr): Creates a new connection handler thread using the specified p... | Implement the Python class `TCPSocketListener` described below.
Class description:
Implement the TCPSocketListener class.
Method signatures and docstrings:
- def start(self): Spin up the TCP listener :return: None
- def handle_connection(self, conn, addr): Creates a new connection handler thread using the specified p... | f95f4aa41929675daf6cd773e85e7bc1e130105d | <|skeleton|>
class TCPSocketListener:
def start(self):
"""Spin up the TCP listener :return: None"""
<|body_0|>
def handle_connection(self, conn, addr):
"""Creates a new connection handler thread using the specified protocol :param conn: Incoming connection :param addr: Source address :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TCPSocketListener:
def start(self):
"""Spin up the TCP listener :return: None"""
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
log.debug('Bind {}:{}'.format(self.listen_host, self.listen_port))
self.sock.bind((self.li... | the_stack_v2_python_sparse | pynetsim/lib/listener.py | rainforest-tokyo/tenet | train | 0 | |
7bba5445d50a0c8a8f23d5c74fb3669761addd0c | [
"self.name = name\nself.light = light\nif self.light:\n self.d = common_light.copy()\nelse:\n self.d = common_dark.copy()\nself.d.update(extra)",
"if self.light:\n self.d.update({k: common_light[k] for k in common_light if k not in self.d})\nelse:\n self.d.update({k: common_dark[k] for k in common_dar... | <|body_start_0|>
self.name = name
self.light = light
if self.light:
self.d = common_light.copy()
else:
self.d = common_dark.copy()
self.d.update(extra)
<|end_body_0|>
<|body_start_1|>
if self.light:
self.d.update({k: common_light[k] fo... | Abstract class that represents a theme | Theme | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Theme:
"""Abstract class that represents a theme"""
def __init__(self, name, light=True, extra=None):
"""Initialise. light indicates whether to initialize with the light theme color values. Extra is a dict containing: some keys in 'css_colors': value => a Color some keys in 'rgb_pref... | stack_v2_sparse_classes_36k_train_014263 | 18,193 | no_license | [
{
"docstring": "Initialise. light indicates whether to initialize with the light theme color values. Extra is a dict containing: some keys in 'css_colors': value => a Color some keys in 'rgb_prefs': value => a Color some keys in 'variant_prefs': value => a tuple (weight, fg, bg) where weight is \"DEFAULT\", \"N... | 3 | stack_v2_sparse_classes_30k_test_001005 | Implement the Python class `Theme` described below.
Class description:
Abstract class that represents a theme
Method signatures and docstrings:
- def __init__(self, name, light=True, extra=None): Initialise. light indicates whether to initialize with the light theme color values. Extra is a dict containing: some keys... | Implement the Python class `Theme` described below.
Class description:
Abstract class that represents a theme
Method signatures and docstrings:
- def __init__(self, name, light=True, extra=None): Initialise. light indicates whether to initialize with the light theme color values. Extra is a dict containing: some keys... | 5b91c1816aadfa3a08bba730b8dfd3f6a0785463 | <|skeleton|>
class Theme:
"""Abstract class that represents a theme"""
def __init__(self, name, light=True, extra=None):
"""Initialise. light indicates whether to initialize with the light theme color values. Extra is a dict containing: some keys in 'css_colors': value => a Color some keys in 'rgb_pref... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Theme:
"""Abstract class that represents a theme"""
def __init__(self, name, light=True, extra=None):
"""Initialise. light indicates whether to initialize with the light theme color values. Extra is a dict containing: some keys in 'css_colors': value => a Color some keys in 'rgb_prefs': value => ... | the_stack_v2_python_sparse | Code/share/gps/support/ui/theme_handling.py | AaronC98/PlaneSystem | train | 0 |
d81eeb5957717858520517bfda383ed7a7717a04 | [
"table = HTML().table(border='1', klass=TABLE_ENV)\nheading = table.thead.tr\nheading.th('No')\nheading.th('Parameter')\nheading.th('Value')\ndetails = [('application', app.name), ('report time', strftime('%Y-%m-%d %H:%M:%S', gmtime())), ('host', app.ip), ('pid', app.pid), ('user', getpass.getuser()), ('os', app.ge... | <|body_start_0|>
table = HTML().table(border='1', klass=TABLE_ENV)
heading = table.thead.tr
heading.th('No')
heading.th('Parameter')
heading.th('Value')
details = [('application', app.name), ('report time', strftime('%Y-%m-%d %H:%M:%S', gmtime())), ('host', app.ip), ('pid... | Builds html report with details about profiling environment | EnvReportBuilder | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvReportBuilder:
"""Builds html report with details about profiling environment"""
def buildEnvironmentTable(app):
"""Builds a table with environment details :param app: an instance of xpedite app, to interact with target application"""
<|body_0|>
def buildCpuInfoTable(... | stack_v2_sparse_classes_36k_train_014264 | 4,154 | permissive | [
{
"docstring": "Builds a table with environment details :param app: an instance of xpedite app, to interact with target application",
"name": "buildEnvironmentTable",
"signature": "def buildEnvironmentTable(app)"
},
{
"docstring": "Builds a table with cpu info details :param app: an instance of ... | 3 | stack_v2_sparse_classes_30k_train_010763 | Implement the Python class `EnvReportBuilder` described below.
Class description:
Builds html report with details about profiling environment
Method signatures and docstrings:
- def buildEnvironmentTable(app): Builds a table with environment details :param app: an instance of xpedite app, to interact with target appl... | Implement the Python class `EnvReportBuilder` described below.
Class description:
Builds html report with details about profiling environment
Method signatures and docstrings:
- def buildEnvironmentTable(app): Builds a table with environment details :param app: an instance of xpedite app, to interact with target appl... | d6b67e98d4b640c98499a373425f1f009e5b9061 | <|skeleton|>
class EnvReportBuilder:
"""Builds html report with details about profiling environment"""
def buildEnvironmentTable(app):
"""Builds a table with environment details :param app: an instance of xpedite app, to interact with target application"""
<|body_0|>
def buildCpuInfoTable(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnvReportBuilder:
"""Builds html report with details about profiling environment"""
def buildEnvironmentTable(app):
"""Builds a table with environment details :param app: an instance of xpedite app, to interact with target application"""
table = HTML().table(border='1', klass=TABLE_ENV)
... | the_stack_v2_python_sparse | scripts/lib/xpedite/report/env.py | dendisuhubdy/Xpedite | train | 1 |
8449a38e460d207821a0f89498cfa382249505b7 | [
"self.inner_parameter_id: str = inner_parameter_id\nself.coupled = False\nself.inner_parameter_type: str = inner_parameter_type\nif scale not in {LIN, LOG, LOG10}:\n raise ValueError(f'Scale not recognized: {scale}.')\nself.scale = scale\nif inner_parameter_type not in (InnerParameterType.OPTIMAL_SCALING, InnerP... | <|body_start_0|>
self.inner_parameter_id: str = inner_parameter_id
self.coupled = False
self.inner_parameter_type: str = inner_parameter_type
if scale not in {LIN, LOG, LOG10}:
raise ValueError(f'Scale not recognized: {scale}.')
self.scale = scale
if inner_par... | An inner parameter of a hierarchical optimization problem. Attributes ---------- coupled: Whether the inner parameter is part of an observable that has both an offset and scaling inner parameter. dummy_value: Value to be used when the optimal parameter is not yet known (in particular to simulate unscaled observables). ... | InnerParameter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InnerParameter:
"""An inner parameter of a hierarchical optimization problem. Attributes ---------- coupled: Whether the inner parameter is part of an observable that has both an offset and scaling inner parameter. dummy_value: Value to be used when the optimal parameter is not yet known (in part... | stack_v2_sparse_classes_36k_train_014265 | 3,387 | permissive | [
{
"docstring": "Construct. Parameters ---------- See class attributes.",
"name": "__init__",
"signature": "def __init__(self, inner_parameter_id: str, inner_parameter_type: InnerParameterType, scale: Literal[LIN, LOG, LOG10]=LIN, lb: float=-np.inf, ub: float=np.inf, ixs: Any=None, dummy_value: float=Non... | 2 | null | Implement the Python class `InnerParameter` described below.
Class description:
An inner parameter of a hierarchical optimization problem. Attributes ---------- coupled: Whether the inner parameter is part of an observable that has both an offset and scaling inner parameter. dummy_value: Value to be used when the opti... | Implement the Python class `InnerParameter` described below.
Class description:
An inner parameter of a hierarchical optimization problem. Attributes ---------- coupled: Whether the inner parameter is part of an observable that has both an offset and scaling inner parameter. dummy_value: Value to be used when the opti... | 9a754573a7b77d30d5dc1f67a8dc1be6c29f1640 | <|skeleton|>
class InnerParameter:
"""An inner parameter of a hierarchical optimization problem. Attributes ---------- coupled: Whether the inner parameter is part of an observable that has both an offset and scaling inner parameter. dummy_value: Value to be used when the optimal parameter is not yet known (in part... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InnerParameter:
"""An inner parameter of a hierarchical optimization problem. Attributes ---------- coupled: Whether the inner parameter is part of an observable that has both an offset and scaling inner parameter. dummy_value: Value to be used when the optimal parameter is not yet known (in particular to sim... | the_stack_v2_python_sparse | pypesto/hierarchical/parameter.py | ICB-DCM/pyPESTO | train | 174 |
1d26a1d4852d3355b041e11199025626fe819d47 | [
"self.__capa = capacity\nself.__size = 0\nself.__min_freq = 0\nself.__freq_to_nodes = collections.defaultdict(LinkedList)\nself.__key_to_node = {}",
"if key not in self.__key_to_node:\n return -1\nold_node = self.__key_to_node[key]\nself.__key_to_node[key] = ListNode(key, old_node.val, old_node.freq)\nself.__f... | <|body_start_0|>
self.__capa = capacity
self.__size = 0
self.__min_freq = 0
self.__freq_to_nodes = collections.defaultdict(LinkedList)
self.__key_to_node = {}
<|end_body_0|>
<|body_start_1|>
if key not in self.__key_to_node:
return -1
old_node = self.... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_014266 | 8,904 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 5195b032d8000a3d888e2d4068984011bebd3b84 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.__capa = capacity
self.__size = 0
self.__min_freq = 0
self.__freq_to_nodes = collections.defaultdict(LinkedList)
self.__key_to_node = {}
def get(self, key):
""":type key: int :rt... | the_stack_v2_python_sparse | leetcode_python/Design/lfu_cache.py | ChillOrb/CS_basics | train | 1 | |
8c84f3e6847a1b5892a2604b430983715a9dca6e | [
"if 'id' not in data:\n raise BaseException('Practitioner requires id')\nself.data = data\n_id = data['id']\nif not _id in self.__class__.instances:\n self.__class__.instances[_id] = self",
"pats = csv.reader(open(patient_file_name, 'U'), dialect='excel-tab')\nheader = next(pats)\nfor pat in pats:\n cls(... | <|body_start_0|>
if 'id' not in data:
raise BaseException('Practitioner requires id')
self.data = data
_id = data['id']
if not _id in self.__class__.instances:
self.__class__.instances[_id] = self
<|end_body_0|>
<|body_start_1|>
pats = csv.reader(open(pat... | Practitioner | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Practitioner:
def __init__(self, data):
"""Creates a Practitioner instance and stores it into the static store"""
<|body_0|>
def load(cls, patient_file_name=PRACTITIONERS_FILE):
"""Load patients from a data file"""
<|body_1|>
def toJSON(self, prefix=''):... | stack_v2_sparse_classes_36k_train_014267 | 4,442 | permissive | [
{
"docstring": "Creates a Practitioner instance and stores it into the static store",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Load patients from a data file",
"name": "load",
"signature": "def load(cls, patient_file_name=PRACTITIONERS_FILE)"
},
... | 3 | stack_v2_sparse_classes_30k_train_016685 | Implement the Python class `Practitioner` described below.
Class description:
Implement the Practitioner class.
Method signatures and docstrings:
- def __init__(self, data): Creates a Practitioner instance and stores it into the static store
- def load(cls, patient_file_name=PRACTITIONERS_FILE): Load patients from a ... | Implement the Python class `Practitioner` described below.
Class description:
Implement the Practitioner class.
Method signatures and docstrings:
- def __init__(self, data): Creates a Practitioner instance and stores it into the static store
- def load(cls, patient_file_name=PRACTITIONERS_FILE): Load patients from a ... | bd9fd3bf6db8b339c7c7fb28c545ec14cc1d0801 | <|skeleton|>
class Practitioner:
def __init__(self, data):
"""Creates a Practitioner instance and stores it into the static store"""
<|body_0|>
def load(cls, patient_file_name=PRACTITIONERS_FILE):
"""Load patients from a data file"""
<|body_1|>
def toJSON(self, prefix=''):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Practitioner:
def __init__(self, data):
"""Creates a Practitioner instance and stores it into the static store"""
if 'id' not in data:
raise BaseException('Practitioner requires id')
self.data = data
_id = data['id']
if not _id in self.__class__.instances:
... | the_stack_v2_python_sparse | bin/practitioner.py | rezacsedu/FHIR_Resource_Generator | train | 1 | |
fded211e5b91ce2dd6024f3934dfdc3c1c394c51 | [
"row = set()\ncolumn = set()\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == 0:\n row.add(i)\n column.add(j)\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if i in row or j in column:\n matrix[i][j] = 0",
... | <|body_start_0|>
row = set()
column = set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
row.add(i)
column.add(j)
for i in range(len(matrix)):
for j in range(len(matrix[0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead. O(m+n) space and O(mn) time"""
<|body_0|>
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-plac... | stack_v2_sparse_classes_36k_train_014268 | 1,492 | no_license | [
{
"docstring": "Do not return anything, modify matrix in-place instead. O(m+n) space and O(mn) time",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix: List[List[int]]) -> None"
},
{
"docstring": "Do not return anything, modify matrix in-place instead. O(1) space O(mn) time, is_col ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead. O(m+n) space and O(mn) time
- def setZeroes(self, matrix: List[List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead. O(m+n) space and O(mn) time
- def setZeroes(self, matrix: List[List[... | 237985eea9853a658f811355e8c75d6b141e40b2 | <|skeleton|>
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead. O(m+n) space and O(mn) time"""
<|body_0|>
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-plac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead. O(m+n) space and O(mn) time"""
row = set()
column = set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matri... | the_stack_v2_python_sparse | 73. Set Matrix Zeroes.py | Eustaceyi/Leetcode | train | 0 | |
e21665db42c86b148596be54b83043287db3d271 | [
"from sktime.distances._distance_alignment_paths import compute_min_return_path\nfrom sktime.distances._edr_numba import _edr_cost_matrix\nfrom sktime.distances.lower_bounding import resolve_bounding_matrix\nfrom sktime.utils.numba.njit import njit\n_bounding_matrix = resolve_bounding_matrix(x, y, window, itakura_m... | <|body_start_0|>
from sktime.distances._distance_alignment_paths import compute_min_return_path
from sktime.distances._edr_numba import _edr_cost_matrix
from sktime.distances.lower_bounding import resolve_bounding_matrix
from sktime.utils.numba.njit import njit
_bounding_matrix =... | Edit distance for real sequences (EDR) between two time series. ERP was adapted in [1] specifically for distances between trajectories. Like LCSS, EDR uses a distance threshold to define when two elements of a series match. However, rather than simply count matches and look for the longest sequence, ERP applies a (cons... | _EdrDistance | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _EdrDistance:
"""Edit distance for real sequences (EDR) between two time series. ERP was adapted in [1] specifically for distances between trajectories. Like LCSS, EDR uses a distance threshold to define when two elements of a series match. However, rather than simply count matches and look for t... | stack_v2_sparse_classes_36k_train_014269 | 8,517 | permissive | [
{
"docstring": "Create a no_python compiled edr alignment path distance callable. Series should be shape (d, m), where d is the number of dimensions, m the series length. Series can be different lengths. Parameters ---------- x: np.ndarray (2d array of shape (d,m1)). First time series. y: np.ndarray (2d array o... | 2 | null | Implement the Python class `_EdrDistance` described below.
Class description:
Edit distance for real sequences (EDR) between two time series. ERP was adapted in [1] specifically for distances between trajectories. Like LCSS, EDR uses a distance threshold to define when two elements of a series match. However, rather t... | Implement the Python class `_EdrDistance` described below.
Class description:
Edit distance for real sequences (EDR) between two time series. ERP was adapted in [1] specifically for distances between trajectories. Like LCSS, EDR uses a distance threshold to define when two elements of a series match. However, rather t... | 70b2bfaaa597eb31bc3a1032366dcc0e1f4c8a9f | <|skeleton|>
class _EdrDistance:
"""Edit distance for real sequences (EDR) between two time series. ERP was adapted in [1] specifically for distances between trajectories. Like LCSS, EDR uses a distance threshold to define when two elements of a series match. However, rather than simply count matches and look for t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _EdrDistance:
"""Edit distance for real sequences (EDR) between two time series. ERP was adapted in [1] specifically for distances between trajectories. Like LCSS, EDR uses a distance threshold to define when two elements of a series match. However, rather than simply count matches and look for the longest se... | the_stack_v2_python_sparse | sktime/distances/_edr.py | sktime/sktime | train | 1,117 |
9e5e155be763ab5a3238cc851665aedb4d18fe1d | [
"super(QSR_Arg_Prob_Relations_Distance, self).__init__()\nself._unique_id = 'argprobd'\n'str: Unique identifier of a QSR.'\nself.allowed_value_types = (tuple, list)\n'tuple of datatypes: ?'\nself.value_sort_key = lambda x: x[1][0]\n'?'",
"u = (x - mu) / np.abs(sigma)\ny = 1 / (np.sqrt(2 * np.pi) * np.abs(sigma)) ... | <|body_start_0|>
super(QSR_Arg_Prob_Relations_Distance, self).__init__()
self._unique_id = 'argprobd'
'str: Unique identifier of a QSR.'
self.allowed_value_types = (tuple, list)
'tuple of datatypes: ?'
self.value_sort_key = lambda x: x[1][0]
'?'
<|end_body_0|>
<|... | Probabilistic ard-distances. Values of the abstract properties * **_unique_id** = "argprobd" * **_all_possible_relations** = depends on what user has passed * **_dtype** = "points" QSR Parameters (for `dynamic_args`) * **'qsr_relations_and_values'**: A dictionary with keys being the relations labels and values .. seeal... | QSR_Arg_Prob_Relations_Distance | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QSR_Arg_Prob_Relations_Distance:
"""Probabilistic ard-distances. Values of the abstract properties * **_unique_id** = "argprobd" * **_all_possible_relations** = depends on what user has passed * **_dtype** = "points" QSR Parameters (for `dynamic_args`) * **'qsr_relations_and_values'**: A dictiona... | stack_v2_sparse_classes_36k_train_014270 | 2,181 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":param x: :type x: :param mu: :type mu: :param sigma: :type sigma: :return: :rtype:",
"name": "__normpdf",
"signature": "def __normpdf(self, x, mu, sigma)"
},
{
"docstring": ":... | 3 | stack_v2_sparse_classes_30k_train_002916 | Implement the Python class `QSR_Arg_Prob_Relations_Distance` described below.
Class description:
Probabilistic ard-distances. Values of the abstract properties * **_unique_id** = "argprobd" * **_all_possible_relations** = depends on what user has passed * **_dtype** = "points" QSR Parameters (for `dynamic_args`) * **'... | Implement the Python class `QSR_Arg_Prob_Relations_Distance` described below.
Class description:
Probabilistic ard-distances. Values of the abstract properties * **_unique_id** = "argprobd" * **_all_possible_relations** = depends on what user has passed * **_dtype** = "points" QSR Parameters (for `dynamic_args`) * **'... | da3c6b47cdd7ec9b211a33d107ec4a6b2a0ff4b3 | <|skeleton|>
class QSR_Arg_Prob_Relations_Distance:
"""Probabilistic ard-distances. Values of the abstract properties * **_unique_id** = "argprobd" * **_all_possible_relations** = depends on what user has passed * **_dtype** = "points" QSR Parameters (for `dynamic_args`) * **'qsr_relations_and_values'**: A dictiona... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QSR_Arg_Prob_Relations_Distance:
"""Probabilistic ard-distances. Values of the abstract properties * **_unique_id** = "argprobd" * **_all_possible_relations** = depends on what user has passed * **_dtype** = "points" QSR Parameters (for `dynamic_args`) * **'qsr_relations_and_values'**: A dictionary with keys ... | the_stack_v2_python_sparse | src/qsr_lib/src/qsrlib_qsrs/qsr_arg_prob_relations_distance.py | MihirSPatil/Utilizing-qualitative-spatial-representations-for-control-of-mobile-robots- | train | 0 |
fdb1802c72566cf4c64fd1b41bb1debdca5c1a7a | [
"waterLevels = self.water(height, len(height))\nsol = waterLevels[0]\nif waterLevels[1] != 0 and waterLevels[2] < len(height) - 1:\n segment = height[waterLevels[2]:len(height)]\n segment.reverse()\n sol += self.water(segment, len(segment))[0]\nreturn sol",
"i = 0\nwater = 0\nwaterTemp = 0\nprevH = 0\npr... | <|body_start_0|>
waterLevels = self.water(height, len(height))
sol = waterLevels[0]
if waterLevels[1] != 0 and waterLevels[2] < len(height) - 1:
segment = height[waterLevels[2]:len(height)]
segment.reverse()
sol += self.water(segment, len(segment))[0]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def water(self, array, l):
""":type height: List[int] :rtype: array"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
waterLevels = self.water(height, len(height))
... | stack_v2_sparse_classes_36k_train_014271 | 2,088 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trap",
"signature": "def trap(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: array",
"name": "water",
"signature": "def water(self, array, l)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010001 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): :type height: List[int] :rtype: int
- def water(self, array, l): :type height: List[int] :rtype: array | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): :type height: List[int] :rtype: int
- def water(self, array, l): :type height: List[int] :rtype: array
<|skeleton|>
class Solution:
def trap(self, h... | 61933e7c0b8d8ffef9bd9a4af4fddfdb77568b62 | <|skeleton|>
class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def water(self, array, l):
""":type height: List[int] :rtype: array"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
waterLevels = self.water(height, len(height))
sol = waterLevels[0]
if waterLevels[1] != 0 and waterLevels[2] < len(height) - 1:
segment = height[waterLevels[2]:len(height)]
segme... | the_stack_v2_python_sparse | 42-Trapping-Rain-Water.py | OhMesch/Algorithm-Problems | train | 0 | |
9b414a61e3af9628677e9473eb3f0865a0270b59 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the User List service. Service to manage user lists. | UserListServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserListServiceServicer:
"""Proto file describing the User List service. Service to manage user lists."""
def GetUserList(self, request, context):
"""Returns the requested user list."""
<|body_0|>
def MutateUserLists(self, request, context):
"""Creates or updates... | stack_v2_sparse_classes_36k_train_014272 | 5,272 | permissive | [
{
"docstring": "Returns the requested user list.",
"name": "GetUserList",
"signature": "def GetUserList(self, request, context)"
},
{
"docstring": "Creates or updates user lists. Operation statuses are returned.",
"name": "MutateUserLists",
"signature": "def MutateUserLists(self, request... | 2 | null | Implement the Python class `UserListServiceServicer` described below.
Class description:
Proto file describing the User List service. Service to manage user lists.
Method signatures and docstrings:
- def GetUserList(self, request, context): Returns the requested user list.
- def MutateUserLists(self, request, context... | Implement the Python class `UserListServiceServicer` described below.
Class description:
Proto file describing the User List service. Service to manage user lists.
Method signatures and docstrings:
- def GetUserList(self, request, context): Returns the requested user list.
- def MutateUserLists(self, request, context... | 969eff5b6c3cec59d21191fa178cffb6270074c3 | <|skeleton|>
class UserListServiceServicer:
"""Proto file describing the User List service. Service to manage user lists."""
def GetUserList(self, request, context):
"""Returns the requested user list."""
<|body_0|>
def MutateUserLists(self, request, context):
"""Creates or updates... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserListServiceServicer:
"""Proto file describing the User List service. Service to manage user lists."""
def GetUserList(self, request, context):
"""Returns the requested user list."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | google/ads/google_ads/v6/proto/services/user_list_service_pb2_grpc.py | VincentFritzsche/google-ads-python | train | 0 |
1c8cdc58c71963fa23ce3e6437cb274d5c0d6972 | [
"self.hm = {}\nself.ls = []\nself.capacity = capacity",
"try:\n tmp = self.ls.pop(self.hm[key][1])\n self.ls.append(tmp)\n self.hm[key][1] = len(self.ls) - 1\n return self.hm[key][0]\nexcept KeyError:\n return -1",
"if self.capacity == len(self.ls):\n del self.hm[self.ls.pop(0)]\nif key not in... | <|body_start_0|>
self.hm = {}
self.ls = []
self.capacity = capacity
<|end_body_0|>
<|body_start_1|>
try:
tmp = self.ls.pop(self.hm[key][1])
self.ls.append(tmp)
self.hm[key][1] = len(self.ls) - 1
return self.hm[key][0]
except KeyErr... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_014273 | 1,544 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | cb74072467a7350c7f34e2ccd9f2ae790583ef85 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.hm = {}
self.ls = []
self.capacity = capacity
def get(self, key):
""":type key: int :rtype: int"""
try:
tmp = self.ls.pop(self.hm[key][1])
self.ls.append(tmp)
... | the_stack_v2_python_sparse | Practice/LRU_Cache.py | KarAbhishek/MSBIC | train | 0 | |
a6aa8c935d6805a2ba1311fc573e73fbb867b63b | [
"self.start_timestamp = event_start\nself.end_timestamp = event_end\nself.reports = list()",
"if file:\n lines = [line for line in open(file, 'r').readlines()]\n formatting = '%m/%d/%y %H:%M %p'\n enforcement_action_report = dict()\n enforcement_action_report['empty_lines'] = [i for i in range(len(lin... | <|body_start_0|>
self.start_timestamp = event_start
self.end_timestamp = event_end
self.reports = list()
<|end_body_0|>
<|body_start_1|>
if file:
lines = [line for line in open(file, 'r').readlines()]
formatting = '%m/%d/%y %H:%M %p'
enforcement_actio... | The FileValidator class is responsible for performing the validation operation of a log file. (i.e Checking for empty lines, missing timestamps and ensuring all timestamps in the file are within range of the start and end dates provided in the event configuration.) | FileValidator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileValidator:
"""The FileValidator class is responsible for performing the validation operation of a log file. (i.e Checking for empty lines, missing timestamps and ensuring all timestamps in the file are within range of the start and end dates provided in the event configuration.)"""
def _... | stack_v2_sparse_classes_36k_train_014274 | 10,150 | no_license | [
{
"docstring": ":param event_start: The start date and start time of an event. :param event_end: The end date and end time of an event.",
"name": "__init__",
"signature": "def __init__(self, event_start, event_end)"
},
{
"docstring": ":param file:(str) The file to be validated. :return:(bool) Va... | 2 | stack_v2_sparse_classes_30k_train_017451 | Implement the Python class `FileValidator` described below.
Class description:
The FileValidator class is responsible for performing the validation operation of a log file. (i.e Checking for empty lines, missing timestamps and ensuring all timestamps in the file are within range of the start and end dates provided in ... | Implement the Python class `FileValidator` described below.
Class description:
The FileValidator class is responsible for performing the validation operation of a log file. (i.e Checking for empty lines, missing timestamps and ensuring all timestamps in the file are within range of the start and end dates provided in ... | 9b8f405f63114cfc8fd91254c1609cfad3e058e6 | <|skeleton|>
class FileValidator:
"""The FileValidator class is responsible for performing the validation operation of a log file. (i.e Checking for empty lines, missing timestamps and ensuring all timestamps in the file are within range of the start and end dates provided in the event configuration.)"""
def _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileValidator:
"""The FileValidator class is responsible for performing the validation operation of a log file. (i.e Checking for empty lines, missing timestamps and ensuring all timestamps in the file are within range of the start and end dates provided in the event configuration.)"""
def __init__(self,... | the_stack_v2_python_sparse | configurations/file_handler.py | CS4311-spring-2020/pick-tool-team12-feathersoft | train | 0 |
18bfc8b192f6ec564224c5a719f370957497d070 | [
"article = check_article.retrieve_article(slug)\ntry:\n highlight = Highlight.objects.get(article_id=article.id, id=highlight_id)\n return highlight\nexcept Highlight.DoesNotExist:\n raise HighlightNotFound",
"highlight = self.retrieve_highlight(slug, highlight_id)\nif request.user.id == highlight.user_i... | <|body_start_0|>
article = check_article.retrieve_article(slug)
try:
highlight = Highlight.objects.get(article_id=article.id, id=highlight_id)
return highlight
except Highlight.DoesNotExist:
raise HighlightNotFound
<|end_body_0|>
<|body_start_1|>
high... | RetrieveUpdateHighlightAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetrieveUpdateHighlightAPIView:
def retrieve_highlight(self, slug, highlight_id):
"""Retrieve highlight"""
<|body_0|>
def delete(self, request, slug, highlight_id):
"""Remove a text highlight and comment"""
<|body_1|>
def patch(self, request, slug, highl... | stack_v2_sparse_classes_36k_train_014275 | 4,382 | permissive | [
{
"docstring": "Retrieve highlight",
"name": "retrieve_highlight",
"signature": "def retrieve_highlight(self, slug, highlight_id)"
},
{
"docstring": "Remove a text highlight and comment",
"name": "delete",
"signature": "def delete(self, request, slug, highlight_id)"
},
{
"docstri... | 3 | stack_v2_sparse_classes_30k_train_001903 | Implement the Python class `RetrieveUpdateHighlightAPIView` described below.
Class description:
Implement the RetrieveUpdateHighlightAPIView class.
Method signatures and docstrings:
- def retrieve_highlight(self, slug, highlight_id): Retrieve highlight
- def delete(self, request, slug, highlight_id): Remove a text hi... | Implement the Python class `RetrieveUpdateHighlightAPIView` described below.
Class description:
Implement the RetrieveUpdateHighlightAPIView class.
Method signatures and docstrings:
- def retrieve_highlight(self, slug, highlight_id): Retrieve highlight
- def delete(self, request, slug, highlight_id): Remove a text hi... | d0f73bf166ad41f243cff6d82caced2f9facf2f9 | <|skeleton|>
class RetrieveUpdateHighlightAPIView:
def retrieve_highlight(self, slug, highlight_id):
"""Retrieve highlight"""
<|body_0|>
def delete(self, request, slug, highlight_id):
"""Remove a text highlight and comment"""
<|body_1|>
def patch(self, request, slug, highl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RetrieveUpdateHighlightAPIView:
def retrieve_highlight(self, slug, highlight_id):
"""Retrieve highlight"""
article = check_article.retrieve_article(slug)
try:
highlight = Highlight.objects.get(article_id=article.id, id=highlight_id)
return highlight
exce... | the_stack_v2_python_sparse | authors/apps/highlights/views.py | andela/ah-the-immortals-backend | train | 3 | |
74563a465b1f898f74de2646b95669f63f3f05d0 | [
"self._config_address = '0x0000000000000000000000000000000000001000'\nself.gasPrice = 300000000\nself.client = transaction_common.TransactionCommon(self._config_address, contract_path, 'SystemConfig')",
"fn_name = 'setValueByKey'\nfn_args = [key, value]\nreturn self.client.send_transaction_getReceipt(fn_name, fn_... | <|body_start_0|>
self._config_address = '0x0000000000000000000000000000000000001000'
self.gasPrice = 300000000
self.client = transaction_common.TransactionCommon(self._config_address, contract_path, 'SystemConfig')
<|end_body_0|>
<|body_start_1|>
fn_name = 'setValueByKey'
fn_arg... | implementation of ConfigPrecompile | ConfigPrecompile | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigPrecompile:
"""implementation of ConfigPrecompile"""
def __init__(self, contract_path):
"""init the address for SystemConfig contract"""
<|body_0|>
def setValueByKey(self, key, value):
"""set value for the givn key"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_014276 | 1,461 | permissive | [
{
"docstring": "init the address for SystemConfig contract",
"name": "__init__",
"signature": "def __init__(self, contract_path)"
},
{
"docstring": "set value for the givn key",
"name": "setValueByKey",
"signature": "def setValueByKey(self, key, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021587 | Implement the Python class `ConfigPrecompile` described below.
Class description:
implementation of ConfigPrecompile
Method signatures and docstrings:
- def __init__(self, contract_path): init the address for SystemConfig contract
- def setValueByKey(self, key, value): set value for the givn key | Implement the Python class `ConfigPrecompile` described below.
Class description:
implementation of ConfigPrecompile
Method signatures and docstrings:
- def __init__(self, contract_path): init the address for SystemConfig contract
- def setValueByKey(self, key, value): set value for the givn key
<|skeleton|>
class C... | 5fa6cc416b604de4bbd0d2407f36ed286d67a792 | <|skeleton|>
class ConfigPrecompile:
"""implementation of ConfigPrecompile"""
def __init__(self, contract_path):
"""init the address for SystemConfig contract"""
<|body_0|>
def setValueByKey(self, key, value):
"""set value for the givn key"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigPrecompile:
"""implementation of ConfigPrecompile"""
def __init__(self, contract_path):
"""init the address for SystemConfig contract"""
self._config_address = '0x0000000000000000000000000000000000001000'
self.gasPrice = 300000000
self.client = transaction_common.Tra... | the_stack_v2_python_sparse | client/precompile/config/config_precompile.py | FISCO-BCOS/python-sdk | train | 68 |
21bc04b65f9d76d593083e051f39dbbafd8eefee | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | AgentProfileServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgentProfileServiceServicer:
"""Missing associated documentation comment in .proto file."""
def createAgent(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def updateAgent(self, request, context):
"""Missing asso... | stack_v2_sparse_classes_36k_train_014277 | 8,348 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "createAgent",
"signature": "def createAgent(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "updateAgent",
"signature": "def updateAgent(self... | 4 | stack_v2_sparse_classes_30k_train_020252 | Implement the Python class `AgentProfileServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def createAgent(self, request, context): Missing associated documentation comment in .proto file.
- def updateAgent(self, request, c... | Implement the Python class `AgentProfileServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def createAgent(self, request, context): Missing associated documentation comment in .proto file.
- def updateAgent(self, request, c... | dc1ea0b58f92429ec8e7b54a8f23525abe024ba9 | <|skeleton|>
class AgentProfileServiceServicer:
"""Missing associated documentation comment in .proto file."""
def createAgent(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def updateAgent(self, request, context):
"""Missing asso... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgentProfileServiceServicer:
"""Missing associated documentation comment in .proto file."""
def createAgent(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not imple... | the_stack_v2_python_sparse | custos-client-sdks/custos-python-sdk/build/lib/custos/server/core/AgentProfileService_pb2_grpc.py | apache/airavata-custos | train | 12 |
f44c285d42145ed96d9e0dcae14423bc9db48a39 | [
"base_pkgs = FL_PACKAGES\nmodule_names = FL_MODULES\nadmin_config_file_path = workspace.get_admin_startup_file_path()\nJsonConfigurator.__init__(self, config_file_name=admin_config_file_path, base_pkgs=base_pkgs, module_names=module_names, exclude_libs=True)\nself.workspace = workspace\nself.admin_config_file_path ... | <|body_start_0|>
base_pkgs = FL_PACKAGES
module_names = FL_MODULES
admin_config_file_path = workspace.get_admin_startup_file_path()
JsonConfigurator.__init__(self, config_file_name=admin_config_file_path, base_pkgs=base_pkgs, module_names=module_names, exclude_libs=True)
self.wor... | FL Admin Client startup configurator. | FLAdminClientStarterConfigurator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FLAdminClientStarterConfigurator:
"""FL Admin Client startup configurator."""
def __init__(self, workspace: Workspace):
"""Uses the json configuration to start the FL admin client. Args: workspace: the workspace object"""
<|body_0|>
def process_config_element(self, confi... | stack_v2_sparse_classes_36k_train_014278 | 3,107 | permissive | [
{
"docstring": "Uses the json configuration to start the FL admin client. Args: workspace: the workspace object",
"name": "__init__",
"signature": "def __init__(self, workspace: Workspace)"
},
{
"docstring": "Process config element. Args: config_ctx: config context node: element node",
"name... | 3 | null | Implement the Python class `FLAdminClientStarterConfigurator` described below.
Class description:
FL Admin Client startup configurator.
Method signatures and docstrings:
- def __init__(self, workspace: Workspace): Uses the json configuration to start the FL admin client. Args: workspace: the workspace object
- def pr... | Implement the Python class `FLAdminClientStarterConfigurator` described below.
Class description:
FL Admin Client startup configurator.
Method signatures and docstrings:
- def __init__(self, workspace: Workspace): Uses the json configuration to start the FL admin client. Args: workspace: the workspace object
- def pr... | 1433290c203bd23f34c29e11795ce592bc067888 | <|skeleton|>
class FLAdminClientStarterConfigurator:
"""FL Admin Client startup configurator."""
def __init__(self, workspace: Workspace):
"""Uses the json configuration to start the FL admin client. Args: workspace: the workspace object"""
<|body_0|>
def process_config_element(self, confi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FLAdminClientStarterConfigurator:
"""FL Admin Client startup configurator."""
def __init__(self, workspace: Workspace):
"""Uses the json configuration to start the FL admin client. Args: workspace: the workspace object"""
base_pkgs = FL_PACKAGES
module_names = FL_MODULES
a... | the_stack_v2_python_sparse | nvflare/fuel/flare_api/config.py | NVIDIA/NVFlare | train | 442 |
3ba414594832e062302928f5953d3210be13293c | [
"m = {}\nfor i in tasks:\n if i not in m:\n m[i] = [0, 0]\n m[i][1] += 1\nlength = 0\nkeys = [i[0] for i in sorted(m.items(), key=lambda x: x[1][1], reverse=True)]\nresults = []\nwhile keys:\n for k in list(keys):\n if m[k][1] > 0 and length >= m[k][0]:\n m[k][1] -= 1\n ... | <|body_start_0|>
m = {}
for i in tasks:
if i not in m:
m[i] = [0, 0]
m[i][1] += 1
length = 0
keys = [i[0] for i in sorted(m.items(), key=lambda x: x[1][1], reverse=True)]
results = []
while keys:
for k in list(keys):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def leastInterval_wrong(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_0|>
def leastInterval_wrong2(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_014279 | 2,163 | no_license | [
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int",
"name": "leastInterval_wrong",
"signature": "def leastInterval_wrong(self, tasks, n)"
},
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int",
"name": "leastInterval_wrong2",
"signature": "def leastInterval_wro... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval_wrong(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def leastInterval_wrong2(self, tasks, n): :type tasks: List[str] :type n: int :rtype: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval_wrong(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def leastInterval_wrong2(self, tasks, n): :type tasks: List[str] :type n: int :rtype: i... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def leastInterval_wrong(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_0|>
def leastInterval_wrong2(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def leastInterval_wrong(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
m = {}
for i in tasks:
if i not in m:
m[i] = [0, 0]
m[i][1] += 1
length = 0
keys = [i[0] for i in sorted(m.items(), key=lambd... | the_stack_v2_python_sparse | task-scheduler/solution.py | uxlsl/leetcode_practice | train | 0 | |
a7a892f59b0888cf109fbf945d3284dd6b3e5466 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ConditionalAccessRoot()",
"from .authentication_context_class_reference import AuthenticationContextClassReference\nfrom .authentication_strength_root import AuthenticationStrengthRoot\nfrom .conditional_access_policy import Conditiona... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ConditionalAccessRoot()
<|end_body_0|>
<|body_start_1|>
from .authentication_context_class_reference import AuthenticationContextClassReference
from .authentication_strength_root import ... | ConditionalAccessRoot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionalAccessRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessRoot:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | stack_v2_sparse_classes_36k_train_014280 | 4,813 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ConditionalAccessRoot",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | null | Implement the Python class `ConditionalAccessRoot` described below.
Class description:
Implement the ConditionalAccessRoot class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessRoot: Creates a new instance of the appropriate class base... | Implement the Python class `ConditionalAccessRoot` described below.
Class description:
Implement the ConditionalAccessRoot class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessRoot: Creates a new instance of the appropriate class base... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ConditionalAccessRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessRoot:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionalAccessRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessRoot:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | the_stack_v2_python_sparse | msgraph/generated/models/conditional_access_root.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3cac6faab86ac028c607954858d0807cba960036 | [
"shadow = self.ETP - self.slant_x / self.slant_x.dot(self.ETP)\nshadow_prime = shadow - shadow.dot(self.normal_vector) / self.slant_z.dot(self.normal_vector) * self.slant_z\ntheta_shadow = numpy.rad2deg(numpy.arctan2(self.row_vector.dot(shadow_prime), self.col_vector.dot(shadow_prime)))\nif theta_shadow < 0:\n t... | <|body_start_0|>
shadow = self.ETP - self.slant_x / self.slant_x.dot(self.ETP)
shadow_prime = shadow - shadow.dot(self.normal_vector) / self.slant_z.dot(self.normal_vector) * self.slant_z
theta_shadow = numpy.rad2deg(numpy.arctan2(self.row_vector.dot(shadow_prime), self.col_vector.dot(shadow_pri... | ExploitationCalculator | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExploitationCalculator:
def Shadow(self):
"""AngleMagnitudeType: The shadow angle and magnitude."""
<|body_0|>
def Layover(self):
"""AngleMagnitudeType: The layover angle and magnitude."""
<|body_1|>
def North(self):
"""Describes the clockwise an... | stack_v2_sparse_classes_36k_train_014281 | 30,331 | permissive | [
{
"docstring": "AngleMagnitudeType: The shadow angle and magnitude.",
"name": "Shadow",
"signature": "def Shadow(self)"
},
{
"docstring": "AngleMagnitudeType: The layover angle and magnitude.",
"name": "Layover",
"signature": "def Layover(self)"
},
{
"docstring": "Describes the c... | 5 | null | Implement the Python class `ExploitationCalculator` described below.
Class description:
Implement the ExploitationCalculator class.
Method signatures and docstrings:
- def Shadow(self): AngleMagnitudeType: The shadow angle and magnitude.
- def Layover(self): AngleMagnitudeType: The layover angle and magnitude.
- def ... | Implement the Python class `ExploitationCalculator` described below.
Class description:
Implement the ExploitationCalculator class.
Method signatures and docstrings:
- def Shadow(self): AngleMagnitudeType: The shadow angle and magnitude.
- def Layover(self): AngleMagnitudeType: The layover angle and magnitude.
- def ... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class ExploitationCalculator:
def Shadow(self):
"""AngleMagnitudeType: The shadow angle and magnitude."""
<|body_0|>
def Layover(self):
"""AngleMagnitudeType: The layover angle and magnitude."""
<|body_1|>
def North(self):
"""Describes the clockwise an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExploitationCalculator:
def Shadow(self):
"""AngleMagnitudeType: The shadow angle and magnitude."""
shadow = self.ETP - self.slant_x / self.slant_x.dot(self.ETP)
shadow_prime = shadow - shadow.dot(self.normal_vector) / self.slant_z.dot(self.normal_vector) * self.slant_z
theta_s... | the_stack_v2_python_sparse | sarpy/io/product/sidd3_elements/ExploitationFeatures.py | ngageoint/sarpy | train | 192 | |
3d0f4bce562e72b74a2f4b34a8eb60b87a42f8ca | [
"f = zipfile.ZipFile(zip_file_path, 'r')\nfor file_temp in f.namelist():\n f.extract(file_temp, save_folder)",
"if folder_name:\n arcname_list = list(map(lambda x: os.path.join(folder_name, os.path.split(x)[1]), file_list))\nelse:\n arcname_list = list(map(lambda x: os.path.split(x)[1], file_list))\nwith... | <|body_start_0|>
f = zipfile.ZipFile(zip_file_path, 'r')
for file_temp in f.namelist():
f.extract(file_temp, save_folder)
<|end_body_0|>
<|body_start_1|>
if folder_name:
arcname_list = list(map(lambda x: os.path.join(folder_name, os.path.split(x)[1]), file_list))
... | ZipUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZipUtil:
def unzip_file(zip_file_path, save_folder):
"""将压缩文件解压 ,存放到对应的文件夹中去"""
<|body_0|>
def zip_files(file_list, save_path, folder_name=None):
"""压缩文件"""
<|body_1|>
def zip_folder(folder_path, save_zip_path, folder_name=None):
"""压缩文件夹"""
... | stack_v2_sparse_classes_36k_train_014282 | 2,107 | no_license | [
{
"docstring": "将压缩文件解压 ,存放到对应的文件夹中去",
"name": "unzip_file",
"signature": "def unzip_file(zip_file_path, save_folder)"
},
{
"docstring": "压缩文件",
"name": "zip_files",
"signature": "def zip_files(file_list, save_path, folder_name=None)"
},
{
"docstring": "压缩文件夹",
"name": "zip_f... | 3 | null | Implement the Python class `ZipUtil` described below.
Class description:
Implement the ZipUtil class.
Method signatures and docstrings:
- def unzip_file(zip_file_path, save_folder): 将压缩文件解压 ,存放到对应的文件夹中去
- def zip_files(file_list, save_path, folder_name=None): 压缩文件
- def zip_folder(folder_path, save_zip_path, folder_n... | Implement the Python class `ZipUtil` described below.
Class description:
Implement the ZipUtil class.
Method signatures and docstrings:
- def unzip_file(zip_file_path, save_folder): 将压缩文件解压 ,存放到对应的文件夹中去
- def zip_files(file_list, save_path, folder_name=None): 压缩文件
- def zip_folder(folder_path, save_zip_path, folder_n... | 32e64be10a6cd2856850f6720d70b4c6e7033f4e | <|skeleton|>
class ZipUtil:
def unzip_file(zip_file_path, save_folder):
"""将压缩文件解压 ,存放到对应的文件夹中去"""
<|body_0|>
def zip_files(file_list, save_path, folder_name=None):
"""压缩文件"""
<|body_1|>
def zip_folder(folder_path, save_zip_path, folder_name=None):
"""压缩文件夹"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZipUtil:
def unzip_file(zip_file_path, save_folder):
"""将压缩文件解压 ,存放到对应的文件夹中去"""
f = zipfile.ZipFile(zip_file_path, 'r')
for file_temp in f.namelist():
f.extract(file_temp, save_folder)
def zip_files(file_list, save_path, folder_name=None):
"""压缩文件"""
if... | the_stack_v2_python_sparse | Report/ZipUtil.py | newjokker/PyUtil | train | 0 | |
e92244f4b6c0999a9b853a86bc112e9af175cda2 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BookingCustomer()",
"from .booking_customer_base import BookingCustomerBase\nfrom .phone import Phone\nfrom .physical_address import PhysicalAddress\nfrom .booking_customer_base import BookingCustomerBase\nfrom .phone import Phone\nfro... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return BookingCustomer()
<|end_body_0|>
<|body_start_1|>
from .booking_customer_base import BookingCustomerBase
from .phone import Phone
from .physical_address import PhysicalAddress
... | Represents a customer of the business. | BookingCustomer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookingCustomer:
"""Represents a customer of the business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomer:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read ... | stack_v2_sparse_classes_36k_train_014283 | 3,391 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: BookingCustomer",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | stack_v2_sparse_classes_30k_train_012882 | Implement the Python class `BookingCustomer` described below.
Class description:
Represents a customer of the business.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomer: Creates a new instance of the appropriate class based on discriminat... | Implement the Python class `BookingCustomer` described below.
Class description:
Represents a customer of the business.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomer: Creates a new instance of the appropriate class based on discriminat... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BookingCustomer:
"""Represents a customer of the business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomer:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookingCustomer:
"""Represents a customer of the business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomer:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discrimin... | the_stack_v2_python_sparse | msgraph/generated/models/booking_customer.py | microsoftgraph/msgraph-sdk-python | train | 135 |
547af18a86944a84f0478d1bebeaa4ae8b472a7f | [
"try:\n data = {'first_name': user_data['given_name'], 'last_name': user_data['family_name'], 'email': user_data['email'], 'photo_url': user_data['picture']}\nexcept KeyError:\n raise PermissionException\nreturn data",
"try:\n user_data = id_token.verify_oauth2_token(token, requests.Request())\nexcept Ex... | <|body_start_0|>
try:
data = {'first_name': user_data['given_name'], 'last_name': user_data['family_name'], 'email': user_data['email'], 'photo_url': user_data['picture']}
except KeyError:
raise PermissionException
return data
<|end_body_0|>
<|body_start_1|>
try:... | Google backend. | GoogleBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleBackend:
"""Google backend."""
def _normalize_user_data(user_data: dict) -> dict:
"""Normalize user data. :param user_data: User data from google :return: normalized user data."""
<|body_0|>
def get_user_data(self, token: str) -> dict:
"""Get user data from... | stack_v2_sparse_classes_36k_train_014284 | 1,627 | no_license | [
{
"docstring": "Normalize user data. :param user_data: User data from google :return: normalized user data.",
"name": "_normalize_user_data",
"signature": "def _normalize_user_data(user_data: dict) -> dict"
},
{
"docstring": "Get user data from Google. :param token: access token :return: User da... | 2 | null | Implement the Python class `GoogleBackend` described below.
Class description:
Google backend.
Method signatures and docstrings:
- def _normalize_user_data(user_data: dict) -> dict: Normalize user data. :param user_data: User data from google :return: normalized user data.
- def get_user_data(self, token: str) -> dic... | Implement the Python class `GoogleBackend` described below.
Class description:
Google backend.
Method signatures and docstrings:
- def _normalize_user_data(user_data: dict) -> dict: Normalize user data. :param user_data: User data from google :return: normalized user data.
- def get_user_data(self, token: str) -> dic... | 713b9d84ac70d964d46f189ab1f9c7b944b9684b | <|skeleton|>
class GoogleBackend:
"""Google backend."""
def _normalize_user_data(user_data: dict) -> dict:
"""Normalize user data. :param user_data: User data from google :return: normalized user data."""
<|body_0|>
def get_user_data(self, token: str) -> dict:
"""Get user data from... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoogleBackend:
"""Google backend."""
def _normalize_user_data(user_data: dict) -> dict:
"""Normalize user data. :param user_data: User data from google :return: normalized user data."""
try:
data = {'first_name': user_data['given_name'], 'last_name': user_data['family_name'], ... | the_stack_v2_python_sparse | jobadvisor/authentication/backends/google.py | ewgen19892/jobadvisor | train | 0 |
3d94915dffecf863595bc80d4a400bbef49f71bd | [
"self.check_permission()\nself.check_addable_types()\nif self.is_application_pkcs7_mime(message):\n filename = 'message.p7m'\nelse:\n filename = 'message.eml'\ncommand = CreateEmailCommand(self.context, filename, message, message_source=MESSAGE_SOURCE_MAILIN)\nobj = command.execute()\ninitialize_custompropert... | <|body_start_0|>
self.check_permission()
self.check_addable_types()
if self.is_application_pkcs7_mime(message):
filename = 'message.p7m'
else:
filename = 'message.eml'
command = CreateEmailCommand(self.context, filename, message, message_source=MESSAGE_SOU... | This adapter is called form ftw.mail when creating mailed-in mails. We override it and create mail with `CreateEmailCommand` to make sure that creating content programmatically always uses the same code-path. | OGCreateMailInContainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OGCreateMailInContainer:
"""This adapter is called form ftw.mail when creating mailed-in mails. We override it and create mail with `CreateEmailCommand` to make sure that creating content programmatically always uses the same code-path."""
def create_mail(self, message):
"""Use `Crea... | stack_v2_sparse_classes_36k_train_014285 | 1,800 | no_license | [
{
"docstring": "Use `CreateEmailCommand` to create the mailed-in mail.",
"name": "create_mail",
"signature": "def create_mail(self, message)"
},
{
"docstring": "Return if message is of application/pkcs7-mime media type. As specified by https://tools.ietf.org/html/rfc8551#section-3.5.3.2.",
"... | 2 | stack_v2_sparse_classes_30k_train_001079 | Implement the Python class `OGCreateMailInContainer` described below.
Class description:
This adapter is called form ftw.mail when creating mailed-in mails. We override it and create mail with `CreateEmailCommand` to make sure that creating content programmatically always uses the same code-path.
Method signatures an... | Implement the Python class `OGCreateMailInContainer` described below.
Class description:
This adapter is called form ftw.mail when creating mailed-in mails. We override it and create mail with `CreateEmailCommand` to make sure that creating content programmatically always uses the same code-path.
Method signatures an... | a01bec6c00d203c21a1b0449f8d489d0033c02b7 | <|skeleton|>
class OGCreateMailInContainer:
"""This adapter is called form ftw.mail when creating mailed-in mails. We override it and create mail with `CreateEmailCommand` to make sure that creating content programmatically always uses the same code-path."""
def create_mail(self, message):
"""Use `Crea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OGCreateMailInContainer:
"""This adapter is called form ftw.mail when creating mailed-in mails. We override it and create mail with `CreateEmailCommand` to make sure that creating content programmatically always uses the same code-path."""
def create_mail(self, message):
"""Use `CreateEmailComman... | the_stack_v2_python_sparse | opengever/mail/create.py | 4teamwork/opengever.core | train | 19 |
b4b97d6eaf87af24d89ed0d8a7f44410356d768c | [
"self.screen = screen\nself.pause_start = 0\nself.window_rect = pg.Rect(int(WIDTH * 0.375), int(HEIGHT * 0.2), int(WIDTH * 0.25), int(HEIGHT * 0.5))\nself.window_image = load_img(PAUSE_WINDOW)\nself.window_image = pg.transform.scale(self.window_image, self.window_rect.size)\nbtn_height = 80\nbtn_offset_x = 20\nbtn_... | <|body_start_0|>
self.screen = screen
self.pause_start = 0
self.window_rect = pg.Rect(int(WIDTH * 0.375), int(HEIGHT * 0.2), int(WIDTH * 0.25), int(HEIGHT * 0.5))
self.window_image = load_img(PAUSE_WINDOW)
self.window_image = pg.transform.scale(self.window_image, self.window_rect... | GameView hold the information about all things related to the main game. | GameView | [
"CC0-1.0",
"CC-BY-4.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameView:
"""GameView hold the information about all things related to the main game."""
def __init__(self, screen: pg.Surface, difficulty: int=1):
"""Initializer for GameView class. screen - parent screen to draw objects on difficulty - 0, 1, 2. Difficulty increases with number."""
... | stack_v2_sparse_classes_36k_train_014286 | 4,902 | permissive | [
{
"docstring": "Initializer for GameView class. screen - parent screen to draw objects on difficulty - 0, 1, 2. Difficulty increases with number.",
"name": "__init__",
"signature": "def __init__(self, screen: pg.Surface, difficulty: int=1)"
},
{
"docstring": "Update period and handle pauses.",
... | 5 | null | Implement the Python class `GameView` described below.
Class description:
GameView hold the information about all things related to the main game.
Method signatures and docstrings:
- def __init__(self, screen: pg.Surface, difficulty: int=1): Initializer for GameView class. screen - parent screen to draw objects on di... | Implement the Python class `GameView` described below.
Class description:
GameView hold the information about all things related to the main game.
Method signatures and docstrings:
- def __init__(self, screen: pg.Surface, difficulty: int=1): Initializer for GameView class. screen - parent screen to draw objects on di... | 3c2a1d1937aeed89bb891f5b6f93a6ce053af42a | <|skeleton|>
class GameView:
"""GameView hold the information about all things related to the main game."""
def __init__(self, screen: pg.Surface, difficulty: int=1):
"""Initializer for GameView class. screen - parent screen to draw objects on difficulty - 0, 1, 2. Difficulty increases with number."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameView:
"""GameView hold the information about all things related to the main game."""
def __init__(self, screen: pg.Surface, difficulty: int=1):
"""Initializer for GameView class. screen - parent screen to draw objects on difficulty - 0, 1, 2. Difficulty increases with number."""
self.... | the_stack_v2_python_sparse | various_vipers/project/gameplay/game_view.py | python-discord/code-jam-5 | train | 32 |
0ecb175a72f176bd965f3c4a5837253c7fc4ff50 | [
"loss = TestLoss(1, 1, 1)\noptimizer = BoltOn(TestOptimizer(), loss)\nn_classes = 2\ninput_dim = 5\nepsilon = 1\nbatch_size = 1\nn_samples = 10\nclf = _do_fit(n_samples, input_dim, n_classes, epsilon, generator, batch_size, reset_n_samples, optimizer, loss)\nself.assertEqual(hasattr(clf, 'layers'), True)",
"loss ... | <|body_start_0|>
loss = TestLoss(1, 1, 1)
optimizer = BoltOn(TestOptimizer(), loss)
n_classes = 2
input_dim = 5
epsilon = 1
batch_size = 1
n_samples = 10
clf = _do_fit(n_samples, input_dim, n_classes, epsilon, generator, batch_size, reset_n_samples, optimi... | Test cases for keras model fitting. | FitTests | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FitTests:
"""Test cases for keras model fitting."""
def test_fit(self, generator, reset_n_samples):
"""Tests fitting of BoltOnModel. Args: generator: True for generator test, False for iterator test. reset_n_samples: True to reset the n_samples to None, False does nothing"""
... | stack_v2_sparse_classes_36k_train_014287 | 16,102 | permissive | [
{
"docstring": "Tests fitting of BoltOnModel. Args: generator: True for generator test, False for iterator test. reset_n_samples: True to reset the n_samples to None, False does nothing",
"name": "test_fit",
"signature": "def test_fit(self, generator, reset_n_samples)"
},
{
"docstring": "Tests t... | 5 | null | Implement the Python class `FitTests` described below.
Class description:
Test cases for keras model fitting.
Method signatures and docstrings:
- def test_fit(self, generator, reset_n_samples): Tests fitting of BoltOnModel. Args: generator: True for generator test, False for iterator test. reset_n_samples: True to re... | Implement the Python class `FitTests` described below.
Class description:
Test cases for keras model fitting.
Method signatures and docstrings:
- def test_fit(self, generator, reset_n_samples): Tests fitting of BoltOnModel. Args: generator: True for generator test, False for iterator test. reset_n_samples: True to re... | c92610e37aa340932ed2d963813e0890035a22bc | <|skeleton|>
class FitTests:
"""Test cases for keras model fitting."""
def test_fit(self, generator, reset_n_samples):
"""Tests fitting of BoltOnModel. Args: generator: True for generator test, False for iterator test. reset_n_samples: True to reset the n_samples to None, False does nothing"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FitTests:
"""Test cases for keras model fitting."""
def test_fit(self, generator, reset_n_samples):
"""Tests fitting of BoltOnModel. Args: generator: True for generator test, False for iterator test. reset_n_samples: True to reset the n_samples to None, False does nothing"""
loss = TestLo... | the_stack_v2_python_sparse | tensorflow_privacy/privacy/bolt_on/models_test.py | tensorflow/privacy | train | 1,881 |
fe2885393f06eb34ac42d12bd2c85ea37e979fc3 | [
"sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ncert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, certificate)\nargs = [OpenSSL.crypto.FILETYPE_PEM, private_key]\nif passphrase is not None:\n args.append(str(passphrase))\ntry:\n pkey = OpenSSL.crypto.load_privatekey(*args)\nexcept... | <|body_start_0|>
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, certificate)
args = [OpenSSL.crypto.FILETYPE_PEM, private_key]
if passphrase is not None:
args.append(str(passphrase))
try:
... | A base service class intended to be subclassed. | BaseService | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseService:
"""A base service class intended to be subclassed."""
def _connect(self, certificate, private_key, passphrase=None):
"""Establishes an encrypted SSL socket connection to the service. After connecting the socket can be written to or read from."""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_014288 | 14,304 | permissive | [
{
"docstring": "Establishes an encrypted SSL socket connection to the service. After connecting the socket can be written to or read from.",
"name": "_connect",
"signature": "def _connect(self, certificate, private_key, passphrase=None)"
},
{
"docstring": "Closes the SSL socket connection.",
... | 2 | stack_v2_sparse_classes_30k_val_001176 | Implement the Python class `BaseService` described below.
Class description:
A base service class intended to be subclassed.
Method signatures and docstrings:
- def _connect(self, certificate, private_key, passphrase=None): Establishes an encrypted SSL socket connection to the service. After connecting the socket can... | Implement the Python class `BaseService` described below.
Class description:
A base service class intended to be subclassed.
Method signatures and docstrings:
- def _connect(self, certificate, private_key, passphrase=None): Establishes an encrypted SSL socket connection to the service. After connecting the socket can... | d48a7862eaa499672f27c192a3cf6f06e06f8117 | <|skeleton|>
class BaseService:
"""A base service class intended to be subclassed."""
def _connect(self, certificate, private_key, passphrase=None):
"""Establishes an encrypted SSL socket connection to the service. After connecting the socket can be written to or read from."""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseService:
"""A base service class intended to be subclassed."""
def _connect(self, certificate, private_key, passphrase=None):
"""Establishes an encrypted SSL socket connection to the service. After connecting the socket can be written to or read from."""
sock = socket.socket(socket.AF... | the_stack_v2_python_sparse | ios_notifications/models.py | doordash/django-ios-notifications | train | 2 |
34dd53fed70eaa1bc9a04607a2c91d2f145a4e6b | [
"if isinstance(key, int):\n return OptionNumber(key)\nif key not in OptionNumber._member_map_:\n extend_enum(OptionNumber, key, default)\nreturn OptionNumber[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nextend_enum(cls,... | <|body_start_0|>
if isinstance(key, int):
return OptionNumber(key)
if key not in OptionNumber._member_map_:
extend_enum(OptionNumber, key, default)
return OptionNumber[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
... | [OptionNumber] IP Option Numbers | OptionNumber | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionNumber:
"""[OptionNumber] IP Option Numbers"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_014289 | 2,969 | permissive | [
{
"docstring": "Backport support for original codes.",
"name": "get",
"signature": "def get(key, default=-1)"
},
{
"docstring": "Lookup function used when value is not found.",
"name": "_missing_",
"signature": "def _missing_(cls, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014742 | Implement the Python class `OptionNumber` described below.
Class description:
[OptionNumber] IP Option Numbers
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found. | Implement the Python class `OptionNumber` described below.
Class description:
[OptionNumber] IP Option Numbers
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found.
<|skeleton|>
class OptionNumber:... | 90cd07d67df28d5c5ab0585bc60f467a78d9db33 | <|skeleton|>
class OptionNumber:
"""[OptionNumber] IP Option Numbers"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptionNumber:
"""[OptionNumber] IP Option Numbers"""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return OptionNumber(key)
if key not in OptionNumber._member_map_:
extend_enum(OptionNumber, key, default)
... | the_stack_v2_python_sparse | pcapkit/const/ipv4/option_number.py | stjordanis/PyPCAPKit | train | 0 |
19491073df7989263280c95fef79a02710ed19df | [
"self.lei = lei\nself.entity = entity\nself.registration = registration\nself.extension = extension\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nlei = dictionary.get('Lei')\nentity = idfy_rest_client.models.lei_entity.LeiEntity.from_dictionary(dictionary.get('Ent... | <|body_start_0|>
self.lei = lei
self.entity = entity
self.registration = registration
self.extension = extension
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
lei = dictionary.get... | Implementation of the 'LeiRecord' model. TODO: type model description here. Attributes: lei (string): TODO: type description here. entity (LeiEntity): TODO: type description here. registration (LeiRegistration): TODO: type description here. extension (LeiExtension): TODO: type description here. | LeiRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeiRecord:
"""Implementation of the 'LeiRecord' model. TODO: type model description here. Attributes: lei (string): TODO: type description here. entity (LeiEntity): TODO: type description here. registration (LeiRegistration): TODO: type description here. extension (LeiExtension): TODO: type descr... | stack_v2_sparse_classes_36k_train_014290 | 2,958 | permissive | [
{
"docstring": "Constructor for the LeiRecord class",
"name": "__init__",
"signature": "def __init__(self, lei=None, entity=None, registration=None, extension=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A ... | 2 | stack_v2_sparse_classes_30k_train_013022 | Implement the Python class `LeiRecord` described below.
Class description:
Implementation of the 'LeiRecord' model. TODO: type model description here. Attributes: lei (string): TODO: type description here. entity (LeiEntity): TODO: type description here. registration (LeiRegistration): TODO: type description here. ext... | Implement the Python class `LeiRecord` described below.
Class description:
Implementation of the 'LeiRecord' model. TODO: type model description here. Attributes: lei (string): TODO: type description here. entity (LeiEntity): TODO: type description here. registration (LeiRegistration): TODO: type description here. ext... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class LeiRecord:
"""Implementation of the 'LeiRecord' model. TODO: type model description here. Attributes: lei (string): TODO: type description here. entity (LeiEntity): TODO: type description here. registration (LeiRegistration): TODO: type description here. extension (LeiExtension): TODO: type descr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LeiRecord:
"""Implementation of the 'LeiRecord' model. TODO: type model description here. Attributes: lei (string): TODO: type description here. entity (LeiEntity): TODO: type description here. registration (LeiRegistration): TODO: type description here. extension (LeiExtension): TODO: type description here."... | the_stack_v2_python_sparse | idfy_rest_client/models/lei_record.py | dealflowteam/Idfy | train | 0 |
b39ab5d569f8cafa772dd4f557213bc1879d4603 | [
"self._GoalFrameId = '/map'\nself._GoalsFilePath = filePath\nwith open(filePath, 'r') as file:\n goals = []\n while True:\n goal = self._ReadNextGoalSection(file)\n if goal is None:\n break\n goals.append(goal)\n file.readline()\nreturn (self._GoalFrameId, goals)",
"fo... | <|body_start_0|>
self._GoalFrameId = '/map'
self._GoalsFilePath = filePath
with open(filePath, 'r') as file:
goals = []
while True:
goal = self._ReadNextGoalSection(file)
if goal is None:
break
goals.appe... | Helper class for extracting goals from a text file that contains the output of the ros topic /move_base/goal: rostopic echo /move_base/goal > ./goals.txt Content looks like this: header: seq: 5 stamp: secs: 1327888889 nsecs: 905062316 frame_id: '' goal_id: stamp: secs: 0 nsecs: 0 id: '' goal: target_pose: header: seq: ... | RecordedGoalsParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecordedGoalsParser:
"""Helper class for extracting goals from a text file that contains the output of the ros topic /move_base/goal: rostopic echo /move_base/goal > ./goals.txt Content looks like this: header: seq: 5 stamp: secs: 1327888889 nsecs: 905062316 frame_id: '' goal_id: stamp: secs: 0 n... | stack_v2_sparse_classes_36k_train_014291 | 11,034 | permissive | [
{
"docstring": "Parses the specified file and returns the extracted frame id and the array of goal poses: (frame_id, [(x,y,theta)])",
"name": "Parse",
"signature": "def Parse(self, filePath)"
},
{
"docstring": "Reads a section of the file that needs to be structured like this: header: seq: 5 sta... | 3 | stack_v2_sparse_classes_30k_train_008884 | Implement the Python class `RecordedGoalsParser` described below.
Class description:
Helper class for extracting goals from a text file that contains the output of the ros topic /move_base/goal: rostopic echo /move_base/goal > ./goals.txt Content looks like this: header: seq: 5 stamp: secs: 1327888889 nsecs: 905062316... | Implement the Python class `RecordedGoalsParser` described below.
Class description:
Helper class for extracting goals from a text file that contains the output of the ros topic /move_base/goal: rostopic echo /move_base/goal > ./goals.txt Content looks like this: header: seq: 5 stamp: secs: 1327888889 nsecs: 905062316... | 48d9144293d1b604969ca1208fb813939e935ed9 | <|skeleton|>
class RecordedGoalsParser:
"""Helper class for extracting goals from a text file that contains the output of the ros topic /move_base/goal: rostopic echo /move_base/goal > ./goals.txt Content looks like this: header: seq: 5 stamp: secs: 1327888889 nsecs: 905062316 frame_id: '' goal_id: stamp: secs: 0 n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecordedGoalsParser:
"""Helper class for extracting goals from a text file that contains the output of the ros topic /move_base/goal: rostopic echo /move_base/goal > ./goals.txt Content looks like this: header: seq: 5 stamp: secs: 1327888889 nsecs: 905062316 frame_id: '' goal_id: stamp: secs: 0 nsecs: 0 id: '... | the_stack_v2_python_sparse | Chapter09/chefbot_code/chefbot_bringup/scripts/bkup_working/GoalsSequencer.py | PacktPublishing/ROS-Robotics-Projects | train | 149 |
e63c73168aaa374b1a71eef1806d7527d18cd09a | [
"self.intervaloInicial = sp.sympify(inicial)\nself.intervaloFinal = sp.sympify(final)\nself.error = sp.sympify(error)\nself.ec = ecuacion",
"x = sp.Symbol('x')\nec = str(ec)\nec = sp.sympify(ec)\nreturn ec.subs(x, n)",
"x = sp.Symbol('x')\nres = sp.solve(sp.sympify(self.ec), x)\ngrade = len(res)\nif grade % 2 =... | <|body_start_0|>
self.intervaloInicial = sp.sympify(inicial)
self.intervaloFinal = sp.sympify(final)
self.error = sp.sympify(error)
self.ec = ecuacion
<|end_body_0|>
<|body_start_1|>
x = sp.Symbol('x')
ec = str(ec)
ec = sp.sympify(ec)
return ec.subs(x, n)... | Biseccion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Biseccion:
def __init__(self, inicial=0, final=0, ecuacion='x**3 + x**2 + 10', error=0.001):
"""Constructor de la clase"""
<|body_0|>
def _f(self, n, ec):
"""f(x) a resolver"""
<|body_1|>
def intervalo(self):
"""Obtenemos el subintervalo en el qu... | stack_v2_sparse_classes_36k_train_014292 | 2,636 | no_license | [
{
"docstring": "Constructor de la clase",
"name": "__init__",
"signature": "def __init__(self, inicial=0, final=0, ecuacion='x**3 + x**2 + 10', error=0.001)"
},
{
"docstring": "f(x) a resolver",
"name": "_f",
"signature": "def _f(self, n, ec)"
},
{
"docstring": "Obtenemos el subi... | 4 | stack_v2_sparse_classes_30k_train_006381 | Implement the Python class `Biseccion` described below.
Class description:
Implement the Biseccion class.
Method signatures and docstrings:
- def __init__(self, inicial=0, final=0, ecuacion='x**3 + x**2 + 10', error=0.001): Constructor de la clase
- def _f(self, n, ec): f(x) a resolver
- def intervalo(self): Obtenemo... | Implement the Python class `Biseccion` described below.
Class description:
Implement the Biseccion class.
Method signatures and docstrings:
- def __init__(self, inicial=0, final=0, ecuacion='x**3 + x**2 + 10', error=0.001): Constructor de la clase
- def _f(self, n, ec): f(x) a resolver
- def intervalo(self): Obtenemo... | 0c363b8962dfde684e955c98eb492d1d2da203d8 | <|skeleton|>
class Biseccion:
def __init__(self, inicial=0, final=0, ecuacion='x**3 + x**2 + 10', error=0.001):
"""Constructor de la clase"""
<|body_0|>
def _f(self, n, ec):
"""f(x) a resolver"""
<|body_1|>
def intervalo(self):
"""Obtenemos el subintervalo en el qu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Biseccion:
def __init__(self, inicial=0, final=0, ecuacion='x**3 + x**2 + 10', error=0.001):
"""Constructor de la clase"""
self.intervaloInicial = sp.sympify(inicial)
self.intervaloFinal = sp.sympify(final)
self.error = sp.sympify(error)
self.ec = ecuacion
def _f(s... | the_stack_v2_python_sparse | Metodos numericos/Método de bisección/principal/MN/Biseccion.py | Portilloglez95/Lenguaje-c | train | 0 | |
fd67da1e95fbe7106e90a39d05ba8f4a82987c25 | [
"def dfs(root, res):\n if not root:\n res.append('#')\n return\n res.append(str(root.val))\n dfs(root.left, res)\n dfs(root.right, res)\nres = []\ndfs(root, res)\nwhile res and res[-1] == '#':\n res.pop()\nreturn '.'.join(res)",
"def helper(values):\n nonlocal index\n if index >... | <|body_start_0|>
def dfs(root, res):
if not root:
res.append('#')
return
res.append(str(root.val))
dfs(root.left, res)
dfs(root.right, res)
res = []
dfs(root, res)
while res and res[-1] == '#':
re... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(root, ... | stack_v2_sparse_classes_36k_train_014293 | 1,279 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_001187 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 0250c3764b6e68dfe339afe8ee047e16c45db4e0 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def dfs(root, res):
if not root:
res.append('#')
return
res.append(str(root.val))
dfs(root.left, res)
dfs(root.right, res)... | the_stack_v2_python_sparse | Python/LC449_SerializeAndDesrializeBST.py | wondershow/CodingTraining | train | 0 | |
61a4ee57be4727ef84cd7310f388a3debd1b5566 | [
"from .timeseriesdata import TimeSeriesData\ntry:\n data = TimeSeriesData.objects.filter(sensor=self).latest('ts')\nexcept TimeSeriesData.DoesNotExist:\n return {}\nreturn data",
"from .timeseriesdata import TimeSeriesData\nraw = TimeSeriesData.objects.filter(ts__gte=data_start, ts__lt=data_end, sensor=self... | <|body_start_0|>
from .timeseriesdata import TimeSeriesData
try:
data = TimeSeriesData.objects.filter(sensor=self).latest('ts')
except TimeSeriesData.DoesNotExist:
return {}
return data
<|end_body_0|>
<|body_start_1|>
from .timeseriesdata import TimeSerie... | A sensor associated with a device Attributes: device (Device): associated device resolution (float): how often this is sampled, in seconds sensor_type (SensorType): type of sensor | DeviceSensor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceSensor:
"""A sensor associated with a device Attributes: device (Device): associated device resolution (float): how often this is sampled, in seconds sensor_type (SensorType): type of sensor"""
def get_latest_ts_data(self):
"""Get latest ts data on this sensor for this device T... | stack_v2_sparse_classes_36k_train_014294 | 8,729 | permissive | [
{
"docstring": "Get latest ts data on this sensor for this device The latest_ts_data_optimised on AbstractDevice should be used instead of directly calling this",
"name": "get_latest_ts_data",
"signature": "def get_latest_ts_data(self)"
},
{
"docstring": "Implementation of aggregating data. See ... | 4 | stack_v2_sparse_classes_30k_train_019830 | Implement the Python class `DeviceSensor` described below.
Class description:
A sensor associated with a device Attributes: device (Device): associated device resolution (float): how often this is sampled, in seconds sensor_type (SensorType): type of sensor
Method signatures and docstrings:
- def get_latest_ts_data(s... | Implement the Python class `DeviceSensor` described below.
Class description:
A sensor associated with a device Attributes: device (Device): associated device resolution (float): how often this is sampled, in seconds sensor_type (SensorType): type of sensor
Method signatures and docstrings:
- def get_latest_ts_data(s... | 5c569f54f100e23d72e2ac4de795739ea461a431 | <|skeleton|>
class DeviceSensor:
"""A sensor associated with a device Attributes: device (Device): associated device resolution (float): how often this is sampled, in seconds sensor_type (SensorType): type of sensor"""
def get_latest_ts_data(self):
"""Get latest ts data on this sensor for this device T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeviceSensor:
"""A sensor associated with a device Attributes: device (Device): associated device resolution (float): how often this is sampled, in seconds sensor_type (SensorType): type of sensor"""
def get_latest_ts_data(self):
"""Get latest ts data on this sensor for this device The latest_ts_... | the_stack_v2_python_sparse | zconnect/zc_timeseries/_models/sensor.py | zconnect-iot/zconnect-django | train | 2 |
52c56be8c0934026a4f5c5321120e5fe513a8936 | [
"self.outvar = outvar\nself.invar = invar\nself.mask = mask\nself.scale = scale\nself.bias = bias\nself.sense = sense",
"biases = np.reshape(self.bias[index, ...], [-1])\nslopes = np.reshape(self.scale[index, ...], [-1])\nmask = np.reshape(self.mask[index, ...], [-1])\nfor act_index, (slope, bias) in enumerate(zi... | <|body_start_0|>
self.outvar = outvar
self.invar = invar
self.mask = mask
self.scale = scale
self.bias = bias
self.sense = sense
<|end_body_0|>
<|body_start_1|>
biases = np.reshape(self.bias[index, ...], [-1])
slopes = np.reshape(self.scale[index, ...], [... | Linear constraint involved in the relaxation of an activation. | RelaxActivationConstraint | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelaxActivationConstraint:
"""Linear constraint involved in the relaxation of an activation."""
def __init__(self, outvar, invar, mask, scale, bias, sense):
"""Represents the constraint outvar =(>)(<) scale * invar + bias."""
<|body_0|>
def encode_into_solver(self, solve... | stack_v2_sparse_classes_36k_train_014295 | 26,545 | permissive | [
{
"docstring": "Represents the constraint outvar =(>)(<) scale * invar + bias.",
"name": "__init__",
"signature": "def __init__(self, outvar, invar, mask, scale, bias, sense)"
},
{
"docstring": "Encode the linear constraints into the provided solver. Args: solver: RelaxationSolver to create the ... | 2 | stack_v2_sparse_classes_30k_train_002232 | Implement the Python class `RelaxActivationConstraint` described below.
Class description:
Linear constraint involved in the relaxation of an activation.
Method signatures and docstrings:
- def __init__(self, outvar, invar, mask, scale, bias, sense): Represents the constraint outvar =(>)(<) scale * invar + bias.
- de... | Implement the Python class `RelaxActivationConstraint` described below.
Class description:
Linear constraint involved in the relaxation of an activation.
Method signatures and docstrings:
- def __init__(self, outvar, invar, mask, scale, bias, sense): Represents the constraint outvar =(>)(<) scale * invar + bias.
- de... | 96e4abb160f5022af4bf1aa8bb854822eb45a59b | <|skeleton|>
class RelaxActivationConstraint:
"""Linear constraint involved in the relaxation of an activation."""
def __init__(self, outvar, invar, mask, scale, bias, sense):
"""Represents the constraint outvar =(>)(<) scale * invar + bias."""
<|body_0|>
def encode_into_solver(self, solve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelaxActivationConstraint:
"""Linear constraint involved in the relaxation of an activation."""
def __init__(self, outvar, invar, mask, scale, bias, sense):
"""Represents the constraint outvar =(>)(<) scale * invar + bias."""
self.outvar = outvar
self.invar = invar
self.ma... | the_stack_v2_python_sparse | jax_verify/src/mip_solver/relaxation.py | harmonicm/jax_verify | train | 0 |
02ef8b0f1bab3e11614fbff457b78f8738981b57 | [
"if not isinstance(data, dict):\n return cls()\ncreation_boot_id = None\nmaximum_size: MaximumSizeType = None\nversion = None\n_creation_boot_id = data.get('creation-boot-id')\nif isinstance(_creation_boot_id, str) and len(_creation_boot_id) == 32:\n creation_boot_id = _creation_boot_id\n_maximum_size = data.... | <|body_start_0|>
if not isinstance(data, dict):
return cls()
creation_boot_id = None
maximum_size: MaximumSizeType = None
version = None
_creation_boot_id = data.get('creation-boot-id')
if isinstance(_creation_boot_id, str) and len(_creation_boot_id) == 32:
... | File System Cache Information This type represents static cache information. It is an immutable named tuple and used to query or set the configuration of a cache. creation_boot_id - Hashed linux boot-id at the time of cache-creation maximum_size - Maximum cache size in bytes, or "unlimited" version - version of the cac... | FsCacheInfo | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FsCacheInfo:
"""File System Cache Information This type represents static cache information. It is an immutable named tuple and used to query or set the configuration of a cache. creation_boot_id - Hashed linux boot-id at the time of cache-creation maximum_size - Maximum cache size in bytes, or "... | stack_v2_sparse_classes_36k_train_014296 | 46,120 | permissive | [
{
"docstring": "Create tuple from parsed JSON This takes a parsed JSON value and converts it into a tuple with the same information. Unknown fields in the input are ignored. The input is usually taken from `json.load()` and similar.",
"name": "from_json",
"signature": "def from_json(cls, data: Any) -> '... | 2 | null | Implement the Python class `FsCacheInfo` described below.
Class description:
File System Cache Information This type represents static cache information. It is an immutable named tuple and used to query or set the configuration of a cache. creation_boot_id - Hashed linux boot-id at the time of cache-creation maximum_s... | Implement the Python class `FsCacheInfo` described below.
Class description:
File System Cache Information This type represents static cache information. It is an immutable named tuple and used to query or set the configuration of a cache. creation_boot_id - Hashed linux boot-id at the time of cache-creation maximum_s... | e7fb2e11174a9b69b1761a726989f7a9a9e2ce1c | <|skeleton|>
class FsCacheInfo:
"""File System Cache Information This type represents static cache information. It is an immutable named tuple and used to query or set the configuration of a cache. creation_boot_id - Hashed linux boot-id at the time of cache-creation maximum_size - Maximum cache size in bytes, or "... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FsCacheInfo:
"""File System Cache Information This type represents static cache information. It is an immutable named tuple and used to query or set the configuration of a cache. creation_boot_id - Hashed linux boot-id at the time of cache-creation maximum_size - Maximum cache size in bytes, or "unlimited" ve... | the_stack_v2_python_sparse | osbuild/util/fscache.py | osbuild/osbuild | train | 150 |
2f17b4c3e3db64f730dcbe33b8acac4249e39c7e | [
"hist, _ = np.histogram(y, bins=max(y[:, 0]) + 1)\nself.class_ids = np.where(n_shot + n_query <= hist)[0]\nself.x = x\nself.y = y\nself.shape_x = x.shape[1:]\nself.n_way = n_way\nself.n_shot = n_shot\nself.n_query = n_query\nself.s_x = np.zeros((n_way * n_shot,) + x[0].shape)\nself.q_x = np.zeros((n_way * n_query,)... | <|body_start_0|>
hist, _ = np.histogram(y, bins=max(y[:, 0]) + 1)
self.class_ids = np.where(n_shot + n_query <= hist)[0]
self.x = x
self.y = y
self.shape_x = x.shape[1:]
self.n_way = n_way
self.n_shot = n_shot
self.n_query = n_query
self.s_x = np.z... | EpisodeGenerator | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0",
"CC-BY-NC-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EpisodeGenerator:
def __init__(self, x, y, n_way, n_shot, n_query):
"""Initialization function for episode generator class Args: x (nd_array): nd_array of images (n_sample, image_shape) y (nd_array): nd_array of labels (n_sample, 1) n_way (int): number of support classes, generally calle... | stack_v2_sparse_classes_36k_train_014297 | 22,165 | permissive | [
{
"docstring": "Initialization function for episode generator class Args: x (nd_array): nd_array of images (n_sample, image_shape) y (nd_array): nd_array of labels (n_sample, 1) n_way (int): number of support classes, generally called n_way in one-shot litterateur n_shot (int): number of shots per class n_query... | 2 | null | Implement the Python class `EpisodeGenerator` described below.
Class description:
Implement the EpisodeGenerator class.
Method signatures and docstrings:
- def __init__(self, x, y, n_way, n_shot, n_query): Initialization function for episode generator class Args: x (nd_array): nd_array of images (n_sample, image_shap... | Implement the Python class `EpisodeGenerator` described below.
Class description:
Implement the EpisodeGenerator class.
Method signatures and docstrings:
- def __init__(self, x, y, n_way, n_shot, n_query): Initialization function for episode generator class Args: x (nd_array): nd_array of images (n_sample, image_shap... | 41f71faa6efff7774a76bbd5af3198322a90a6ab | <|skeleton|>
class EpisodeGenerator:
def __init__(self, x, y, n_way, n_shot, n_query):
"""Initialization function for episode generator class Args: x (nd_array): nd_array of images (n_sample, image_shape) y (nd_array): nd_array of labels (n_sample, 1) n_way (int): number of support classes, generally calle... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EpisodeGenerator:
def __init__(self, x, y, n_way, n_shot, n_query):
"""Initialization function for episode generator class Args: x (nd_array): nd_array of images (n_sample, image_shape) y (nd_array): nd_array of labels (n_sample, 1) n_way (int): number of support classes, generally called n_way in one... | the_stack_v2_python_sparse | meta-learning/prototypical/prototypical.py | sony/nnabla-examples | train | 308 | |
d87574e09b5d6209a73863ef4e1280e6ea6dd87c | [
"self.size = size\nself.sum = 0\nself.q = [0] * size\nself.index = 0",
"self.index += 1\nself.q.remove(self.q[0])\nself.q.append(val)\nself.sum = sum(self.q)\nreturn self.sum / min(self.size, self.index)"
] | <|body_start_0|>
self.size = size
self.sum = 0
self.q = [0] * size
self.index = 0
<|end_body_0|>
<|body_start_1|>
self.index += 1
self.q.remove(self.q[0])
self.q.append(val)
self.sum = sum(self.q)
return self.sum / min(self.size, self.index)
<|end... | MovingAverage3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage3:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.sum = ... | stack_v2_sparse_classes_36k_train_014298 | 2,826 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | null | Implement the Python class `MovingAverage3` described below.
Class description:
Implement the MovingAverage3 class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage3` described below.
Class description:
Implement the MovingAverage3 class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage3:... | 2ffe01713a12090848ed9b75457bf9ee156db84b | <|skeleton|>
class MovingAverage3:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage3:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.sum = 0
self.q = [0] * size
self.index = 0
def next(self, val):
""":type val: int :rtype: float"""
self.index += 1
sel... | the_stack_v2_python_sparse | array/Q346_movingAverage.py | liangming168/leetcode | train | 0 | |
c67c90ea579b7b8f36e6cd1f45af2939d6325125 | [
"if root is None:\n return '[]'\nqueue = [root]\nres = []\nwhile len(queue) != 0:\n current = queue[0]\n if isinstance(current, TreeNode):\n res.append(current.val)\n else:\n res.append(current)\n queue.pop(0)\n if current != None:\n queue.append(current.left)\n queue.a... | <|body_start_0|>
if root is None:
return '[]'
queue = [root]
res = []
while len(queue) != 0:
current = queue[0]
if isinstance(current, TreeNode):
res.append(current.val)
else:
res.append(current)
... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_014299 | 4,160 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 9adbe5fc2bce71f4c09ccf83079c44699c27fce4 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root is None:
return '[]'
queue = [root]
res = []
while len(queue) != 0:
current = queue[0]
if isinstance(current, TreeNode... | the_stack_v2_python_sparse | leetcode/binary_tree/297.py | 1lch2/PythonExercise | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.