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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2ac75cbc6d7097e85f26f959e246ab06126e52cc | [
"self._time = time\nself._interval_secs = interval_secs\nself._last_called_secs = 0",
"wait_secs = self._last_called_secs + self._interval_secs - self._time.time()\nif wait_secs > 0:\n self._time.sleep(wait_secs)\nself._last_called_secs = self._time.time()"
] | <|body_start_0|>
self._time = time
self._interval_secs = interval_secs
self._last_called_secs = 0
<|end_body_0|>
<|body_start_1|>
wait_secs = self._last_called_secs + self._interval_secs - self._time.time()
if wait_secs > 0:
self._time.sleep(wait_secs)
self._... | Helper class for rate-limiting using a fixed minimum interval. | RateLimiter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RateLimiter:
"""Helper class for rate-limiting using a fixed minimum interval."""
def __init__(self, interval_secs):
"""Constructs a RateLimiter that permits a tick() every `interval_secs`."""
<|body_0|>
def tick(self):
"""Blocks until it has been at least `inter... | stack_v2_sparse_classes_36k_train_003200 | 6,644 | permissive | [
{
"docstring": "Constructs a RateLimiter that permits a tick() every `interval_secs`.",
"name": "__init__",
"signature": "def __init__(self, interval_secs)"
},
{
"docstring": "Blocks until it has been at least `interval_secs` since last tick().",
"name": "tick",
"signature": "def tick(se... | 2 | null | Implement the Python class `RateLimiter` described below.
Class description:
Helper class for rate-limiting using a fixed minimum interval.
Method signatures and docstrings:
- def __init__(self, interval_secs): Constructs a RateLimiter that permits a tick() every `interval_secs`.
- def tick(self): Blocks until it has... | Implement the Python class `RateLimiter` described below.
Class description:
Helper class for rate-limiting using a fixed minimum interval.
Method signatures and docstrings:
- def __init__(self, interval_secs): Constructs a RateLimiter that permits a tick() every `interval_secs`.
- def tick(self): Blocks until it has... | 5961c76dca0fb9bb40d146f5ce13834ac29d8ddb | <|skeleton|>
class RateLimiter:
"""Helper class for rate-limiting using a fixed minimum interval."""
def __init__(self, interval_secs):
"""Constructs a RateLimiter that permits a tick() every `interval_secs`."""
<|body_0|>
def tick(self):
"""Blocks until it has been at least `inter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RateLimiter:
"""Helper class for rate-limiting using a fixed minimum interval."""
def __init__(self, interval_secs):
"""Constructs a RateLimiter that permits a tick() every `interval_secs`."""
self._time = time
self._interval_secs = interval_secs
self._last_called_secs = 0... | the_stack_v2_python_sparse | tensorboard/uploader/util.py | tensorflow/tensorboard | train | 6,766 |
cf0f1df8f532da2aefa06001d44d225cb74eaf3a | [
"region_spec = concepts.ResourceSpec('cloudbuild.projects.locations', resource_name='region', projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG, locationsId=resource_args.RegionAttributeConfig())\nconcept_parsers.ConceptParser.ForResource('--region', region_spec, 'Cloud region', required=True).AddToParser(parser... | <|body_start_0|>
region_spec = concepts.ResourceSpec('cloudbuild.projects.locations', resource_name='region', projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG, locationsId=resource_args.RegionAttributeConfig())
concept_parsers.ConceptParser.ForResource('--region', region_spec, 'Cloud region', requir... | Create a build trigger for a GCB v2 repository. | CreateRepository | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateRepository:
"""Create a build trigger for a GCB v2 repository."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
<|... | stack_v2_sparse_classes_36k_train_003201 | 7,136 | permissive | [
{
"docstring": "Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Parses command line arguments int... | 3 | stack_v2_sparse_classes_30k_train_004287 | Implement the Python class `CreateRepository` described below.
Class description:
Create a build trigger for a GCB v2 repository.
Method signatures and docstrings:
- def Args(parser): Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some infor... | Implement the Python class `CreateRepository` described below.
Class description:
Create a build trigger for a GCB v2 repository.
Method signatures and docstrings:
- def Args(parser): Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some infor... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class CreateRepository:
"""Create a build trigger for a GCB v2 repository."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateRepository:
"""Create a build trigger for a GCB v2 repository."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
region_spec = c... | the_stack_v2_python_sparse | lib/surface/builds/triggers/create/repository.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
71ce71839005959f906fa4da46af607b4be67f9e | [
"super(BinaryCrossEntropyLoss, self).__init__()\nself.weight = weight\nself.ignore_index = ignore_index\nself.reduction = reduction",
"targets = [t for target in targets for t in target['targets']]\ntargets = torch.stack(targets).float()\nlogits = torch.stack([torch.sum(cost * alignment) for cost, alignment in lo... | <|body_start_0|>
super(BinaryCrossEntropyLoss, self).__init__()
self.weight = weight
self.ignore_index = ignore_index
self.reduction = reduction
<|end_body_0|>
<|body_start_1|>
targets = [t for target in targets for t in target['targets']]
targets = torch.stack(targets).... | Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu). For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin| i.e. sum over all positive/negative pairs | BinaryCrossEntropyLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryCrossEntropyLoss:
"""Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu). For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin| i.e. sum over all positive/negative pairs"""
def __init__(self, weight: Optional[to... | stack_v2_sparse_classes_36k_train_003202 | 2,776 | permissive | [
{
"docstring": "Initialize the MultiLabelNLLLoss. Parameters ---------- weight : Optional[torch.Tensor] A manual rescaling weight given to each class. If given, has to be a Tensor of size N, where N is the number of classes. ignore_index : Optional[int], optional Specifies a target value that is ignored and doe... | 2 | stack_v2_sparse_classes_30k_train_002543 | Implement the Python class `BinaryCrossEntropyLoss` described below.
Class description:
Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu). For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin| i.e. sum over all positive/negative pairs
Method... | Implement the Python class `BinaryCrossEntropyLoss` described below.
Class description:
Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu). For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin| i.e. sum over all positive/negative pairs
Method... | 8d2bf06ba4c121863833094d5d4896bf34a9a73e | <|skeleton|>
class BinaryCrossEntropyLoss:
"""Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu). For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin| i.e. sum over all positive/negative pairs"""
def __init__(self, weight: Optional[to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinaryCrossEntropyLoss:
"""Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu). For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin| i.e. sum over all positive/negative pairs"""
def __init__(self, weight: Optional[torch.Tensor]=N... | the_stack_v2_python_sparse | classify/metric/loss/bce.py | ManHieu/rationale-alignment | train | 0 |
3c2ae1718db51e2625f9bb18367957de2df00787 | [
"assert len(latent_dims) == len(data_dims) + 1, 'Expected too receive {} private latent spaces and one shared for {} data inputs but got {} instead.'.format(len(data_dims) + 1, len(data_dims), len(latent_dims))\nname = 'Reparametrised Gaussian Conjoint Encoder'\nlogger.info('Initialising {} model with {}-dimensiona... | <|body_start_0|>
assert len(latent_dims) == len(data_dims) + 1, 'Expected too receive {} private latent spaces and one shared for {} data inputs but got {} instead.'.format(len(data_dims) + 1, len(data_dims), len(latent_dims))
name = 'Reparametrised Gaussian Conjoint Encoder'
logger.info('Initia... | A ReparametrisedGaussianConjointEncoder parametrises a Gaussian latent distribution given two (or more) datasets, by partially sharing the latent vector between two (or more) encoders: Data_1 Data_2 | | ------------- ------------- | Encoder_1 | | Encoder_2 | ------------- ------------- | | Latent_1 -- Latent_shared -- ... | ReparametrisedGaussianConjointEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReparametrisedGaussianConjointEncoder:
"""A ReparametrisedGaussianConjointEncoder parametrises a Gaussian latent distribution given two (or more) datasets, by partially sharing the latent vector between two (or more) encoders: Data_1 Data_2 | | ------------- ------------- | Encoder_1 | | Encoder_... | stack_v2_sparse_classes_36k_train_003203 | 23,104 | permissive | [
{
"docstring": "Args: data_dims: tuple, flattened data dimension for each dataset latent_dims: tuple, flattened latent dimensions for each private latent space and the dimension of the shared space. network_architecture: str, the codename of the encoder network architecture (will be the same for all)",
"nam... | 2 | stack_v2_sparse_classes_30k_train_013782 | Implement the Python class `ReparametrisedGaussianConjointEncoder` described below.
Class description:
A ReparametrisedGaussianConjointEncoder parametrises a Gaussian latent distribution given two (or more) datasets, by partially sharing the latent vector between two (or more) encoders: Data_1 Data_2 | | -------------... | Implement the Python class `ReparametrisedGaussianConjointEncoder` described below.
Class description:
A ReparametrisedGaussianConjointEncoder parametrises a Gaussian latent distribution given two (or more) datasets, by partially sharing the latent vector between two (or more) encoders: Data_1 Data_2 | | -------------... | 545e4993c90622f05b5b7ba0183bc07d5972371e | <|skeleton|>
class ReparametrisedGaussianConjointEncoder:
"""A ReparametrisedGaussianConjointEncoder parametrises a Gaussian latent distribution given two (or more) datasets, by partially sharing the latent vector between two (or more) encoders: Data_1 Data_2 | | ------------- ------------- | Encoder_1 | | Encoder_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReparametrisedGaussianConjointEncoder:
"""A ReparametrisedGaussianConjointEncoder parametrises a Gaussian latent distribution given two (or more) datasets, by partially sharing the latent vector between two (or more) encoders: Data_1 Data_2 | | ------------- ------------- | Encoder_1 | | Encoder_2 | ---------... | the_stack_v2_python_sparse | playground/models/networks/encoder.py | gdikov/vae-playground | train | 1 |
b0d0f363e29aad0a64be302d58f9e85cfcec7e2b | [
"SimpleDifficultyItemFormRecord._init_map(self)\nSourceItemFormRecord._init_map(self)\nPDFPreviewFormRecord._init_map(self)\nPublishedFormRecord._init_map(self)\nProvenanceFormRecord._init_map(self)\nsuper(MecQBankBaseMixin, self)._init_map()",
"SimpleDifficultyItemFormRecord._init_metadata(self)\nSourceItemFormR... | <|body_start_0|>
SimpleDifficultyItemFormRecord._init_map(self)
SourceItemFormRecord._init_map(self)
PDFPreviewFormRecord._init_map(self)
PublishedFormRecord._init_map(self)
ProvenanceFormRecord._init_map(self)
super(MecQBankBaseMixin, self)._init_map()
<|end_body_0|>
<|... | to make this cooperative with super() | MecQBankBaseMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MecQBankBaseMixin:
"""to make this cooperative with super()"""
def _init_map(self):
"""stub"""
<|body_0|>
def _init_metadata(self):
"""stub"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
SimpleDifficultyItemFormRecord._init_map(self)
So... | stack_v2_sparse_classes_36k_train_003204 | 15,792 | permissive | [
{
"docstring": "stub",
"name": "_init_map",
"signature": "def _init_map(self)"
},
{
"docstring": "stub",
"name": "_init_metadata",
"signature": "def _init_metadata(self)"
}
] | 2 | null | Implement the Python class `MecQBankBaseMixin` described below.
Class description:
to make this cooperative with super()
Method signatures and docstrings:
- def _init_map(self): stub
- def _init_metadata(self): stub | Implement the Python class `MecQBankBaseMixin` described below.
Class description:
to make this cooperative with super()
Method signatures and docstrings:
- def _init_map(self): stub
- def _init_metadata(self): stub
<|skeleton|>
class MecQBankBaseMixin:
"""to make this cooperative with super()"""
def _init_... | 445f968a175d61c8d92c0f617a3c17dc1dc7c584 | <|skeleton|>
class MecQBankBaseMixin:
"""to make this cooperative with super()"""
def _init_map(self):
"""stub"""
<|body_0|>
def _init_metadata(self):
"""stub"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MecQBankBaseMixin:
"""to make this cooperative with super()"""
def _init_map(self):
"""stub"""
SimpleDifficultyItemFormRecord._init_map(self)
SourceItemFormRecord._init_map(self)
PDFPreviewFormRecord._init_map(self)
PublishedFormRecord._init_map(self)
Prove... | the_stack_v2_python_sparse | dlkit/records/assessment/mecqbank/mecqbank_base_records.py | mitsei/dlkit | train | 2 |
a6a51bbc03f0eac56ac1767f12f96ed18ad8ff50 | [
"super(DownloadWorkerThread, self).__init__(worker_queue, result_queue)\nself._job = job\nself._num_retries = num_retries\nself._time_between_retries = time_between_retries\nself._retry_exceptions = retry_exceptions",
"result = None\nfor _ in range(self._num_retries):\n try:\n result = self._download_ch... | <|body_start_0|>
super(DownloadWorkerThread, self).__init__(worker_queue, result_queue)
self._job = job
self._num_retries = num_retries
self._time_between_retries = time_between_retries
self._retry_exceptions = retry_exceptions
<|end_body_0|>
<|body_start_1|>
result = No... | DownloadWorkerThread | [
"CC-BY-3.0",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"ZPL-2.0",
"Unlicense",
"LGPL-3.0-only",
"CC0-1.0",
"LicenseRef-scancode-other-permissive",
"CNRI-Python",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-or-later",
"Python-2.0",
"GPL-3.0... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownloadWorkerThread:
def __init__(self, job, worker_queue, result_queue, num_retries=5, time_between_retries=5, retry_exceptions=Exception):
"""Individual download thread that will download parts of the file from Glacier. Parts to download stored in work queue. Parts download to a temp ... | stack_v2_sparse_classes_36k_train_003205 | 17,241 | permissive | [
{
"docstring": "Individual download thread that will download parts of the file from Glacier. Parts to download stored in work queue. Parts download to a temp dir with each part a separate file :param job: Glacier job object :param work_queue: A queue of tuples which include the part_number and part_size :param... | 3 | stack_v2_sparse_classes_30k_train_021150 | Implement the Python class `DownloadWorkerThread` described below.
Class description:
Implement the DownloadWorkerThread class.
Method signatures and docstrings:
- def __init__(self, job, worker_queue, result_queue, num_retries=5, time_between_retries=5, retry_exceptions=Exception): Individual download thread that wi... | Implement the Python class `DownloadWorkerThread` described below.
Class description:
Implement the DownloadWorkerThread class.
Method signatures and docstrings:
- def __init__(self, job, worker_queue, result_queue, num_retries=5, time_between_retries=5, retry_exceptions=Exception): Individual download thread that wi... | dccb9467675c67b9c3399fc76c5de6d31bfb8255 | <|skeleton|>
class DownloadWorkerThread:
def __init__(self, job, worker_queue, result_queue, num_retries=5, time_between_retries=5, retry_exceptions=Exception):
"""Individual download thread that will download parts of the file from Glacier. Parts to download stored in work queue. Parts download to a temp ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DownloadWorkerThread:
def __init__(self, job, worker_queue, result_queue, num_retries=5, time_between_retries=5, retry_exceptions=Exception):
"""Individual download thread that will download parts of the file from Glacier. Parts to download stored in work queue. Parts download to a temp dir with each ... | the_stack_v2_python_sparse | desktop/core/ext-py3/boto-2.49.0/boto/glacier/concurrent.py | cloudera/hue | train | 5,655 | |
dfbbaf512e227a1294b7175591d6e7f421c44fd6 | [
"self.cleaned.barcode = room.barcode\nself.cleaned.title = room.title\nself.cleaned.x = room.x\nself.cleaned.y = room.y\nself.cleaned.z = room.z\nself.cleaned.description = room.description.text\nself.cleaned.exits = []\nfor exit in room.exits:\n definition = {}\n definition['name'] = exit.name_for(room)\n ... | <|body_start_0|>
self.cleaned.barcode = room.barcode
self.cleaned.title = room.title
self.cleaned.x = room.x
self.cleaned.y = room.y
self.cleaned.z = room.z
self.cleaned.description = room.description.text
self.cleaned.exits = []
for exit in room.exits:
... | Room document to add rooms in blueprints. | RoomDocument | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoomDocument:
"""Room document to add rooms in blueprints."""
def fill_from_object(self, room):
"""Draw the document from an object."""
<|body_0|>
def add_neighbor(self, barcode: str, title: str, x: Optional[int]=None, y: Optional[int]=None, z: Optional[int]=None, descri... | stack_v2_sparse_classes_36k_train_003206 | 8,190 | permissive | [
{
"docstring": "Draw the document from an object.",
"name": "fill_from_object",
"signature": "def fill_from_object(self, room)"
},
{
"docstring": "Add a room, optionally connected to the current room. Args: barcode (str): the new room's barcode. title (str): the new room's title. x (int, optiona... | 4 | stack_v2_sparse_classes_30k_test_000034 | Implement the Python class `RoomDocument` described below.
Class description:
Room document to add rooms in blueprints.
Method signatures and docstrings:
- def fill_from_object(self, room): Draw the document from an object.
- def add_neighbor(self, barcode: str, title: str, x: Optional[int]=None, y: Optional[int]=Non... | Implement the Python class `RoomDocument` described below.
Class description:
Room document to add rooms in blueprints.
Method signatures and docstrings:
- def fill_from_object(self, room): Draw the document from an object.
- def add_neighbor(self, barcode: str, title: str, x: Optional[int]=None, y: Optional[int]=Non... | fb7f98d331e47e2032ee1e51bf3e4b2592807fdf | <|skeleton|>
class RoomDocument:
"""Room document to add rooms in blueprints."""
def fill_from_object(self, room):
"""Draw the document from an object."""
<|body_0|>
def add_neighbor(self, barcode: str, title: str, x: Optional[int]=None, y: Optional[int]=None, z: Optional[int]=None, descri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoomDocument:
"""Room document to add rooms in blueprints."""
def fill_from_object(self, room):
"""Draw the document from an object."""
self.cleaned.barcode = room.barcode
self.cleaned.title = room.title
self.cleaned.x = room.x
self.cleaned.y = room.y
self.... | the_stack_v2_python_sparse | src/data/blueprints/room.py | vincent-lg/avenew.one | train | 0 |
3a8b2cf6d3f36cfe05234b8088f2db3fb8254e99 | [
"self._logger = logger\nself._no_run = False\nif not is_exe(exe_path):\n self._logger.error('No trim_quality script available (exiting)')\n sys.exit(1)\nself._exe_path = exe_path\nself.format = 'fastq'",
"self.__build_cmd(infname, outdir)\nmsg = ['Running...', '\\t%s' % self._cmd]\nfor m in msg:\n self._... | <|body_start_0|>
self._logger = logger
self._no_run = False
if not is_exe(exe_path):
self._logger.error('No trim_quality script available (exiting)')
sys.exit(1)
self._exe_path = exe_path
self.format = 'fastq'
<|end_body_0|>
<|body_start_1|>
self.... | Class for working with trim_quality | Trim_Quality | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trim_Quality:
"""Class for working with trim_quality"""
def __init__(self, exe_path, logger):
"""Instantiate with location of executable"""
<|body_0|>
def run(self, infname, outdir):
"""Run trim_quality on the passed file"""
<|body_1|>
def __build_cm... | stack_v2_sparse_classes_36k_train_003207 | 3,597 | permissive | [
{
"docstring": "Instantiate with location of executable",
"name": "__init__",
"signature": "def __init__(self, exe_path, logger)"
},
{
"docstring": "Run trim_quality on the passed file",
"name": "run",
"signature": "def run(self, infname, outdir)"
},
{
"docstring": "Build a comma... | 3 | stack_v2_sparse_classes_30k_train_006504 | Implement the Python class `Trim_Quality` described below.
Class description:
Class for working with trim_quality
Method signatures and docstrings:
- def __init__(self, exe_path, logger): Instantiate with location of executable
- def run(self, infname, outdir): Run trim_quality on the passed file
- def __build_cmd(se... | Implement the Python class `Trim_Quality` described below.
Class description:
Class for working with trim_quality
Method signatures and docstrings:
- def __init__(self, exe_path, logger): Instantiate with location of executable
- def run(self, infname, outdir): Run trim_quality on the passed file
- def __build_cmd(se... | a3c64198aad3709a5c4d969f48ae0af11fdc25db | <|skeleton|>
class Trim_Quality:
"""Class for working with trim_quality"""
def __init__(self, exe_path, logger):
"""Instantiate with location of executable"""
<|body_0|>
def run(self, infname, outdir):
"""Run trim_quality on the passed file"""
<|body_1|>
def __build_cm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trim_Quality:
"""Class for working with trim_quality"""
def __init__(self, exe_path, logger):
"""Instantiate with location of executable"""
self._logger = logger
self._no_run = False
if not is_exe(exe_path):
self._logger.error('No trim_quality script available ... | the_stack_v2_python_sparse | metapy/pycits/seq_crumbs.py | peterthorpe5/public_scripts | train | 35 |
bb3bc6092c99d7e8b4ff9b0483b32e167e844b76 | [
"self.backends = {'mockbackend': {'ENGINE': harness.MockBackend}}\nself.set_backends()\nrouter = get_router()\nself.assertFalse(router.is_eager('foo'))",
"self.backends = {'mockbackend': {'ENGINE': harness.MockBackend}}\nself.set_backends()\nrouter = get_router()\nself.assertFalse(router.is_eager('mockbackend'))"... | <|body_start_0|>
self.backends = {'mockbackend': {'ENGINE': harness.MockBackend}}
self.set_backends()
router = get_router()
self.assertFalse(router.is_eager('foo'))
<|end_body_0|>
<|body_start_1|>
self.backends = {'mockbackend': {'ENGINE': harness.MockBackend}}
self.set_... | CeleryRouterConfigTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CeleryRouterConfigTest:
def test_eager_invalid_backend(self):
"""is_eager should return False if backend doesn't exist."""
<|body_0|>
def test_eager_not_set(self):
"""is_eager should return False if not set for specified backend."""
<|body_1|>
def test_o... | stack_v2_sparse_classes_36k_train_003208 | 3,254 | permissive | [
{
"docstring": "is_eager should return False if backend doesn't exist.",
"name": "test_eager_invalid_backend",
"signature": "def test_eager_invalid_backend(self)"
},
{
"docstring": "is_eager should return False if not set for specified backend.",
"name": "test_eager_not_set",
"signature"... | 3 | stack_v2_sparse_classes_30k_val_000703 | Implement the Python class `CeleryRouterConfigTest` described below.
Class description:
Implement the CeleryRouterConfigTest class.
Method signatures and docstrings:
- def test_eager_invalid_backend(self): is_eager should return False if backend doesn't exist.
- def test_eager_not_set(self): is_eager should return Fa... | Implement the Python class `CeleryRouterConfigTest` described below.
Class description:
Implement the CeleryRouterConfigTest class.
Method signatures and docstrings:
- def test_eager_invalid_backend(self): is_eager should return False if backend doesn't exist.
- def test_eager_not_set(self): is_eager should return Fa... | aaa2ddab68e19d979525c3823c3ec0e646e92c83 | <|skeleton|>
class CeleryRouterConfigTest:
def test_eager_invalid_backend(self):
"""is_eager should return False if backend doesn't exist."""
<|body_0|>
def test_eager_not_set(self):
"""is_eager should return False if not set for specified backend."""
<|body_1|>
def test_o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CeleryRouterConfigTest:
def test_eager_invalid_backend(self):
"""is_eager should return False if backend doesn't exist."""
self.backends = {'mockbackend': {'ENGINE': harness.MockBackend}}
self.set_backends()
router = get_router()
self.assertFalse(router.is_eager('foo'))... | the_stack_v2_python_sparse | rapidsms/router/celery/tests.py | rapidsms/rapidsms | train | 409 | |
6a2442a7d9ef17368052906ec335b86b218f47d1 | [
"if self._replicasResource is None:\n self._replicasResource = {}\n if isinstance(self.replicas, list):\n for replica in self.replicas:\n self._replicasResource['replicaName'] = replica.name\n self._replicasResource['replicaID'] = replica.guid\nreturn self._replicasResource",
"u... | <|body_start_0|>
if self._replicasResource is None:
self._replicasResource = {}
if isinstance(self.replicas, list):
for replica in self.replicas:
self._replicasResource['replicaName'] = replica.name
self._replicasResource['replicaID... | Represents a single geodata service layer | GeoData | [
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeoData:
"""Represents a single geodata service layer"""
def replicasResource(self):
"""returns a list of replices"""
<|body_0|>
def unRegisterReplica(self, replicaGUID):
"""unRegisterReplica operation is performed on a Geodata Service resource (POST only). This ... | stack_v2_sparse_classes_36k_train_003209 | 1,911 | permissive | [
{
"docstring": "returns a list of replices",
"name": "replicasResource",
"signature": "def replicasResource(self)"
},
{
"docstring": "unRegisterReplica operation is performed on a Geodata Service resource (POST only). This operation unregisters a replica on the geodata service. Unregistering a r... | 2 | stack_v2_sparse_classes_30k_train_015553 | Implement the Python class `GeoData` described below.
Class description:
Represents a single geodata service layer
Method signatures and docstrings:
- def replicasResource(self): returns a list of replices
- def unRegisterReplica(self, replicaGUID): unRegisterReplica operation is performed on a Geodata Service resour... | Implement the Python class `GeoData` described below.
Class description:
Represents a single geodata service layer
Method signatures and docstrings:
- def replicasResource(self): returns a list of replices
- def unRegisterReplica(self, replicaGUID): unRegisterReplica operation is performed on a Geodata Service resour... | a874fe7e5c95196e4de68db2da0e2a05eb70e5d8 | <|skeleton|>
class GeoData:
"""Represents a single geodata service layer"""
def replicasResource(self):
"""returns a list of replices"""
<|body_0|>
def unRegisterReplica(self, replicaGUID):
"""unRegisterReplica operation is performed on a Geodata Service resource (POST only). This ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeoData:
"""Represents a single geodata service layer"""
def replicasResource(self):
"""returns a list of replices"""
if self._replicasResource is None:
self._replicasResource = {}
if isinstance(self.replicas, list):
for replica in self.replicas:
... | the_stack_v2_python_sparse | arcpyenv/arcgispro-py3-clone/Lib/site-packages/arcgis/gis/server/_service/_geodataservice.py | SherbazHashmi/HackathonServer | train | 3 |
47ca071d4aa7a0f7e1e52765acc5f58be89da92d | [
"if not root:\n return True\nleft = self.maxDepth(root.left)\nright = self.maxDepth(root.right)\nif abs(left - right) > 1:\n return False\nreturn self.isBalanced(root.left) and self.isBalanced(root.right)",
"if not root:\n return 0\nif not root.left and (not root.right):\n return 1\nreturn 1 + max(sel... | <|body_start_0|>
if not root:
return True
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
if abs(left - right) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
<|end_body_0|>
<|body_start_1|>
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return True
left ... | stack_v2_sparse_classes_36k_train_003210 | 715 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isBalanced",
"signature": "def isBalanced(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002509 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def maxDepth(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def maxDepth(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def isBalanced(self,... | 5ab258f04771db37a3beb3cb0c490a06183f7b51 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
if not root:
return True
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
if abs(left - right) > 1:
return False
return self.isBalanced(root.le... | the_stack_v2_python_sparse | py_solution/p110_tree_balance.py | dengshilong/leetcode | train | 0 | |
64c62c4beaa9f8f5643b9d8d8f3578ed24a1741e | [
"logout_button_sitem = self.locator_finder_by_id(self.logout_button_id)\nlogout_button_sitem.click()\nprint('Logout from the current user\\n')\nself.wait_for_ajax()",
"elem = self.locator_finder_by_xpath('/html/body/div[2]/div/div[1]/div/ul[1]/li[2]/a[2]')\nself.progress('Health state:' + elem.text)\nreturn elem.... | <|body_start_0|>
logout_button_sitem = self.locator_finder_by_id(self.logout_button_id)
logout_button_sitem.click()
print('Logout from the current user\n')
self.wait_for_ajax()
<|end_body_0|>
<|body_start_1|>
elem = self.locator_finder_by_xpath('/html/body/div[2]/div/div[1]/div/... | Page object representing the user bar | UserBarPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserBarPage:
"""Page object representing the user bar"""
def log_out(self):
"""click log out icon on the user bar and wait for"""
<|body_0|>
def get_health_state(self):
"""extract the health state in the upper right corner"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_003211 | 861 | no_license | [
{
"docstring": "click log out icon on the user bar and wait for",
"name": "log_out",
"signature": "def log_out(self)"
},
{
"docstring": "extract the health state in the upper right corner",
"name": "get_health_state",
"signature": "def get_health_state(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006142 | Implement the Python class `UserBarPage` described below.
Class description:
Page object representing the user bar
Method signatures and docstrings:
- def log_out(self): click log out icon on the user bar and wait for
- def get_health_state(self): extract the health state in the upper right corner | Implement the Python class `UserBarPage` described below.
Class description:
Page object representing the user bar
Method signatures and docstrings:
- def log_out(self): click log out icon on the user bar and wait for
- def get_health_state(self): extract the health state in the upper right corner
<|skeleton|>
class... | 4d4a0b049eb83625df41d86f2066ddb0c6c9c85b | <|skeleton|>
class UserBarPage:
"""Page object representing the user bar"""
def log_out(self):
"""click log out icon on the user bar and wait for"""
<|body_0|>
def get_health_state(self):
"""extract the health state in the upper right corner"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserBarPage:
"""Page object representing the user bar"""
def log_out(self):
"""click log out icon on the user bar and wait for"""
logout_button_sitem = self.locator_finder_by_id(self.logout_button_id)
logout_button_sitem.click()
print('Logout from the current user\n')
... | the_stack_v2_python_sparse | release_tester/selenium_ui_test/pages/user_bar_page.py | arangodb/release-test-automation | train | 14 |
9e69155b820e56c6b47aa0b37da52ebd0a87b631 | [
"while i < j:\n subnums[i], subnums[j] = (subnums[j], subnums[i])\n i = i + 1\n j = j - 1",
"l = len(nums)\nk = k % l\nif k == 0:\n print(nums)\n return\nself.reverse(nums, 0, l - k - 1)\nself.reverse(nums, l - k, l - 1)\nself.reverse(nums, 0, l - 1)\nprint(nums)"
] | <|body_start_0|>
while i < j:
subnums[i], subnums[j] = (subnums[j], subnums[i])
i = i + 1
j = j - 1
<|end_body_0|>
<|body_start_1|>
l = len(nums)
k = k % l
if k == 0:
print(nums)
return
self.reverse(nums, 0, l - k - 1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, subnums, i, j):
""":type subnus: List[int] :type i: int :type j: int"""
<|body_0|>
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_003212 | 1,750 | no_license | [
{
"docstring": ":type subnus: List[int] :type i: int :type j: int",
"name": "reverse",
"signature": "def reverse(self, subnums, i, j)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature":... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, subnums, i, j): :type subnus: List[int] :type i: int :type j: int
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return any... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, subnums, i, j): :type subnus: List[int] :type i: int :type j: int
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return any... | 62ccbdedf4e1fb9788acfeb2a5bfce70f86c68b6 | <|skeleton|>
class Solution:
def reverse(self, subnums, i, j):
""":type subnus: List[int] :type i: int :type j: int"""
<|body_0|>
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse(self, subnums, i, j):
""":type subnus: List[int] :type i: int :type j: int"""
while i < j:
subnums[i], subnums[j] = (subnums[j], subnums[i])
i = i + 1
j = j - 1
def rotate(self, nums, k):
""":type nums: List[int] :type k: i... | the_stack_v2_python_sparse | LeetCode/189.py | cylinder-lee-cn/LeetCode | train | 0 | |
8c6c7b820e394fb0f2ebbd4c3eb37090ca3d68a7 | [
"if not is_string(pattern):\n raise ValueError('Pattern argument must be a string')\nself._pattern = pattern\nself._regex = re.compile(pattern) if pattern is not None else None",
"value = super(StringPatternParser, self).parse(value)\nif not self._regex.match(value):\n raise ValueParsingError(u\"String valu... | <|body_start_0|>
if not is_string(pattern):
raise ValueError('Pattern argument must be a string')
self._pattern = pattern
self._regex = re.compile(pattern) if pattern is not None else None
<|end_body_0|>
<|body_start_1|>
value = super(StringPatternParser, self).parse(value)
... | String parser using a regular expression pattern. | StringPatternParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringPatternParser:
"""String parser using a regular expression pattern."""
def __init__(self, pattern):
"""Initialize a new instance of StringPatternParser class. :param pattern: Regular expression which string's value must conform to :type pattern: RegEx"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_003213 | 23,409 | permissive | [
{
"docstring": "Initialize a new instance of StringPatternParser class. :param pattern: Regular expression which string's value must conform to :type pattern: RegEx",
"name": "__init__",
"signature": "def __init__(self, pattern)"
},
{
"docstring": "Parse a string value using the specified regula... | 2 | stack_v2_sparse_classes_30k_train_004366 | Implement the Python class `StringPatternParser` described below.
Class description:
String parser using a regular expression pattern.
Method signatures and docstrings:
- def __init__(self, pattern): Initialize a new instance of StringPatternParser class. :param pattern: Regular expression which string's value must c... | Implement the Python class `StringPatternParser` described below.
Class description:
String parser using a regular expression pattern.
Method signatures and docstrings:
- def __init__(self, pattern): Initialize a new instance of StringPatternParser class. :param pattern: Regular expression which string's value must c... | 662cc7e0721d0153857c8c17a37e2a6df86f8ce6 | <|skeleton|>
class StringPatternParser:
"""String parser using a regular expression pattern."""
def __init__(self, pattern):
"""Initialize a new instance of StringPatternParser class. :param pattern: Regular expression which string's value must conform to :type pattern: RegEx"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringPatternParser:
"""String parser using a regular expression pattern."""
def __init__(self, pattern):
"""Initialize a new instance of StringPatternParser class. :param pattern: Regular expression which string's value must conform to :type pattern: RegEx"""
if not is_string(pattern):
... | the_stack_v2_python_sparse | core/util/webpub_manifest_parser/core/parsers.py | NYPL-Simplified/circulation | train | 20 |
bde595c7e9a4ee5dc25e735b39f55e4f4d7f7ffa | [
"super(ModelBrowser, self).__init__(parent=parent)\nself.path_ = path\nself.width_ = width\nself.height_ = height\nself.inc = 0\nself.roty = 0\nself.cam = Camera('PERSPECTIVE')\npass",
"self.model = Model()\nself.model.load_model(self.path_)\nself.cam.setEye(0, 0, -60)\nself.cam.on()\npass",
"glPushMatrix()\ngl... | <|body_start_0|>
super(ModelBrowser, self).__init__(parent=parent)
self.path_ = path
self.width_ = width
self.height_ = height
self.inc = 0
self.roty = 0
self.cam = Camera('PERSPECTIVE')
pass
<|end_body_0|>
<|body_start_1|>
self.model = Model()
... | ModelBrowser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelBrowser:
def __init__(self, path, width, height, parent=None):
"""@param path : Path to a model @param width : Width of the Screen @param height : Height of the Screen"""
<|body_0|>
def initGL(self):
"""Overloaded function from GLWidget"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_003214 | 1,827 | no_license | [
{
"docstring": "@param path : Path to a model @param width : Width of the Screen @param height : Height of the Screen",
"name": "__init__",
"signature": "def __init__(self, path, width, height, parent=None)"
},
{
"docstring": "Overloaded function from GLWidget",
"name": "initGL",
"signat... | 4 | stack_v2_sparse_classes_30k_train_004398 | Implement the Python class `ModelBrowser` described below.
Class description:
Implement the ModelBrowser class.
Method signatures and docstrings:
- def __init__(self, path, width, height, parent=None): @param path : Path to a model @param width : Width of the Screen @param height : Height of the Screen
- def initGL(s... | Implement the Python class `ModelBrowser` described below.
Class description:
Implement the ModelBrowser class.
Method signatures and docstrings:
- def __init__(self, path, width, height, parent=None): @param path : Path to a model @param width : Width of the Screen @param height : Height of the Screen
- def initGL(s... | ef3737087d25248e3f924e7d66bb4ef459745956 | <|skeleton|>
class ModelBrowser:
def __init__(self, path, width, height, parent=None):
"""@param path : Path to a model @param width : Width of the Screen @param height : Height of the Screen"""
<|body_0|>
def initGL(self):
"""Overloaded function from GLWidget"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelBrowser:
def __init__(self, path, width, height, parent=None):
"""@param path : Path to a model @param width : Width of the Screen @param height : Height of the Screen"""
super(ModelBrowser, self).__init__(parent=parent)
self.path_ = path
self.width_ = width
self.h... | the_stack_v2_python_sparse | tutorials/model_browser.py | pchalas1/libWall | train | 0 | |
f78c4063bc7b46c14aeed2b204ead3271a43c51a | [
"super(GameLR, self).__init__()\nself.queries, self.encrypt, self.key_len = (queries, encrypt, key_len)\nself.key = ''\nself.b = -1\nself.key_gen = key_gen",
"if self.key_gen is None:\n self.key = random_string(self.key_len)\nelse:\n self.key = self.key_gen()\nif b is None:\n b = random.randrange(0, 2, 1... | <|body_start_0|>
super(GameLR, self).__init__()
self.queries, self.encrypt, self.key_len = (queries, encrypt, key_len)
self.key = ''
self.b = -1
self.key_gen = key_gen
<|end_body_0|>
<|body_start_1|>
if self.key_gen is None:
self.key = random_string(self.key_... | This game is used as a base game for games that need to determine between a left and right encryption. It is useful to determine how well a scheme is hiding its data from the adversary. | GameLR | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameLR:
"""This game is used as a base game for games that need to determine between a left and right encryption. It is useful to determine how well a scheme is hiding its data from the adversary."""
def __init__(self, queries, encrypt, key_len, key_gen=None):
""":param encrypt: This... | stack_v2_sparse_classes_36k_train_003215 | 2,984 | no_license | [
{
"docstring": ":param encrypt: This must be a callable python function that takes two inputs, k and x where k is a key of length key_len and x is a message. :param key_len: Length of the key (in bytes) used in the function that will be tested with this game.",
"name": "__init__",
"signature": "def __in... | 4 | stack_v2_sparse_classes_30k_train_004161 | Implement the Python class `GameLR` described below.
Class description:
This game is used as a base game for games that need to determine between a left and right encryption. It is useful to determine how well a scheme is hiding its data from the adversary.
Method signatures and docstrings:
- def __init__(self, queri... | Implement the Python class `GameLR` described below.
Class description:
This game is used as a base game for games that need to determine between a left and right encryption. It is useful to determine how well a scheme is hiding its data from the adversary.
Method signatures and docstrings:
- def __init__(self, queri... | 9014f5a9bf7021bef9f5cc4aa5b16424ca83dee9 | <|skeleton|>
class GameLR:
"""This game is used as a base game for games that need to determine between a left and right encryption. It is useful to determine how well a scheme is hiding its data from the adversary."""
def __init__(self, queries, encrypt, key_len, key_gen=None):
""":param encrypt: This... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameLR:
"""This game is used as a base game for games that need to determine between a left and right encryption. It is useful to determine how well a scheme is hiding its data from the adversary."""
def __init__(self, queries, encrypt, key_len, key_gen=None):
""":param encrypt: This must be a ca... | the_stack_v2_python_sparse | src/playcrypt/games/game_lr.py | UCSDCSE107/playcrypt | train | 2 |
aca34e89d46a1dea0e3ba257eb44055a9cd9736e | [
"cur = head\nnew_head = None\nwhile cur:\n if not new_head:\n new_head = ListNode(cur.val)\n else:\n node = ListNode(cur.val)\n node.next = new_head\n new_head = node\n cur = cur.next\nreturn new_head",
"new_head = None\nwhile head:\n tmp = head.next\n head.next = new_he... | <|body_start_0|>
cur = head
new_head = None
while cur:
if not new_head:
new_head = ListNode(cur.val)
else:
node = ListNode(cur.val)
node.next = new_head
new_head = node
cur = cur.next
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cur = head
new_head = None
... | stack_v2_sparse_classes_36k_train_003216 | 1,399 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList1",
"signature": "def reverseList1(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017012 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList1(self, head): :type head: ListNode :rtype: ListNode
- def reverseList(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList1(self, head): :type head: ListNode :rtype: ListNode
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def re... | 27e1a7dc757f4a254dc94dd16619e2f3d73895a7 | <|skeleton|>
class Solution:
def reverseList1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList1(self, head):
""":type head: ListNode :rtype: ListNode"""
cur = head
new_head = None
while cur:
if not new_head:
new_head = ListNode(cur.val)
else:
node = ListNode(cur.val)
node.ne... | the_stack_v2_python_sparse | problems/206_Reverse_Linked_List.py | johnnyshi1225/leetcode | train | 2 | |
a6cb4bd1c560abaad1a0deaffc2214891c6453fa | [
"super(RecyclingEmbedder, self).__init__()\nself.c_m = c_m\nself.c_z = c_z\nself.min_bin = min_bin\nself.max_bin = max_bin\nself.no_bins = no_bins\nself.inf = inf\nself.linear = Linear(self.no_bins, self.c_z)\nself.layer_norm_m = LayerNorm(self.c_m)\nself.layer_norm_z = LayerNorm(self.c_z)",
"m_update = self.laye... | <|body_start_0|>
super(RecyclingEmbedder, self).__init__()
self.c_m = c_m
self.c_z = c_z
self.min_bin = min_bin
self.max_bin = max_bin
self.no_bins = no_bins
self.inf = inf
self.linear = Linear(self.no_bins, self.c_z)
self.layer_norm_m = LayerNorm(... | Embeds the output of an iteration of the model for recycling. Implements Algorithm 32. | RecyclingEmbedder | [
"Apache-2.0",
"CC-BY-4.0",
"LicenseRef-scancode-other-permissive",
"CC-BY-NC-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecyclingEmbedder:
"""Embeds the output of an iteration of the model for recycling. Implements Algorithm 32."""
def __init__(self, c_m: int, c_z: int, min_bin: float, max_bin: float, no_bins: int, inf: float=100000000.0, **kwargs):
"""Args: c_m: MSA channel dimension c_z: Pair embedd... | stack_v2_sparse_classes_36k_train_003217 | 9,577 | permissive | [
{
"docstring": "Args: c_m: MSA channel dimension c_z: Pair embedding channel dimension min_bin: Smallest distogram bin (Angstroms) max_bin: Largest distogram bin (Angstroms) no_bins: Number of distogram bins",
"name": "__init__",
"signature": "def __init__(self, c_m: int, c_z: int, min_bin: float, max_b... | 2 | stack_v2_sparse_classes_30k_train_014671 | Implement the Python class `RecyclingEmbedder` described below.
Class description:
Embeds the output of an iteration of the model for recycling. Implements Algorithm 32.
Method signatures and docstrings:
- def __init__(self, c_m: int, c_z: int, min_bin: float, max_bin: float, no_bins: int, inf: float=100000000.0, **k... | Implement the Python class `RecyclingEmbedder` described below.
Class description:
Embeds the output of an iteration of the model for recycling. Implements Algorithm 32.
Method signatures and docstrings:
- def __init__(self, c_m: int, c_z: int, min_bin: float, max_bin: float, no_bins: int, inf: float=100000000.0, **k... | 2134cc09b3994b6280e6e3c569dd7d761e4da7a0 | <|skeleton|>
class RecyclingEmbedder:
"""Embeds the output of an iteration of the model for recycling. Implements Algorithm 32."""
def __init__(self, c_m: int, c_z: int, min_bin: float, max_bin: float, no_bins: int, inf: float=100000000.0, **kwargs):
"""Args: c_m: MSA channel dimension c_z: Pair embedd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecyclingEmbedder:
"""Embeds the output of an iteration of the model for recycling. Implements Algorithm 32."""
def __init__(self, c_m: int, c_z: int, min_bin: float, max_bin: float, no_bins: int, inf: float=100000000.0, **kwargs):
"""Args: c_m: MSA channel dimension c_z: Pair embedding channel d... | the_stack_v2_python_sparse | openfold/model/embedders.py | aqlaboratory/openfold | train | 2,033 |
f38a512c2b299eca501fd4da924f0106637a673e | [
"self.first = True\nself.my_arr = list(characters)\nself.my_val = []\nfor i in range(combinationLength):\n self.my_val.append(i)",
"if self.first:\n self.first = False\n return_arr = ''\n for i in self.my_val:\n return_arr += self.my_arr[i]\n return return_arr\nif self.my_val[-1] == len(self... | <|body_start_0|>
self.first = True
self.my_arr = list(characters)
self.my_val = []
for i in range(combinationLength):
self.my_val.append(i)
<|end_body_0|>
<|body_start_1|>
if self.first:
self.first = False
return_arr = ''
for i in ... | CombinationIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CombinationIterator:
def __init__(self, characters, combinationLength):
""":type characters: str :type combinationLength: int"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k_train_003218 | 2,009 | no_license | [
{
"docstring": ":type characters: str :type combinationLength: int",
"name": "__init__",
"signature": "def __init__(self, characters, combinationLength)"
},
{
"docstring": ":rtype: str",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "... | 3 | null | Implement the Python class `CombinationIterator` described below.
Class description:
Implement the CombinationIterator class.
Method signatures and docstrings:
- def __init__(self, characters, combinationLength): :type characters: str :type combinationLength: int
- def next(self): :rtype: str
- def hasNext(self): :rt... | Implement the Python class `CombinationIterator` described below.
Class description:
Implement the CombinationIterator class.
Method signatures and docstrings:
- def __init__(self, characters, combinationLength): :type characters: str :type combinationLength: int
- def next(self): :rtype: str
- def hasNext(self): :rt... | 77a13580fd6231830558b1cf8c84f8b3b62b99d0 | <|skeleton|>
class CombinationIterator:
def __init__(self, characters, combinationLength):
""":type characters: str :type combinationLength: int"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CombinationIterator:
def __init__(self, characters, combinationLength):
""":type characters: str :type combinationLength: int"""
self.first = True
self.my_arr = list(characters)
self.my_val = []
for i in range(combinationLength):
self.my_val.append(i)
d... | the_stack_v2_python_sparse | lc-1286.py | UtsavRaychaudhuri/leetcode | train | 0 | |
805f530bab71d4a09b91e729ee876a7b65185179 | [
"for i in range(len(board)):\n for j in range(len(board[0])):\n if self.dfs(board, i, j, word):\n return True\nreturn False",
"if len(word) == 0:\n return True\nif i < 0 or i > len(board) - 1 or j < 0 or (j > len(board[0]) - 1) or (board[i][j] != word[0]):\n return False\ntmp = board[i]... | <|body_start_0|>
for i in range(len(board)):
for j in range(len(board[0])):
if self.dfs(board, i, j, word):
return True
return False
<|end_body_0|>
<|body_start_1|>
if len(word) == 0:
return True
if i < 0 or i > len(board) - 1 ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def exist(self, board, word):
"""horizontally search"""
<|body_0|>
def dfs(self, board, i, j, word):
"""make sure whether there exists a path of given word start from board[i][j] this is dfs search!!! 1. first check if board[i][j] == word[0], return false i... | stack_v2_sparse_classes_36k_train_003219 | 1,860 | no_license | [
{
"docstring": "horizontally search",
"name": "exist",
"signature": "def exist(self, board, word)"
},
{
"docstring": "make sure whether there exists a path of given word start from board[i][j] this is dfs search!!! 1. first check if board[i][j] == word[0], return false if not, turn to another di... | 2 | stack_v2_sparse_classes_30k_train_019747 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def exist(self, board, word): horizontally search
- def dfs(self, board, i, j, word): make sure whether there exists a path of given word start from board[i][j] this is dfs searc... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def exist(self, board, word): horizontally search
- def dfs(self, board, i, j, word): make sure whether there exists a path of given word start from board[i][j] this is dfs searc... | b9a2bd8385e44cc79454f9c7f2146370896559ec | <|skeleton|>
class Solution:
def exist(self, board, word):
"""horizontally search"""
<|body_0|>
def dfs(self, board, i, j, word):
"""make sure whether there exists a path of given word start from board[i][j] this is dfs search!!! 1. first check if board[i][j] == word[0], return false i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def exist(self, board, word):
"""horizontally search"""
for i in range(len(board)):
for j in range(len(board[0])):
if self.dfs(board, i, j, word):
return True
return False
def dfs(self, board, i, j, word):
"""make s... | the_stack_v2_python_sparse | 79.WordSearch.py | haveGrasses/Algorithm | train | 0 | |
df1f7ec18c67941dd46beb4812c532d7686e3bf0 | [
"time_elements_tuple = self._GetValueFromStructure(structure, 'header_date_time')\ntry:\n date_time = dfdatetime_time_elements.TimeElementsInMilliseconds(time_elements_tuple=time_elements_tuple)\nexcept ValueError:\n parser_mediator.ProduceExtractionWarning('invalid date time value: {0!s}'.format(time_element... | <|body_start_0|>
time_elements_tuple = self._GetValueFromStructure(structure, 'header_date_time')
try:
date_time = dfdatetime_time_elements.TimeElementsInMilliseconds(time_elements_tuple=time_elements_tuple)
except ValueError:
parser_mediator.ProduceExtractionWarning('inv... | Parses SkyDrive log files. | SkyDriveLogParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkyDriveLogParser:
"""Parses SkyDrive log files."""
def _ParseHeader(self, parser_mediator, structure):
"""Parse header lines and store appropriate attributes. ['Logging started.', 'Version=', '17.0.2011.0627', [2013, 7, 25], 16, 3, 23, 291, 'StartLocalTime', '<details>'] Args: parse... | stack_v2_sparse_classes_36k_train_003220 | 16,775 | permissive | [
{
"docstring": "Parse header lines and store appropriate attributes. ['Logging started.', 'Version=', '17.0.2011.0627', [2013, 7, 25], 16, 3, 23, 291, 'StartLocalTime', '<details>'] Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. str... | 4 | null | Implement the Python class `SkyDriveLogParser` described below.
Class description:
Parses SkyDrive log files.
Method signatures and docstrings:
- def _ParseHeader(self, parser_mediator, structure): Parse header lines and store appropriate attributes. ['Logging started.', 'Version=', '17.0.2011.0627', [2013, 7, 25], 1... | Implement the Python class `SkyDriveLogParser` described below.
Class description:
Parses SkyDrive log files.
Method signatures and docstrings:
- def _ParseHeader(self, parser_mediator, structure): Parse header lines and store appropriate attributes. ['Logging started.', 'Version=', '17.0.2011.0627', [2013, 7, 25], 1... | c69b2952b608cfce47ff8fd0d1409d856be35cb1 | <|skeleton|>
class SkyDriveLogParser:
"""Parses SkyDrive log files."""
def _ParseHeader(self, parser_mediator, structure):
"""Parse header lines and store appropriate attributes. ['Logging started.', 'Version=', '17.0.2011.0627', [2013, 7, 25], 16, 3, 23, 291, 'StartLocalTime', '<details>'] Args: parse... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SkyDriveLogParser:
"""Parses SkyDrive log files."""
def _ParseHeader(self, parser_mediator, structure):
"""Parse header lines and store appropriate attributes. ['Logging started.', 'Version=', '17.0.2011.0627', [2013, 7, 25], 16, 3, 23, 291, 'StartLocalTime', '<details>'] Args: parser_mediator (P... | the_stack_v2_python_sparse | plaso/parsers/skydrivelog.py | cyb3rfox/plaso | train | 3 |
5ca7ea81e1e2fab1dae5cc8643c73c23e15e94cf | [
"super().__init__()\nself.conv = Conv2dHeadModel(image_shape=image_shape, channels=channels or [16, 32], kernel_sizes=kernel_sizes or [8, 4], strides=strides or [4, 2], paddings=paddings or [0, 1], use_maxpool=use_maxpool, hidden_sizes=fc_sizes)\nself.pi = torch.nn.Linear(self.conv.output_size, output_size)\nself.v... | <|body_start_0|>
super().__init__()
self.conv = Conv2dHeadModel(image_shape=image_shape, channels=channels or [16, 32], kernel_sizes=kernel_sizes or [8, 4], strides=strides or [4, 2], paddings=paddings or [0, 1], use_maxpool=use_maxpool, hidden_sizes=fc_sizes)
self.pi = torch.nn.Linear(self.conv... | Feedforward model for Atari agents: a convolutional network feeding an MLP with outputs for action probabilities and state-value estimate. | AtariFfModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtariFfModel:
"""Feedforward model for Atari agents: a convolutional network feeding an MLP with outputs for action probabilities and state-value estimate."""
def __init__(self, image_shape, output_size, fc_sizes=512, use_maxpool=False, channels=None, kernel_sizes=None, strides=None, padding... | stack_v2_sparse_classes_36k_train_003221 | 2,373 | permissive | [
{
"docstring": "Instantiate neural net module according to inputs.",
"name": "__init__",
"signature": "def __init__(self, image_shape, output_size, fc_sizes=512, use_maxpool=False, channels=None, kernel_sizes=None, strides=None, paddings=None)"
},
{
"docstring": "Compute action probabilities and... | 2 | stack_v2_sparse_classes_30k_train_005750 | Implement the Python class `AtariFfModel` described below.
Class description:
Feedforward model for Atari agents: a convolutional network feeding an MLP with outputs for action probabilities and state-value estimate.
Method signatures and docstrings:
- def __init__(self, image_shape, output_size, fc_sizes=512, use_ma... | Implement the Python class `AtariFfModel` described below.
Class description:
Feedforward model for Atari agents: a convolutional network feeding an MLP with outputs for action probabilities and state-value estimate.
Method signatures and docstrings:
- def __init__(self, image_shape, output_size, fc_sizes=512, use_ma... | 98681a23bae9e8e5e9fbf68a0316ca2a22a27593 | <|skeleton|>
class AtariFfModel:
"""Feedforward model for Atari agents: a convolutional network feeding an MLP with outputs for action probabilities and state-value estimate."""
def __init__(self, image_shape, output_size, fc_sizes=512, use_maxpool=False, channels=None, kernel_sizes=None, strides=None, padding... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AtariFfModel:
"""Feedforward model for Atari agents: a convolutional network feeding an MLP with outputs for action probabilities and state-value estimate."""
def __init__(self, image_shape, output_size, fc_sizes=512, use_maxpool=False, channels=None, kernel_sizes=None, strides=None, paddings=None):
... | the_stack_v2_python_sparse | dependencies/rlpyt/rlpyt/models/pg/atari_ff_model.py | keirp/glamor | train | 5 |
d30a2106268094b00b2f65cca7c23749a3488635 | [
"logging.info('original table has %d rows' % len(table))\ntable = table.dropna(subset=[stat_col])\nlogging.info('cleaned table has %d rows' % len(table))\nreturn table",
"threshold = float(threshold)\ntry:\n if alternative == 'less':\n table = table[table[filter_column] < threshold]\n else:\n ... | <|body_start_0|>
logging.info('original table has %d rows' % len(table))
table = table.dropna(subset=[stat_col])
logging.info('cleaned table has %d rows' % len(table))
return table
<|end_body_0|>
<|body_start_1|>
threshold = float(threshold)
try:
if alternati... | This class contains static methods to clean and filter specific columns of a table | TableElaboration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TableElaboration:
"""This class contains static methods to clean and filter specific columns of a table"""
def clean_table(table: pd.DataFrame, stat_col: str='stat') -> pd.DataFrame:
"""This function clean the table from the N/A values :param table: dataframerepresenting the table to... | stack_v2_sparse_classes_36k_train_003222 | 2,137 | permissive | [
{
"docstring": "This function clean the table from the N/A values :param table: dataframerepresenting the table to be cleaned :param stat_col: the column to be cleaned :return: the table cleaned from the N/A values Example _______ >>> import numpy as np >>> table = pd.DataFrame(np.random.randint(0,100,size=(100... | 2 | stack_v2_sparse_classes_30k_train_016171 | Implement the Python class `TableElaboration` described below.
Class description:
This class contains static methods to clean and filter specific columns of a table
Method signatures and docstrings:
- def clean_table(table: pd.DataFrame, stat_col: str='stat') -> pd.DataFrame: This function clean the table from the N/... | Implement the Python class `TableElaboration` described below.
Class description:
This class contains static methods to clean and filter specific columns of a table
Method signatures and docstrings:
- def clean_table(table: pd.DataFrame, stat_col: str='stat') -> pd.DataFrame: This function clean the table from the N/... | 3c172abe4b5391c5fb9a41f5fdc104ba0a3ab86b | <|skeleton|>
class TableElaboration:
"""This class contains static methods to clean and filter specific columns of a table"""
def clean_table(table: pd.DataFrame, stat_col: str='stat') -> pd.DataFrame:
"""This function clean the table from the N/A values :param table: dataframerepresenting the table to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TableElaboration:
"""This class contains static methods to clean and filter specific columns of a table"""
def clean_table(table: pd.DataFrame, stat_col: str='stat') -> pd.DataFrame:
"""This function clean the table from the N/A values :param table: dataframerepresenting the table to be cleaned :... | the_stack_v2_python_sparse | pygna/elaborators.py | stracquadaniolab/pygna | train | 41 |
8922755f3f0aca7677e194fd2ecddb0978b9215e | [
"self.source = source\nself.provider = provider\nself.date = date\nself.currency = currency\nself.buy_normal = None\nself.buy_foil = None\nself.sell_normal = None\nself.sell_foil = None",
"buy_sell_option: Dict[str, Any] = {}\nif self.buy_normal is not None or self.buy_foil is not None:\n buy_sell_option['buyl... | <|body_start_0|>
self.source = source
self.provider = provider
self.date = date
self.currency = currency
self.buy_normal = None
self.buy_foil = None
self.sell_normal = None
self.sell_foil = None
<|end_body_0|>
<|body_start_1|>
buy_sell_option: Dic... | MTGJSON Singular Prices.Card Object | MtgjsonPricesObject | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MtgjsonPricesObject:
"""MTGJSON Singular Prices.Card Object"""
def __init__(self, source: str, provider: str, date: str, currency: str) -> None:
"""Initializer for Pricing Container"""
<|body_0|>
def to_json(self) -> Dict[str, Any]:
"""Support json.dump() :return... | stack_v2_sparse_classes_36k_train_003223 | 1,883 | permissive | [
{
"docstring": "Initializer for Pricing Container",
"name": "__init__",
"signature": "def __init__(self, source: str, provider: str, date: str, currency: str) -> None"
},
{
"docstring": "Support json.dump() :return: JSON serialized object",
"name": "to_json",
"signature": "def to_json(se... | 2 | null | Implement the Python class `MtgjsonPricesObject` described below.
Class description:
MTGJSON Singular Prices.Card Object
Method signatures and docstrings:
- def __init__(self, source: str, provider: str, date: str, currency: str) -> None: Initializer for Pricing Container
- def to_json(self) -> Dict[str, Any]: Suppor... | Implement the Python class `MtgjsonPricesObject` described below.
Class description:
MTGJSON Singular Prices.Card Object
Method signatures and docstrings:
- def __init__(self, source: str, provider: str, date: str, currency: str) -> None: Initializer for Pricing Container
- def to_json(self) -> Dict[str, Any]: Suppor... | 55b8fea1969fa83587361ea53a2633e2a8ec1263 | <|skeleton|>
class MtgjsonPricesObject:
"""MTGJSON Singular Prices.Card Object"""
def __init__(self, source: str, provider: str, date: str, currency: str) -> None:
"""Initializer for Pricing Container"""
<|body_0|>
def to_json(self) -> Dict[str, Any]:
"""Support json.dump() :return... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MtgjsonPricesObject:
"""MTGJSON Singular Prices.Card Object"""
def __init__(self, source: str, provider: str, date: str, currency: str) -> None:
"""Initializer for Pricing Container"""
self.source = source
self.provider = provider
self.date = date
self.currency = c... | the_stack_v2_python_sparse | mtgjson5/classes/mtgjson_prices.py | mtgjson/mtgjson | train | 291 |
a44acaa1c86f430e650f326c0bd36ba6b739a27d | [
"self.W = theano.shared(value=rng.uniform(low=-numpy.sqrt(6.0 / n_in), high=numpy.sqrt(6.0 / n_in), size=(n_in,)), name='W', borrow=True)\nself.b = theano.shared(value=0.0, name='b', borrow=True)\nself.L1 = abs(self.W).sum()\nself.L2_sqr = (self.W ** 2).sum()\nh_1 = T.dot(input, self.W) + self.b\nself.p_1 = 1 / (1 ... | <|body_start_0|>
self.W = theano.shared(value=rng.uniform(low=-numpy.sqrt(6.0 / n_in), high=numpy.sqrt(6.0 / n_in), size=(n_in,)), name='W', borrow=True)
self.b = theano.shared(value=0.0, name='b', borrow=True)
self.L1 = abs(self.W).sum()
self.L2_sqr = (self.W ** 2).sum()
h_1 = T... | Binary Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is used to determine a class membership probability. | LogisticRegression | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogisticRegression:
"""Binary Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is used to determine a class membership prob... | stack_v2_sparse_classes_36k_train_003224 | 4,246 | permissive | [
{
"docstring": "Initialize the parameters of the logistic regression :type input: theano.tensor.TensorType :param input: symbolic variable that describes the input of the architecture (one minibatch) :type n_in: int :param n_in: number of input units, the dimension of the space in which the datapoints lie :type... | 3 | stack_v2_sparse_classes_30k_val_000954 | Implement the Python class `LogisticRegression` described below.
Class description:
Binary Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is us... | Implement the Python class `LogisticRegression` described below.
Class description:
Binary Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is us... | 82e04d1b5beadda9c8c0b8a684fe0aa8230852e3 | <|skeleton|>
class LogisticRegression:
"""Binary Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is used to determine a class membership prob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogisticRegression:
"""Binary Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is used to determine a class membership probability."""
... | the_stack_v2_python_sparse | tools/DependencyReordering/nnAdapt/models/logistic_sgd.py | nusnlp/neuralreord-aaai2017 | train | 3 |
f8a37a2e9d16fa72cf44fad38ce36e73a84659f8 | [
"self.ai_settings = ai_settings\nself.reset_stats()\nself.game_active = False\nself.high_score = 0",
"self.ships_left = self.ai_settings.ship_limit\nself.score = 0\nself.level = 1\nfilename = 'high_score.json'\ntry:\n with open(filename) as f:\n self.high_score = json.load(f)\nexcept FileNotFoundError:\... | <|body_start_0|>
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = False
self.high_score = 0
<|end_body_0|>
<|body_start_1|>
self.ships_left = self.ai_settings.ship_limit
self.score = 0
self.level = 1
filename = 'high_score.json'
... | 跟踪游戏的统计信息 | GameStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, ai_settings):
"""初始化统计信息"""
<|body_0|>
def reset_stats(self):
"""初始化在游戏运行期间可能变化的统计信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.ai_settings = ai_settings
self.reset_stats()
... | stack_v2_sparse_classes_36k_train_003225 | 901 | no_license | [
{
"docstring": "初始化统计信息",
"name": "__init__",
"signature": "def __init__(self, ai_settings)"
},
{
"docstring": "初始化在游戏运行期间可能变化的统计信息",
"name": "reset_stats",
"signature": "def reset_stats(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001684 | Implement the Python class `GameStats` described below.
Class description:
跟踪游戏的统计信息
Method signatures and docstrings:
- def __init__(self, ai_settings): 初始化统计信息
- def reset_stats(self): 初始化在游戏运行期间可能变化的统计信息 | Implement the Python class `GameStats` described below.
Class description:
跟踪游戏的统计信息
Method signatures and docstrings:
- def __init__(self, ai_settings): 初始化统计信息
- def reset_stats(self): 初始化在游戏运行期间可能变化的统计信息
<|skeleton|>
class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, ai_settings):
"""初始化统计信息"""
... | 9dc8ddd440e56a9961b118813162323fdfd4f16e | <|skeleton|>
class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, ai_settings):
"""初始化统计信息"""
<|body_0|>
def reset_stats(self):
"""初始化在游戏运行期间可能变化的统计信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, ai_settings):
"""初始化统计信息"""
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = False
self.high_score = 0
def reset_stats(self):
"""初始化在游戏运行期间可能变化的统计信息"""
self.ships_left = self.ai_... | the_stack_v2_python_sparse | python编程从入门到实践/第十四章/14-5/game_stats.py | huanglun1994/learn | train | 0 |
fb0d65dc5abc847545701fc4408ba69975074156 | [
"self.db.max_hp = 100\nself.db.hp = self.db.max_hp\n\"\\n Adds attributes for a character's current and maximum HP.\\n We're just going to set this value at '100' by default.\\n\\n You may want to expand this to include various 'stats' that\\n can be changed at creation and factor into c... | <|body_start_0|>
self.db.max_hp = 100
self.db.hp = self.db.max_hp
"\n Adds attributes for a character's current and maximum HP.\n We're just going to set this value at '100' by default.\n\n You may want to expand this to include various 'stats' that\n can be changed a... | A character able to participate in turn-based combat. Has attributes for current and maximum HP, and access to combat commands. | TBBasicCharacter | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TBBasicCharacter:
"""A character able to participate in turn-based combat. Has attributes for current and maximum HP, and access to combat commands."""
def at_object_creation(self):
"""Called once, when this object is first created. This is the normal hook to overload for most object... | stack_v2_sparse_classes_36k_train_003226 | 28,762 | permissive | [
{
"docstring": "Called once, when this object is first created. This is the normal hook to overload for most object types.",
"name": "at_object_creation",
"signature": "def at_object_creation(self)"
},
{
"docstring": "Called just before starting to move this object to destination. Args: destinat... | 2 | null | Implement the Python class `TBBasicCharacter` described below.
Class description:
A character able to participate in turn-based combat. Has attributes for current and maximum HP, and access to combat commands.
Method signatures and docstrings:
- def at_object_creation(self): Called once, when this object is first cre... | Implement the Python class `TBBasicCharacter` described below.
Class description:
A character able to participate in turn-based combat. Has attributes for current and maximum HP, and access to combat commands.
Method signatures and docstrings:
- def at_object_creation(self): Called once, when this object is first cre... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class TBBasicCharacter:
"""A character able to participate in turn-based combat. Has attributes for current and maximum HP, and access to combat commands."""
def at_object_creation(self):
"""Called once, when this object is first created. This is the normal hook to overload for most object... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TBBasicCharacter:
"""A character able to participate in turn-based combat. Has attributes for current and maximum HP, and access to combat commands."""
def at_object_creation(self):
"""Called once, when this object is first created. This is the normal hook to overload for most object types."""
... | the_stack_v2_python_sparse | evennia/contrib/game_systems/turnbattle/tb_basic.py | evennia/evennia | train | 1,781 |
40a15310b790c7932bcda06941d80f6183e8507f | [
"if not nums:\n return 0\nif len(nums) == 1:\n return nums[0]\nreturn max(self.rob1(nums[:-1]), self.rob1(nums[1:]))",
"size = len(num)\nif size == 0:\n return 0\nif size == 1:\n return num[0]\ndp = [0] * (size + 1)\ndp[0] = 0\ndp[1] = num[0]\nfor i in range(2, size + 1):\n dp[i] = max(dp[i - 1], d... | <|body_start_0|>
if not nums:
return 0
if len(nums) == 1:
return nums[0]
return max(self.rob1(nums[:-1]), self.rob1(nums[1:]))
<|end_body_0|>
<|body_start_1|>
size = len(num)
if size == 0:
return 0
if size == 1:
return num[... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob1(self, num):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
if len(nums) == 1:
... | stack_v2_sparse_classes_36k_train_003227 | 2,121 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob1",
"signature": "def rob1(self, num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009941 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob1(self, num): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob1(self, num): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
""... | fa638c7fda3802e9f4e0751a2c4c084edf09a441 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob1(self, num):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
if len(nums) == 1:
return nums[0]
return max(self.rob1(nums[:-1]), self.rob1(nums[1:]))
def rob1(self, num):
""":type nums: List[int] :rtype: int"""... | the_stack_v2_python_sparse | python/Dynamic Programming/213.House Robber II.py | EvanJamesMG/Leetcode | train | 5 | |
a67a7759a1fd7d8f4de0891e033b078c2fb0c7e9 | [
"self.gpu_id = gpu_id\nif self.gpu_id is not None and isinstance(self.gpu_id, int) and paddle.device.is_compiled_with_cuda():\n paddle.device.set_device('gpu:{}'.format(self.gpu_id))\nelse:\n paddle.device.set_device('cpu')\ncheckpoint = paddle.load(model_path)\nconfig = checkpoint['config']\nconfig['arch']['... | <|body_start_0|>
self.gpu_id = gpu_id
if self.gpu_id is not None and isinstance(self.gpu_id, int) and paddle.device.is_compiled_with_cuda():
paddle.device.set_device('gpu:{}'.format(self.gpu_id))
else:
paddle.device.set_device('cpu')
checkpoint = paddle.load(model... | PaddleModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaddleModel:
def __init__(self, model_path, post_p_thre=0.7, gpu_id=None):
"""初始化模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) :param gpu_id: 在哪一块gpu上运行"""
<|body_0|>
def predict(self, img_path: str, is_output_polygon=False, short_size: int=1024):
"""对传入的图像进行预测... | stack_v2_sparse_classes_36k_train_003228 | 6,575 | permissive | [
{
"docstring": "初始化模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) :param gpu_id: 在哪一块gpu上运行",
"name": "__init__",
"signature": "def __init__(self, model_path, post_p_thre=0.7, gpu_id=None)"
},
{
"docstring": "对传入的图像进行预测,支持图像地址,opecv 读取图片,偏慢 :param img_path: 图像地址 :param is_numpy: :return:",
... | 2 | stack_v2_sparse_classes_30k_train_006980 | Implement the Python class `PaddleModel` described below.
Class description:
Implement the PaddleModel class.
Method signatures and docstrings:
- def __init__(self, model_path, post_p_thre=0.7, gpu_id=None): 初始化模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) :param gpu_id: 在哪一块gpu上运行
- def predict(self, img_path:... | Implement the Python class `PaddleModel` described below.
Class description:
Implement the PaddleModel class.
Method signatures and docstrings:
- def __init__(self, model_path, post_p_thre=0.7, gpu_id=None): 初始化模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) :param gpu_id: 在哪一块gpu上运行
- def predict(self, img_path:... | 15963b0d242867a4cc4d76445626dc8965509b2f | <|skeleton|>
class PaddleModel:
def __init__(self, model_path, post_p_thre=0.7, gpu_id=None):
"""初始化模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) :param gpu_id: 在哪一块gpu上运行"""
<|body_0|>
def predict(self, img_path: str, is_output_polygon=False, short_size: int=1024):
"""对传入的图像进行预测... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaddleModel:
def __init__(self, model_path, post_p_thre=0.7, gpu_id=None):
"""初始化模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) :param gpu_id: 在哪一块gpu上运行"""
self.gpu_id = gpu_id
if self.gpu_id is not None and isinstance(self.gpu_id, int) and paddle.device.is_compiled_with_cuda():
... | the_stack_v2_python_sparse | benchmark/PaddleOCR_DBNet/tools/predict.py | PaddlePaddle/PaddleOCR | train | 34,195 | |
01a4ffadf11bb5a9c8fc53204007c26e67a1e7fc | [
"self.domain = 'a52.com'\nself.data = {}\nself.data.update(kwargs)",
"if source == 'db':\n return self._get_db_emails()\nelse:\n pass",
"emails = []\nsel = \"\\tselect\\n\\t\\t\\t\\t\\tea.uid,\\n\\t\\t\\t\\t\\tea.address,\\n\\t\\t\\t\\t\\tea.user_id,\\n\\t\\t\\t\\t\\tea.domain,\\n\\t\\t\\t\\t\\tea.first_n... | <|body_start_0|>
self.domain = 'a52.com'
self.data = {}
self.data.update(kwargs)
<|end_body_0|>
<|body_start_1|>
if source == 'db':
return self._get_db_emails()
else:
pass
<|end_body_1|>
<|body_start_2|>
emails = []
sel = "\tselect\n\t\t\... | MailingList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MailingList:
def __init__(self, **kwargs):
"""Mailing List Object"""
<|body_0|>
def get_emails(self, source='db'):
"""Get mailing lists assigned to the mailing list"""
<|body_1|>
def _get_db_emails(self):
"""Get emails for this mailing list from ... | stack_v2_sparse_classes_36k_train_003229 | 1,815 | no_license | [
{
"docstring": "Mailing List Object",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Get mailing lists assigned to the mailing list",
"name": "get_emails",
"signature": "def get_emails(self, source='db')"
},
{
"docstring": "Get emails for this ... | 3 | stack_v2_sparse_classes_30k_val_000743 | Implement the Python class `MailingList` described below.
Class description:
Implement the MailingList class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Mailing List Object
- def get_emails(self, source='db'): Get mailing lists assigned to the mailing list
- def _get_db_emails(self): Get emails... | Implement the Python class `MailingList` described below.
Class description:
Implement the MailingList class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Mailing List Object
- def get_emails(self, source='db'): Get mailing lists assigned to the mailing list
- def _get_db_emails(self): Get emails... | a8734fa74171d928b08cfe783fa0e02ac6185a4d | <|skeleton|>
class MailingList:
def __init__(self, **kwargs):
"""Mailing List Object"""
<|body_0|>
def get_emails(self, source='db'):
"""Get mailing lists assigned to the mailing list"""
<|body_1|>
def _get_db_emails(self):
"""Get emails for this mailing list from ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MailingList:
def __init__(self, **kwargs):
"""Mailing List Object"""
self.domain = 'a52.com'
self.data = {}
self.data.update(kwargs)
def get_emails(self, source='db'):
"""Get mailing lists assigned to the mailing list"""
if source == 'db':
retur... | the_stack_v2_python_sparse | MailingList/main.py | tommyhooper/legacy_python_utils | train | 0 | |
2dd1eb873ee7c948987c556dff2f51c15beb213f | [
"sha = SHA256.new()\nif not random_number:\n random_number = os.urandom(16)\nsha.update(random_number)\nsha.update(secret_passphrase)\nreturn (sha.digest(), random_number)",
"if data is None:\n return None\nif data == 'None':\n return None\nif len(data) == 0:\n return None\nmod_res = len(data) % 16\ni... | <|body_start_0|>
sha = SHA256.new()
if not random_number:
random_number = os.urandom(16)
sha.update(random_number)
sha.update(secret_passphrase)
return (sha.digest(), random_number)
<|end_body_0|>
<|body_start_1|>
if data is None:
return None
... | EncryptedField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncryptedField:
def __GetSHADigest(self, random_number=None):
"""This function returns a sha hash of the user's random number and the secret password."""
<|body_0|>
def encrypt(self, data):
"""Encrypts the data to be stored in the datastore"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_003230 | 2,091 | no_license | [
{
"docstring": "This function returns a sha hash of the user's random number and the secret password.",
"name": "__GetSHADigest",
"signature": "def __GetSHADigest(self, random_number=None)"
},
{
"docstring": "Encrypts the data to be stored in the datastore",
"name": "encrypt",
"signature... | 2 | stack_v2_sparse_classes_30k_test_000330 | Implement the Python class `EncryptedField` described below.
Class description:
Implement the EncryptedField class.
Method signatures and docstrings:
- def __GetSHADigest(self, random_number=None): This function returns a sha hash of the user's random number and the secret password.
- def encrypt(self, data): Encrypt... | Implement the Python class `EncryptedField` described below.
Class description:
Implement the EncryptedField class.
Method signatures and docstrings:
- def __GetSHADigest(self, random_number=None): This function returns a sha hash of the user's random number and the secret password.
- def encrypt(self, data): Encrypt... | b09e3247fd13ad00a88718fdb7e934b6691760fd | <|skeleton|>
class EncryptedField:
def __GetSHADigest(self, random_number=None):
"""This function returns a sha hash of the user's random number and the secret password."""
<|body_0|>
def encrypt(self, data):
"""Encrypts the data to be stored in the datastore"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncryptedField:
def __GetSHADigest(self, random_number=None):
"""This function returns a sha hash of the user's random number and the secret password."""
sha = SHA256.new()
if not random_number:
random_number = os.urandom(16)
sha.update(random_number)
sha.up... | the_stack_v2_python_sparse | mind-well/my_transform.py | danhooper/mindwell | train | 1 | |
91ed2256d5e7684918185c40e61204051f75266c | [
"for i in range(len(nums)):\n if nums[i] < nums[0]:\n return nums[i]\nreturn nums[0]",
"if len(nums) == 1 or nums[-1] > nums[0]:\n return nums[0]\nleft = 0\nright = len(nums) - 1\nwhile left < right:\n mid = (left + right) // 2\n if nums[mid] > nums[right]:\n left = mid + 1\n elif num... | <|body_start_0|>
for i in range(len(nums)):
if nums[i] < nums[0]:
return nums[i]
return nums[0]
<|end_body_0|>
<|body_start_1|>
if len(nums) == 1 or nums[-1] > nums[0]:
return nums[0]
left = 0
right = len(nums) - 1
while left < rig... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMin1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in range(len(nums)):
if nums[i] < ... | stack_v2_sparse_classes_36k_train_003231 | 1,261 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin1",
"signature": "def findMin1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin",
"signature": "def findMin(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin1(self, nums): :type nums: List[int] :rtype: int
- def findMin(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin1(self, nums): :type nums: List[int] :rtype: int
- def findMin(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def findMin1(self, num... | eedf73b5f167025a97f0905d3718b6eab2ee3e09 | <|skeleton|>
class Solution:
def findMin1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMin1(self, nums):
""":type nums: List[int] :rtype: int"""
for i in range(len(nums)):
if nums[i] < nums[0]:
return nums[i]
return nums[0]
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 1... | the_stack_v2_python_sparse | Array/154_Find_Minimum_in_Rotated_Sorted_Array_II.py | xiaomojie/LeetCode | train | 0 | |
62b0a3cff75728c12d5ea6044b95fd259cea29be | [
"self._location = location\nself._interactive_flows = interactive_flows or []\nself._preprocessors = preprocessors or []\nself._postprocessors = postprocessors or []\nself._plugins = plugins or []\nfor plugin in self._plugins:\n if plugin.interactive_flow:\n self._interactive_flows.append(plugin.interacti... | <|body_start_0|>
self._location = location
self._interactive_flows = interactive_flows or []
self._preprocessors = preprocessors or []
self._postprocessors = postprocessors or []
self._plugins = plugins or []
for plugin in self._plugins:
if plugin.interactive_... | A class for project generation based on cookiecutter template Attributes ---------- location: str Template location (git, mercurial, http(s), path) interactive_flows: Optional[List[InteractiveFlow]] An optional series of interactive questions to be asked to the user where the answers are used to fulfill the values of t... | Template | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Template:
"""A class for project generation based on cookiecutter template Attributes ---------- location: str Template location (git, mercurial, http(s), path) interactive_flows: Optional[List[InteractiveFlow]] An optional series of interactive questions to be asked to the user where the answers... | stack_v2_sparse_classes_36k_train_003232 | 9,214 | permissive | [
{
"docstring": "Initialize the class Parameters ---------- location: str Template location (git, mercurial, http(s), path) interactive_flows: Optional[List[InteractiveFlow]] An optional series of interactive questions to be asked to the user where the answers are used to fulfill the values of the cookiecutter.j... | 3 | null | Implement the Python class `Template` described below.
Class description:
A class for project generation based on cookiecutter template Attributes ---------- location: str Template location (git, mercurial, http(s), path) interactive_flows: Optional[List[InteractiveFlow]] An optional series of interactive questions to... | Implement the Python class `Template` described below.
Class description:
A class for project generation based on cookiecutter template Attributes ---------- location: str Template location (git, mercurial, http(s), path) interactive_flows: Optional[List[InteractiveFlow]] An optional series of interactive questions to... | b297ff015f2b69d7c74059c2d42ece1c29ea73ee | <|skeleton|>
class Template:
"""A class for project generation based on cookiecutter template Attributes ---------- location: str Template location (git, mercurial, http(s), path) interactive_flows: Optional[List[InteractiveFlow]] An optional series of interactive questions to be asked to the user where the answers... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Template:
"""A class for project generation based on cookiecutter template Attributes ---------- location: str Template location (git, mercurial, http(s), path) interactive_flows: Optional[List[InteractiveFlow]] An optional series of interactive questions to be asked to the user where the answers are used to ... | the_stack_v2_python_sparse | samcli/lib/cookiecutter/template.py | aws/aws-sam-cli | train | 1,402 |
4deb60a43cdf0d480ae614b0e67c28b0b242d8e0 | [
"if len(labels.shape) <= 2:\n return self._gather_unbatched(labels, match_indices, mask, mask_val)\nelif len(labels.shape) == 3:\n return self._gather_batched(labels, match_indices, mask, mask_val)\nelse:\n raise ValueError('`TargetGather` does not support `labels` with rank larger than 3, got {}'.format(l... | <|body_start_0|>
if len(labels.shape) <= 2:
return self._gather_unbatched(labels, match_indices, mask, mask_val)
elif len(labels.shape) == 3:
return self._gather_batched(labels, match_indices, mask, mask_val)
else:
raise ValueError('`TargetGather` does not sup... | Targer gather for dense object detector. | TargetGather | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TargetGather:
"""Targer gather for dense object detector."""
def __call__(self, labels, match_indices, mask=None, mask_val=0.0):
"""Labels anchors with ground truth inputs. B: batch_size N: number of groundtruth boxes. Args: labels: An integer tensor with shape [N, dims] or [B, N, ..... | stack_v2_sparse_classes_36k_train_003233 | 4,035 | permissive | [
{
"docstring": "Labels anchors with ground truth inputs. B: batch_size N: number of groundtruth boxes. Args: labels: An integer tensor with shape [N, dims] or [B, N, ...] representing groundtruth labels. match_indices: An integer tensor with shape [M] or [B, M] representing match label index. mask: An boolean t... | 3 | null | Implement the Python class `TargetGather` described below.
Class description:
Targer gather for dense object detector.
Method signatures and docstrings:
- def __call__(self, labels, match_indices, mask=None, mask_val=0.0): Labels anchors with ground truth inputs. B: batch_size N: number of groundtruth boxes. Args: la... | Implement the Python class `TargetGather` described below.
Class description:
Targer gather for dense object detector.
Method signatures and docstrings:
- def __call__(self, labels, match_indices, mask=None, mask_val=0.0): Labels anchors with ground truth inputs. B: batch_size N: number of groundtruth boxes. Args: la... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class TargetGather:
"""Targer gather for dense object detector."""
def __call__(self, labels, match_indices, mask=None, mask_val=0.0):
"""Labels anchors with ground truth inputs. B: batch_size N: number of groundtruth boxes. Args: labels: An integer tensor with shape [N, dims] or [B, N, ..... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TargetGather:
"""Targer gather for dense object detector."""
def __call__(self, labels, match_indices, mask=None, mask_val=0.0):
"""Labels anchors with ground truth inputs. B: batch_size N: number of groundtruth boxes. Args: labels: An integer tensor with shape [N, dims] or [B, N, ...] representi... | the_stack_v2_python_sparse | models/official/vision/keras_cv/ops/target_gather.py | aboerzel/German_License_Plate_Recognition | train | 34 |
70bc1997ebe1d638bb68e184e23626b1691aec92 | [
"if self.initial_extra:\n return 0\nelse:\n return forms.BaseInlineFormSet.initial_form_count(self)",
"if self.initial_extra:\n count = len(self.initial_extra) if self.initial_extra else 0\n count += self.extra\n return count\nelse:\n return forms.BaseInlineFormSet.total_form_count(self)"
] | <|body_start_0|>
if self.initial_extra:
return 0
else:
return forms.BaseInlineFormSet.initial_form_count(self)
<|end_body_0|>
<|body_start_1|>
if self.initial_extra:
count = len(self.initial_extra) if self.initial_extra else 0
count += self.extra
... | Custom formset that support initial data | CustomInlineFormset | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomInlineFormset:
"""Custom formset that support initial data"""
def initial_form_count(self):
"""set 0 to use initial_extra explicitly."""
<|body_0|>
def total_form_count(self):
"""here use the initial_extra len to determine needed forms"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_003234 | 7,933 | permissive | [
{
"docstring": "set 0 to use initial_extra explicitly.",
"name": "initial_form_count",
"signature": "def initial_form_count(self)"
},
{
"docstring": "here use the initial_extra len to determine needed forms",
"name": "total_form_count",
"signature": "def total_form_count(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001144 | Implement the Python class `CustomInlineFormset` described below.
Class description:
Custom formset that support initial data
Method signatures and docstrings:
- def initial_form_count(self): set 0 to use initial_extra explicitly.
- def total_form_count(self): here use the initial_extra len to determine needed forms | Implement the Python class `CustomInlineFormset` described below.
Class description:
Custom formset that support initial data
Method signatures and docstrings:
- def initial_form_count(self): set 0 to use initial_extra explicitly.
- def total_form_count(self): here use the initial_extra len to determine needed forms
... | 5367a8aed309fade0f17bc72efa099b0afc76aa7 | <|skeleton|>
class CustomInlineFormset:
"""Custom formset that support initial data"""
def initial_form_count(self):
"""set 0 to use initial_extra explicitly."""
<|body_0|>
def total_form_count(self):
"""here use the initial_extra len to determine needed forms"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomInlineFormset:
"""Custom formset that support initial data"""
def initial_form_count(self):
"""set 0 to use initial_extra explicitly."""
if self.initial_extra:
return 0
else:
return forms.BaseInlineFormSet.initial_form_count(self)
def total_form_... | the_stack_v2_python_sparse | mc2/controllers/base/forms.py | praekeltfoundation/mc2 | train | 0 |
2d2be295ae22ec7be495e9bebc28f5283928e949 | [
"self.significance = None\nself._decimalSeparator = decimalSeparator\nif decimalSeparator not in ['.', ',']:\n raise ValueError('invalid decimalSeparator: {}'.format(decimalSeparator))\nval = ''\nif default is not None and default != '':\n if not isinstance(default, (int, str, Decimal)):\n raise ValueE... | <|body_start_0|>
self.significance = None
self._decimalSeparator = decimalSeparator
if decimalSeparator not in ['.', ',']:
raise ValueError('invalid decimalSeparator: {}'.format(decimalSeparator))
val = ''
if default is not None and default != '':
if not i... | Edit widget for float values. | FloatEdit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloatEdit:
"""Edit widget for float values."""
def __init__(self, caption='', default=None, preserveSignificance=True, decimalSeparator='.'):
"""caption -- caption markup default -- default edit value preserveSignificance -- return value has the same signif. as default decimalSeparat... | stack_v2_sparse_classes_36k_train_003235 | 10,901 | permissive | [
{
"docstring": "caption -- caption markup default -- default edit value preserveSignificance -- return value has the same signif. as default decimalSeparator -- use '.' as separator by default, optionally a ',' >>> FloatEdit(u\"\", \"1.065434\") <FloatEdit selectable flow widget '1.065434' edit_pos=8> >>> e, si... | 2 | stack_v2_sparse_classes_30k_train_019498 | Implement the Python class `FloatEdit` described below.
Class description:
Edit widget for float values.
Method signatures and docstrings:
- def __init__(self, caption='', default=None, preserveSignificance=True, decimalSeparator='.'): caption -- caption markup default -- default edit value preserveSignificance -- re... | Implement the Python class `FloatEdit` described below.
Class description:
Edit widget for float values.
Method signatures and docstrings:
- def __init__(self, caption='', default=None, preserveSignificance=True, decimalSeparator='.'): caption -- caption markup default -- default edit value preserveSignificance -- re... | 95b7a061eabd6f2b607fba79e007186030f02720 | <|skeleton|>
class FloatEdit:
"""Edit widget for float values."""
def __init__(self, caption='', default=None, preserveSignificance=True, decimalSeparator='.'):
"""caption -- caption markup default -- default edit value preserveSignificance -- return value has the same signif. as default decimalSeparat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FloatEdit:
"""Edit widget for float values."""
def __init__(self, caption='', default=None, preserveSignificance=True, decimalSeparator='.'):
"""caption -- caption markup default -- default edit value preserveSignificance -- return value has the same signif. as default decimalSeparator -- use '.'... | the_stack_v2_python_sparse | Ricardo_OS/Python_backend/venv/lib/python3.8/site-packages/urwid/numedit.py | icl-rocketry/Avionics | train | 9 |
3a451d3eff90e90c67e63b2186b30a2b6645f943 | [
"super(NN, self).__init__()\nself.fc1 = nn.Linear(input_size, 50)\nself.fc2 = nn.Linear(50, num_classes)",
"x = F.relu(self.fc1(x))\nx = self.fc2(x)\nreturn x"
] | <|body_start_0|>
super(NN, self).__init__()
self.fc1 = nn.Linear(input_size, 50)
self.fc2 = nn.Linear(50, num_classes)
<|end_body_0|>
<|body_start_1|>
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
<|end_body_1|>
| NN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NN:
def __init__(self, input_size, num_classes):
"""Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (28x28) num_classes: the number of classes we want to predict, in this case 10 (0-9)"""
... | stack_v2_sparse_classes_36k_train_003236 | 5,621 | permissive | [
{
"docstring": "Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (28x28) num_classes: the number of classes we want to predict, in this case 10 (0-9)",
"name": "__init__",
"signature": "def __init__(self, input... | 2 | null | Implement the Python class `NN` described below.
Class description:
Implement the NN class.
Method signatures and docstrings:
- def __init__(self, input_size, num_classes): Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (2... | Implement the Python class `NN` described below.
Class description:
Implement the NN class.
Method signatures and docstrings:
- def __init__(self, input_size, num_classes): Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (2... | 558557c7989f0b10fee6e8d8f953d7269ae43d4f | <|skeleton|>
class NN:
def __init__(self, input_size, num_classes):
"""Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (28x28) num_classes: the number of classes we want to predict, in this case 10 (0-9)"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NN:
def __init__(self, input_size, num_classes):
"""Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (28x28) num_classes: the number of classes we want to predict, in this case 10 (0-9)"""
super(NN, s... | the_stack_v2_python_sparse | ML/Pytorch/Basics/pytorch_simple_fullynet.py | aladdinpersson/Machine-Learning-Collection | train | 5,653 | |
6fc4b746b192a737442735583c4009decb5234d3 | [
"if not root:\n return '[]'\nres = []\nqueue = collections.deque()\nqueue.append(root)\nwhile queue:\n node = queue.popleft()\n if node:\n res.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\n else:\n res.append('null')\nreturn '[' + ','.join(res) +... | <|body_start_0|>
if not root:
return '[]'
res = []
queue = collections.deque()
queue.append(root)
while queue:
node = queue.popleft()
if node:
res.append(str(node.val))
queue.append(node.left)
que... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def serialize(self, root):
"""类似于面试题32 :param root: 传入一棵树 :return: 返回字符串"""
<|body_0|>
def deserialize(self, data):
""":param data: 是一个字符串 :return: 返回一棵树"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return '[]'
... | stack_v2_sparse_classes_36k_train_003237 | 2,245 | no_license | [
{
"docstring": "类似于面试题32 :param root: 传入一棵树 :return: 返回字符串",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": ":param data: 是一个字符串 :return: 返回一棵树",
"name": "deserialize",
"signature": "def deserialize(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000126 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def serialize(self, root): 类似于面试题32 :param root: 传入一棵树 :return: 返回字符串
- def deserialize(self, data): :param data: 是一个字符串 :return: 返回一棵树 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def serialize(self, root): 类似于面试题32 :param root: 传入一棵树 :return: 返回字符串
- def deserialize(self, data): :param data: 是一个字符串 :return: 返回一棵树
<|skeleton|>
class Solution:
def ser... | f1bbd6b3197cd9ac4f0d35a37539c11b02272065 | <|skeleton|>
class Solution:
def serialize(self, root):
"""类似于面试题32 :param root: 传入一棵树 :return: 返回字符串"""
<|body_0|>
def deserialize(self, data):
""":param data: 是一个字符串 :return: 返回一棵树"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def serialize(self, root):
"""类似于面试题32 :param root: 传入一棵树 :return: 返回字符串"""
if not root:
return '[]'
res = []
queue = collections.deque()
queue.append(root)
while queue:
node = queue.popleft()
if node:
... | the_stack_v2_python_sparse | offer/树/37. 序列化二叉树/Codec.py | guohaoyuan/algorithms-for-work | train | 2 | |
3f0895d61a88bf95f9a735b81ae22a28666e2003 | [
"preserve_exceptions_and_events(mock_events)\nuser = User(1234, 'foo@bar.baz')\nmock_events.load.return_value = (Submission(creator=user, owner=user, created=datetime.now(UTC)), [CreateSubmission(creator=user)])\ncontent, status_code, headers = submission.get_submission(1)\nself.assertEqual(mock_events.load.call_co... | <|body_start_0|>
preserve_exceptions_and_events(mock_events)
user = User(1234, 'foo@bar.baz')
mock_events.load.return_value = (Submission(creator=user, owner=user, created=datetime.now(UTC)), [CreateSubmission(creator=user)])
content, status_code, headers = submission.get_submission(1)
... | Tests for :func:`.submission.get_submission`. | TestGetSubmission | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGetSubmission:
"""Tests for :func:`.submission.get_submission`."""
def test_get_submission(self, mock_events):
"""Should return a JSON-serializable dict if submisison exists."""
<|body_0|>
def test_get_nonexistant_submission(self, mock_events):
"""Should rais... | stack_v2_sparse_classes_36k_train_003238 | 11,936 | permissive | [
{
"docstring": "Should return a JSON-serializable dict if submisison exists.",
"name": "test_get_submission",
"signature": "def test_get_submission(self, mock_events)"
},
{
"docstring": "Should raise NotFound if the submission does not exist.",
"name": "test_get_nonexistant_submission",
... | 2 | stack_v2_sparse_classes_30k_train_011735 | Implement the Python class `TestGetSubmission` described below.
Class description:
Tests for :func:`.submission.get_submission`.
Method signatures and docstrings:
- def test_get_submission(self, mock_events): Should return a JSON-serializable dict if submisison exists.
- def test_get_nonexistant_submission(self, mock... | Implement the Python class `TestGetSubmission` described below.
Class description:
Tests for :func:`.submission.get_submission`.
Method signatures and docstrings:
- def test_get_submission(self, mock_events): Should return a JSON-serializable dict if submisison exists.
- def test_get_nonexistant_submission(self, mock... | 6077ce4e0685d67ce7010800083a898857158112 | <|skeleton|>
class TestGetSubmission:
"""Tests for :func:`.submission.get_submission`."""
def test_get_submission(self, mock_events):
"""Should return a JSON-serializable dict if submisison exists."""
<|body_0|>
def test_get_nonexistant_submission(self, mock_events):
"""Should rais... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestGetSubmission:
"""Tests for :func:`.submission.get_submission`."""
def test_get_submission(self, mock_events):
"""Should return a JSON-serializable dict if submisison exists."""
preserve_exceptions_and_events(mock_events)
user = User(1234, 'foo@bar.baz')
mock_events.lo... | the_stack_v2_python_sparse | metadata/metadata/controllers/submission/tests.py | arXiv/arxiv-submission-core | train | 14 |
27ac0cce22afcade77a5078ee9035ba676d7a408 | [
"self.nums = nums\nself.quickSort(nums, 0, len(nums) - 1)\nreturn nums[-k]",
"if start < end:\n i, j = (start, end)\n base = nums[i]\n while i < j:\n while i < j and nums[j] >= base:\n j -= 1\n nums[i] = nums[j]\n while i < j and nums[i] <= base:\n i += 1\n ... | <|body_start_0|>
self.nums = nums
self.quickSort(nums, 0, len(nums) - 1)
return nums[-k]
<|end_body_0|>
<|body_start_1|>
if start < end:
i, j = (start, end)
base = nums[i]
while i < j:
while i < j and nums[j] >= base:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
"""单纯的快排"""
<|body_0|>
def quickSort(self, nums, start, end):
"""快排"""
<|body_1|>
def findKthLargest1(self, nums, k):
"""借助快排的思想"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.n... | stack_v2_sparse_classes_36k_train_003239 | 1,646 | no_license | [
{
"docstring": "单纯的快排",
"name": "findKthLargest",
"signature": "def findKthLargest(self, nums, k)"
},
{
"docstring": "快排",
"name": "quickSort",
"signature": "def quickSort(self, nums, start, end)"
},
{
"docstring": "借助快排的思想",
"name": "findKthLargest1",
"signature": "def f... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): 单纯的快排
- def quickSort(self, nums, start, end): 快排
- def findKthLargest1(self, nums, k): 借助快排的思想 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): 单纯的快排
- def quickSort(self, nums, start, end): 快排
- def findKthLargest1(self, nums, k): 借助快排的思想
<|skeleton|>
class Solution:
def findKthL... | a3872425745425f8ca960840120f06de4a8370bb | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
"""单纯的快排"""
<|body_0|>
def quickSort(self, nums, start, end):
"""快排"""
<|body_1|>
def findKthLargest1(self, nums, k):
"""借助快排的思想"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findKthLargest(self, nums, k):
"""单纯的快排"""
self.nums = nums
self.quickSort(nums, 0, len(nums) - 1)
return nums[-k]
def quickSort(self, nums, start, end):
"""快排"""
if start < end:
i, j = (start, end)
base = nums[i]
... | the_stack_v2_python_sparse | leetcode_数组中的第K个最大元素.py | xiaozuo7/algorithm_python | train | 1 | |
18351b102250c725708807d91ec94f88fba7a31f | [
"from collections import Counter\ncounter = Counter(s)\nodd = 0\nfor value in counter.values():\n if value % 2 == 1:\n odd += 1\n if odd > 1:\n return False\nreturn True",
"cur = []\nfor char in s:\n if char in cur:\n cur.remove(char)\n else:\n cur.append(char)\nreturn len(... | <|body_start_0|>
from collections import Counter
counter = Counter(s)
odd = 0
for value in counter.values():
if value % 2 == 1:
odd += 1
if odd > 1:
return False
return True
<|end_body_0|>
<|body_start_1|>
cur = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
"""借助hashmap数据结构"""
<|body_0|>
def canPermutePalindrome_2(self, s: str) -> bool:
"""借助数组"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from collections import Counter
counter = Coun... | stack_v2_sparse_classes_36k_train_003240 | 1,670 | no_license | [
{
"docstring": "借助hashmap数据结构",
"name": "canPermutePalindrome",
"signature": "def canPermutePalindrome(self, s: str) -> bool"
},
{
"docstring": "借助数组",
"name": "canPermutePalindrome_2",
"signature": "def canPermutePalindrome_2(self, s: str) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_000636 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPermutePalindrome(self, s: str) -> bool: 借助hashmap数据结构
- def canPermutePalindrome_2(self, s: str) -> bool: 借助数组 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPermutePalindrome(self, s: str) -> bool: 借助hashmap数据结构
- def canPermutePalindrome_2(self, s: str) -> bool: 借助数组
<|skeleton|>
class Solution:
def canPermutePalindrome... | 13e7ec9fe7a92ab13b247bd4edeb1ada5de81a08 | <|skeleton|>
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
"""借助hashmap数据结构"""
<|body_0|>
def canPermutePalindrome_2(self, s: str) -> bool:
"""借助数组"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canPermutePalindrome(self, s: str) -> bool:
"""借助hashmap数据结构"""
from collections import Counter
counter = Counter(s)
odd = 0
for value in counter.values():
if value % 2 == 1:
odd += 1
if odd > 1:
retu... | the_stack_v2_python_sparse | Interview/01_04.py | lirui-ML/my_leetcode | train | 1 | |
ea8ad6ff1c8eb443684dcf7e4ba8e560c1242348 | [
"serializer = self.get_serializer_class(request.data)\nif serializer.is_valid():\n mp = serializer.save()\n res = self.get_rate_quote_results(mp)\n if res.status_code == 400:\n return response.Response(res.data, status=status.HTTP_400_BAD_REQUEST)\n uuid = res.data.get('request_uuid')\n self.r... | <|body_start_0|>
serializer = self.get_serializer_class(request.data)
if serializer.is_valid():
mp = serializer.save()
res = self.get_rate_quote_results(mp)
if res.status_code == 400:
return response.Response(res.data, status=status.HTTP_400_BAD_REQUES... | View for handling requests for rate quotes. Creates `MortgageProfile` from inbound request data. | RateQuoteRequestView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RateQuoteRequestView:
"""View for handling requests for rate quotes. Creates `MortgageProfile` from inbound request data."""
def post(self, request, *args, **kwargs):
"""Takes a POST request from external partner websites to return rate quote results to the consumer portal. - Minimum... | stack_v2_sparse_classes_36k_train_003241 | 14,021 | no_license | [
{
"docstring": "Takes a POST request from external partner websites to return rate quote results to the consumer portal. - Minimum fields required:: * Purchase: kind, property_state, property_value, purchase_downpayment, credit_score, property_occupation * Refi: kind, property_state, property_value, property_oc... | 2 | stack_v2_sparse_classes_30k_train_005927 | Implement the Python class `RateQuoteRequestView` described below.
Class description:
View for handling requests for rate quotes. Creates `MortgageProfile` from inbound request data.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Takes a POST request from external partner websites to re... | Implement the Python class `RateQuoteRequestView` described below.
Class description:
View for handling requests for rate quotes. Creates `MortgageProfile` from inbound request data.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Takes a POST request from external partner websites to re... | f1a8cd8268d032ea8321e1588e226da09925b7aa | <|skeleton|>
class RateQuoteRequestView:
"""View for handling requests for rate quotes. Creates `MortgageProfile` from inbound request data."""
def post(self, request, *args, **kwargs):
"""Takes a POST request from external partner websites to return rate quote results to the consumer portal. - Minimum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RateQuoteRequestView:
"""View for handling requests for rate quotes. Creates `MortgageProfile` from inbound request data."""
def post(self, request, *args, **kwargs):
"""Takes a POST request from external partner websites to return rate quote results to the consumer portal. - Minimum fields requi... | the_stack_v2_python_sparse | website/apps/mortgage_profiles/views.py | protoprojects/worksample | train | 0 |
bb8e704eca90eb49930b6fb10bf9bd4924c87959 | [
"self.serial_devname = serial_devname\nproxy_prompt = '{}>'.format(serial_devname)\nsuper(PlinkSerial, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, expected_prompt=proxy_prompt, target_newline=target_newline, runner=runner)\nself.ret_required = False\nself._python_shell_exit_sen... | <|body_start_0|>
self.serial_devname = serial_devname
proxy_prompt = '{}>'.format(serial_devname)
super(PlinkSerial, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, expected_prompt=proxy_prompt, target_newline=target_newline, runner=runner)
self.ret_requ... | PlinkSerial | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlinkSerial:
def __init__(self, connection, serial_devname, prompt=None, newline_chars=None, target_newline='\n', runner=None):
""":param connection: Moler connection to device, terminal when command is executed. :param serial_devname: name of serial device to be proxied (f.ex. COM5, tty... | stack_v2_sparse_classes_36k_train_003242 | 3,590 | permissive | [
{
"docstring": ":param connection: Moler connection to device, terminal when command is executed. :param serial_devname: name of serial device to be proxied (f.ex. COM5, ttyS4). :param prompt: prompt where we start from :param newline_chars: Characters to split local lines - list. :param target_newline: Charact... | 4 | stack_v2_sparse_classes_30k_train_019237 | Implement the Python class `PlinkSerial` described below.
Class description:
Implement the PlinkSerial class.
Method signatures and docstrings:
- def __init__(self, connection, serial_devname, prompt=None, newline_chars=None, target_newline='\n', runner=None): :param connection: Moler connection to device, terminal w... | Implement the Python class `PlinkSerial` described below.
Class description:
Implement the PlinkSerial class.
Method signatures and docstrings:
- def __init__(self, connection, serial_devname, prompt=None, newline_chars=None, target_newline='\n', runner=None): :param connection: Moler connection to device, terminal w... | 5a7bb06807b6e0124c77040367d0c20f42849a4c | <|skeleton|>
class PlinkSerial:
def __init__(self, connection, serial_devname, prompt=None, newline_chars=None, target_newline='\n', runner=None):
""":param connection: Moler connection to device, terminal when command is executed. :param serial_devname: name of serial device to be proxied (f.ex. COM5, tty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlinkSerial:
def __init__(self, connection, serial_devname, prompt=None, newline_chars=None, target_newline='\n', runner=None):
""":param connection: Moler connection to device, terminal when command is executed. :param serial_devname: name of serial device to be proxied (f.ex. COM5, ttyS4). :param pr... | the_stack_v2_python_sparse | moler/cmd/at/plink_serial.py | nokia/moler | train | 60 | |
6eb255acc9ff492d4bfd8b8f40088ee95315c82e | [
"n = len(s)\nstart1, start2 = (0, n - 1)\ncur_len, max_len, end_index = (0, 0, 0)\nwhile start1 <= n - 1 or start2 > 0:\n count = min(n - start1, n - start2)\n for i in range(count):\n if s[start1 + i] == s[-1 - start2 - i]:\n cur_len += 1\n else:\n if cur_len > max_len and... | <|body_start_0|>
n = len(s)
start1, start2 = (0, n - 1)
cur_len, max_len, end_index = (0, 0, 0)
while start1 <= n - 1 or start2 > 0:
count = min(n - start1, n - start2)
for i in range(count):
if s[start1 + i] == s[-1 - start2 - i]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome1(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(s)
start1, start2 = (0, n - 1)
c... | stack_v2_sparse_classes_36k_train_003243 | 3,585 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome1",
"signature": "def longestPalindrome1(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome1(self, s): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome1(self, s): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def longestPalindrome1(sel... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def longestPalindrome1(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome1(self, s):
""":type s: str :rtype: str"""
n = len(s)
start1, start2 = (0, n - 1)
cur_len, max_len, end_index = (0, 0, 0)
while start1 <= n - 1 or start2 > 0:
count = min(n - start1, n - start2)
for i in range(count... | the_stack_v2_python_sparse | String/q005_longest_palindromic_substring.py | sevenhe716/LeetCode | train | 0 | |
245e26466fbd216eda585cfef1abd3c865c92162 | [
"super(AggregatorMetric, self).__init__(env, realign_fn)\nself.selection_fn = selection_fn\nself.stratify_fn = stratify_fn or (lambda x: 1)\nself.modifier_fn = modifier_fn or (lambda x, y, z: x)\nself.calc_mean = calc_mean",
"sum_aggregate_result = collections.defaultdict(int)\ngroup_count_result = collections.de... | <|body_start_0|>
super(AggregatorMetric, self).__init__(env, realign_fn)
self.selection_fn = selection_fn
self.stratify_fn = stratify_fn or (lambda x: 1)
self.modifier_fn = modifier_fn or (lambda x, y, z: x)
self.calc_mean = calc_mean
<|end_body_0|>
<|body_start_1|>
sum_... | Metric that modifies and aggregates an env state variable. This metric can be used to calculate any value that needs to be aggregated in sum or mean over the entire history by applying some modifications to the env state variable based on group-id. For instance, to calculate costs for each group, we might have differen... | AggregatorMetric | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AggregatorMetric:
"""Metric that modifies and aggregates an env state variable. This metric can be used to calculate any value that needs to be aggregated in sum or mean over the entire history by applying some modifications to the env state variable based on group-id. For instance, to calculate ... | stack_v2_sparse_classes_36k_train_003244 | 7,087 | permissive | [
{
"docstring": "Initializes the metric. Args: env: A `core.FairnessEnv`. selection_fn: Returns a state variable which needs to be modified and aggregated. stratify_fn: A function that takes a (state, action) pair and returns a stratum-id to collect together pairs. By default (None), all examples are in a single... | 2 | stack_v2_sparse_classes_30k_train_001214 | Implement the Python class `AggregatorMetric` described below.
Class description:
Metric that modifies and aggregates an env state variable. This metric can be used to calculate any value that needs to be aggregated in sum or mean over the entire history by applying some modifications to the env state variable based o... | Implement the Python class `AggregatorMetric` described below.
Class description:
Metric that modifies and aggregates an env state variable. This metric can be used to calculate any value that needs to be aggregated in sum or mean over the entire history by applying some modifications to the env state variable based o... | 38eaf4514062892e0c3ce5d7cff4b4c1a7e49242 | <|skeleton|>
class AggregatorMetric:
"""Metric that modifies and aggregates an env state variable. This metric can be used to calculate any value that needs to be aggregated in sum or mean over the entire history by applying some modifications to the env state variable based on group-id. For instance, to calculate ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AggregatorMetric:
"""Metric that modifies and aggregates an env state variable. This metric can be used to calculate any value that needs to be aggregated in sum or mean over the entire history by applying some modifications to the env state variable based on group-id. For instance, to calculate costs for eac... | the_stack_v2_python_sparse | metrics/value_tracking_metrics.py | google/ml-fairness-gym | train | 310 |
e2063b4154f217d2ff5041f56af8865f22ccaa65 | [
"challenges: List[Dict[str, Any]] = []\nchallenges = MiscellaneousChallenges.Table(self, challenges)\nUtility.WriteFile(self, f'{self.eXAssets}/miscChallenges.json', challenges)\nlog.info(f'Compiled {len(challenges):,} Miscellaneous Challenges')",
"table: List[Dict[str, Any]] = Utility.ReadCSV(self, f'{self.iXAss... | <|body_start_0|>
challenges: List[Dict[str, Any]] = []
challenges = MiscellaneousChallenges.Table(self, challenges)
Utility.WriteFile(self, f'{self.eXAssets}/miscChallenges.json', challenges)
log.info(f'Compiled {len(challenges):,} Miscellaneous Challenges')
<|end_body_0|>
<|body_start_... | Miscellaneous Challenges XAssets. | MiscellaneousChallenges | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MiscellaneousChallenges:
"""Miscellaneous Challenges XAssets."""
def Compile(self: Any) -> None:
"""Compile the Miscellaneous Challenges XAssets."""
<|body_0|>
def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the misc_cha... | stack_v2_sparse_classes_36k_train_003245 | 13,794 | permissive | [
{
"docstring": "Compile the Miscellaneous Challenges XAssets.",
"name": "Compile",
"signature": "def Compile(self: Any) -> None"
},
{
"docstring": "Compile the misc_challenges.csv XAsset.",
"name": "Table",
"signature": "def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict... | 2 | stack_v2_sparse_classes_30k_train_016638 | Implement the Python class `MiscellaneousChallenges` described below.
Class description:
Miscellaneous Challenges XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Miscellaneous Challenges XAssets.
- def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:... | Implement the Python class `MiscellaneousChallenges` described below.
Class description:
Miscellaneous Challenges XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Miscellaneous Challenges XAssets.
- def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:... | 82d3198a64eb2905e96dd536ce2f0acb52f9ce77 | <|skeleton|>
class MiscellaneousChallenges:
"""Miscellaneous Challenges XAssets."""
def Compile(self: Any) -> None:
"""Compile the Miscellaneous Challenges XAssets."""
<|body_0|>
def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the misc_cha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MiscellaneousChallenges:
"""Miscellaneous Challenges XAssets."""
def Compile(self: Any) -> None:
"""Compile the Miscellaneous Challenges XAssets."""
challenges: List[Dict[str, Any]] = []
challenges = MiscellaneousChallenges.Table(self, challenges)
Utility.WriteFile(self, f... | the_stack_v2_python_sparse | ModernWarfare/XAssets/challenges.py | dbuentello/Hyde | train | 0 |
5f463645a680afdcb3f01fb2d7c4f4317bf52f9d | [
"self.m = torch.zeros(shape, dtype=data_type).cuda()\nself.v = torch.zeros(shape, dtype=data_type).cuda()\nself.t = 0\nself._beta1 = beta1\nself._beta2 = beta2\nself._learning_rate = learning_rate\nself._epsilon = epsilon",
"self.t += 1\nself.m = self._beta1 * self.m + (1 - self._beta1) * gradient\nself.v = self.... | <|body_start_0|>
self.m = torch.zeros(shape, dtype=data_type).cuda()
self.v = torch.zeros(shape, dtype=data_type).cuda()
self.t = 0
self._beta1 = beta1
self._beta2 = beta2
self._learning_rate = learning_rate
self._epsilon = epsilon
<|end_body_0|>
<|body_start_1|>... | Basic Adam optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized | AdamOptimizer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdamOptimizer:
"""Basic Adam optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized"""
def __init__(self, shape, data_type, learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-07):... | stack_v2_sparse_classes_36k_train_003246 | 5,641 | permissive | [
{
"docstring": "Updates internal parameters of the optimizer and returns the change that should be applied to the variable. Parameters ---------- shape : tuple the shape of the image learning_rate: float the learning rate in the current iteration beta1: float decay rate for calculating the exponentially decayin... | 2 | stack_v2_sparse_classes_30k_train_001099 | Implement the Python class `AdamOptimizer` described below.
Class description:
Basic Adam optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized
Method signatures and docstrings:
- def __init__(self, shap... | Implement the Python class `AdamOptimizer` described below.
Class description:
Basic Adam optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized
Method signatures and docstrings:
- def __init__(self, shap... | 0e38d26cf6e082baf4de89d0cdfece6ba15573eb | <|skeleton|>
class AdamOptimizer:
"""Basic Adam optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized"""
def __init__(self, shape, data_type, learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-07):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdamOptimizer:
"""Basic Adam optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized"""
def __init__(self, shape, data_type, learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-07):
"""U... | the_stack_v2_python_sparse | code/attacks/spsa/validate_spsa_pytorch.py | davidwagner/bagnet-patch-defense | train | 1 |
09ceeff88db61da4ecf6a84878bedc5302bdf39a | [
"if self.request.version == 'v6':\n return IngestDetailsSerializerV6\nelif self.request.version == 'v7':\n return IngestDetailsSerializerV6",
"if request.version == 'v6' or request.version == 'v7':\n return self.retrieve_v6(request, ingest_id)\nraise Http404()",
"try:\n is_staff = False\n if requ... | <|body_start_0|>
if self.request.version == 'v6':
return IngestDetailsSerializerV6
elif self.request.version == 'v7':
return IngestDetailsSerializerV6
<|end_body_0|>
<|body_start_1|>
if request.version == 'v6' or request.version == 'v7':
return self.retrieve_... | This view is the endpoint for retrieving/updating details of an ingest. | IngestDetailsView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IngestDetailsView:
"""This view is the endpoint for retrieving/updating details of an ingest."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
<|body_0|>
def retrieve(self, request, ingest_id=None,... | stack_v2_sparse_classes_36k_train_003247 | 30,689 | permissive | [
{
"docstring": "Returns the appropriate serializer based off the requests version of the REST API",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Determine api version and call specific method :param request: the HTTP GET request :type request: ... | 3 | stack_v2_sparse_classes_30k_train_010447 | Implement the Python class `IngestDetailsView` described below.
Class description:
This view is the endpoint for retrieving/updating details of an ingest.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def retriev... | Implement the Python class `IngestDetailsView` described below.
Class description:
This view is the endpoint for retrieving/updating details of an ingest.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def retriev... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class IngestDetailsView:
"""This view is the endpoint for retrieving/updating details of an ingest."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
<|body_0|>
def retrieve(self, request, ingest_id=None,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IngestDetailsView:
"""This view is the endpoint for retrieving/updating details of an ingest."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
if self.request.version == 'v6':
return IngestDetailsSeriali... | the_stack_v2_python_sparse | scale/ingest/views.py | kfconsultant/scale | train | 0 |
d14738842ace94d36e9deb10ec66db2580f6625c | [
"res = []\nif not root:\n return res\nqueue = collections.deque()\nqueue.append(root)\nlost_num_index = 0\nwhile queue:\n cur_node = queue.popleft()\n if not cur_node:\n res.append(cur_node)\n continue\n res.append(cur_node.val)\n lost_num_index = len(res)\n queue.append(cur_node.lef... | <|body_start_0|>
res = []
if not root:
return res
queue = collections.deque()
queue.append(root)
lost_num_index = 0
while queue:
cur_node = queue.popleft()
if not cur_node:
res.append(cur_node)
continue
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_003248 | 2,084 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_011757 | 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:... | f43d70cac56bdf6377b22b865174af822902ff78 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = []
if not root:
return res
queue = collections.deque()
queue.append(root)
lost_num_index = 0
while queue:
cur_node =... | the_stack_v2_python_sparse | 剑指offer/序列化二叉树.py | ltzp/LeetCode | train | 0 | |
d1742ec12dc4bb8a2f78e3cb02a4f54815bdfcbc | [
"class AMessage(messages.Message):\n pass\nmessage_descriptor = descriptor.describe_message(AMessage)\nmessage_class = definition.define_message(message_descriptor, '__main__')\nself.assertEquals('AMessage', message_class.__name__)\nself.assertEquals('__main__', message_class.__module__)\nself.assertEquals(messa... | <|body_start_0|>
class AMessage(messages.Message):
pass
message_descriptor = descriptor.describe_message(AMessage)
message_class = definition.define_message(message_descriptor, '__main__')
self.assertEquals('AMessage', message_class.__name__)
self.assertEquals('__main... | Test for define_message. | DefineMessageTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefineMessageTest:
"""Test for define_message."""
def testDefineMessageEmpty(self):
"""Test definition a message with no fields or enums."""
<|body_0|>
def testDefineMessageEnumOnly(self):
"""Test definition a message with only enums."""
<|body_1|>
d... | stack_v2_sparse_classes_36k_train_003249 | 23,499 | permissive | [
{
"docstring": "Test definition a message with no fields or enums.",
"name": "testDefineMessageEmpty",
"signature": "def testDefineMessageEmpty(self)"
},
{
"docstring": "Test definition a message with only enums.",
"name": "testDefineMessageEnumOnly",
"signature": "def testDefineMessageE... | 4 | stack_v2_sparse_classes_30k_train_005066 | Implement the Python class `DefineMessageTest` described below.
Class description:
Test for define_message.
Method signatures and docstrings:
- def testDefineMessageEmpty(self): Test definition a message with no fields or enums.
- def testDefineMessageEnumOnly(self): Test definition a message with only enums.
- def t... | Implement the Python class `DefineMessageTest` described below.
Class description:
Test for define_message.
Method signatures and docstrings:
- def testDefineMessageEmpty(self): Test definition a message with no fields or enums.
- def testDefineMessageEnumOnly(self): Test definition a message with only enums.
- def t... | 2cb4493d796746cb46c8519a100ef3ef128a761a | <|skeleton|>
class DefineMessageTest:
"""Test for define_message."""
def testDefineMessageEmpty(self):
"""Test definition a message with no fields or enums."""
<|body_0|>
def testDefineMessageEnumOnly(self):
"""Test definition a message with only enums."""
<|body_1|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefineMessageTest:
"""Test for define_message."""
def testDefineMessageEmpty(self):
"""Test definition a message with no fields or enums."""
class AMessage(messages.Message):
pass
message_descriptor = descriptor.describe_message(AMessage)
message_class = defini... | the_stack_v2_python_sparse | src/lib/protorpc/definition_test.py | thonkify/thonkify | train | 17 |
91bc920380f815839d84305009957d00eeb0bbb5 | [
"if n <= 1:\n return head\nprev = head\nm = n\nprint('Find Tail')\nwhile m >= 1:\n print('prev.val = ', prev.val)\n prev = prev.next\n m -= 1\ncur = head\nprint('Reverse Start')\nwhile n >= 1:\n print('cur.val = ', cur.val)\n tail = cur.next\n cur.next = prev\n prev = cur\n cur = tail\n ... | <|body_start_0|>
if n <= 1:
return head
prev = head
m = n
print('Find Tail')
while m >= 1:
print('prev.val = ', prev.val)
prev = prev.next
m -= 1
cur = head
print('Reverse Start')
while n >= 1:
pr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseToN(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def reverseBetween(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_003250 | 1,461 | no_license | [
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "reverseToN",
"signature": "def reverseToN(self, head, n)"
},
{
"docstring": ":type head: ListNode :type m: int :type n: int :rtype: ListNode",
"name": "reverseBetween",
"signature": "def reverseBetween(self, he... | 2 | stack_v2_sparse_classes_30k_val_000933 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseToN(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def reverseBetween(self, head, m, n): :type head: ListNode :type m: int :type n: int :rtype: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseToN(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def reverseBetween(self, head, m, n): :type head: ListNode :type m: int :type n: int :rtype: L... | f8b35179b980e55f61bbcd2631fa3a9bf30c40ec | <|skeleton|>
class Solution:
def reverseToN(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def reverseBetween(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseToN(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
if n <= 1:
return head
prev = head
m = n
print('Find Tail')
while m >= 1:
print('prev.val = ', prev.val)
prev = prev.next
... | the_stack_v2_python_sparse | Python Solutions/092 Reverse Linked List II.py | Sue9/Leetcode | train | 0 | |
4e2a7659b3b97cda44731ce5fd901742d2d6a44c | [
"if operations not in ['f', 'b', 'fb', 'bf']:\n raise ValueError(\"'operations' parameter should be one of the following options: f, b, fb, bf.\")\nself.feature = next(self._parse_features(feature)())\nself.operations = operations\nself.value = value\nself.axis = axis",
"if not isinstance(data, np.ndarray) or ... | <|body_start_0|>
if operations not in ['f', 'b', 'fb', 'bf']:
raise ValueError("'operations' parameter should be one of the following options: f, b, fb, bf.")
self.feature = next(self._parse_features(feature)())
self.operations = operations
self.value = value
self.axi... | Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, nan, 8, 5, 5, 1, 0, 0, 0 'b': nan, nan, nan, ... | ValueFilloutTask | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueFilloutTask:
"""Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, n... | stack_v2_sparse_classes_36k_train_003251 | 8,688 | permissive | [
{
"docstring": ":param feature: A feature that must be value-filled. :type feature: an object supported by the :class:`FeatureParser<eolearn.core.utilities.FeatureParser>` :param operations: Fill directions, which should be one of ['f', 'b', 'fb', 'bf']. :type operations: str :param value: Which value to fill b... | 3 | stack_v2_sparse_classes_30k_train_004954 | Implement the Python class `ValueFilloutTask` described below.
Class description:
Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8... | Implement the Python class `ValueFilloutTask` described below.
Class description:
Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8... | 148189e2b92e06059b87f223b596255ccafac86d | <|skeleton|>
class ValueFilloutTask:
"""Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValueFilloutTask:
"""Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, nan, 8, 5, 5, ... | the_stack_v2_python_sparse | features/eolearn/features/feature_manipulation.py | wouellette/eo-learn | train | 2 |
db9788aaa0ae45006e2157243c4972c3fd065ad0 | [
"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.emailFileAssessmentRequest'.casefold():\n ... | <|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() ==... | ThreatAssessmentRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreatAssessmentRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ThreatAssessmentRequest:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and creat... | stack_v2_sparse_classes_36k_train_003252 | 7,669 | 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: ThreatAssessmentRequest",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimin... | 3 | stack_v2_sparse_classes_30k_train_007377 | Implement the Python class `ThreatAssessmentRequest` described below.
Class description:
Implement the ThreatAssessmentRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ThreatAssessmentRequest: Creates a new instance of the appropriate clas... | Implement the Python class `ThreatAssessmentRequest` described below.
Class description:
Implement the ThreatAssessmentRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ThreatAssessmentRequest: Creates a new instance of the appropriate clas... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ThreatAssessmentRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ThreatAssessmentRequest:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and creat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreatAssessmentRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ThreatAssessmentRequest:
"""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 R... | the_stack_v2_python_sparse | msgraph/generated/models/threat_assessment_request.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
ba3a5f1c9813e9546e496c36725bcad3ed6aa44c | [
"self.cycletime = '20190711T1200Z'\nvalidity_time = datetime(2019, 7, 11, 14)\nself.cube_early = set_up_variable_cube(np.full((4, 4), 273.15, dtype=np.float32), time=validity_time, frt=datetime(2019, 7, 11, 9))\nself.cube_late = set_up_variable_cube(np.full((4, 4), 273.15, dtype=np.float32), time=validity_time, frt... | <|body_start_0|>
self.cycletime = '20190711T1200Z'
validity_time = datetime(2019, 7, 11, 14)
self.cube_early = set_up_variable_cube(np.full((4, 4), 273.15, dtype=np.float32), time=validity_time, frt=datetime(2019, 7, 11, 9))
self.cube_late = set_up_variable_cube(np.full((4, 4), 273.15, d... | Test the rebadge_forecasts_as_latest_cycle function | Test_rebadge_forecasts_as_latest_cycle | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_rebadge_forecasts_as_latest_cycle:
"""Test the rebadge_forecasts_as_latest_cycle function"""
def setUp(self):
"""Set up some cubes with different cycle times"""
<|body_0|>
def test_cubelist(self):
"""Test a list of cubes is returned with the latest frt"""
... | stack_v2_sparse_classes_36k_train_003253 | 20,564 | permissive | [
{
"docstring": "Set up some cubes with different cycle times",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test a list of cubes is returned with the latest frt",
"name": "test_cubelist",
"signature": "def test_cubelist(self)"
},
{
"docstring": "Test a list ... | 5 | null | Implement the Python class `Test_rebadge_forecasts_as_latest_cycle` described below.
Class description:
Test the rebadge_forecasts_as_latest_cycle function
Method signatures and docstrings:
- def setUp(self): Set up some cubes with different cycle times
- def test_cubelist(self): Test a list of cubes is returned with... | Implement the Python class `Test_rebadge_forecasts_as_latest_cycle` described below.
Class description:
Test the rebadge_forecasts_as_latest_cycle function
Method signatures and docstrings:
- def setUp(self): Set up some cubes with different cycle times
- def test_cubelist(self): Test a list of cubes is returned with... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_rebadge_forecasts_as_latest_cycle:
"""Test the rebadge_forecasts_as_latest_cycle function"""
def setUp(self):
"""Set up some cubes with different cycle times"""
<|body_0|>
def test_cubelist(self):
"""Test a list of cubes is returned with the latest frt"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_rebadge_forecasts_as_latest_cycle:
"""Test the rebadge_forecasts_as_latest_cycle function"""
def setUp(self):
"""Set up some cubes with different cycle times"""
self.cycletime = '20190711T1200Z'
validity_time = datetime(2019, 7, 11, 14)
self.cube_early = set_up_variab... | the_stack_v2_python_sparse | improver_tests/metadata/test_forecast_times.py | metoppv/improver | train | 101 |
2cd833ca6d134f13f2797769fa2822cb85484337 | [
"if not email:\n raise ValueError(_('Users must have an email address'))\nuser = self.model(email=self.normalize_email(email), name=name, phone1=phone1, signed_up=signed_up)\nuser.set_password(password)\nuser.save(using=self._db)\nMyUserProfile.objects.create(myuser=user)\nNotifClick.objects.create(myuser=user)\... | <|body_start_0|>
if not email:
raise ValueError(_('Users must have an email address'))
user = self.model(email=self.normalize_email(email), name=name, phone1=phone1, signed_up=signed_up)
user.set_password(password)
user.save(using=self._db)
MyUserProfile.objects.creat... | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, email, name, phone1, password=None, signed_up=timezone.localtime()):
"""Creates and saves a User with the given email, name and password."""
<|body_0|>
def create_superuser(self, email, name, phone1, password=None, signed_up=timezone.loca... | stack_v2_sparse_classes_36k_train_003254 | 4,013 | no_license | [
{
"docstring": "Creates and saves a User with the given email, name and password.",
"name": "create_user",
"signature": "def create_user(self, email, name, phone1, password=None, signed_up=timezone.localtime())"
},
{
"docstring": "Creates and saves a superuser with the given email, name and pass... | 2 | stack_v2_sparse_classes_30k_train_014586 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, name, phone1, password=None, signed_up=timezone.localtime()): Creates and saves a User with the given email, name and password.
- def creat... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, name, phone1, password=None, signed_up=timezone.localtime()): Creates and saves a User with the given email, name and password.
- def creat... | 94751753d907b1299613fd35b0cf8a2cec3cd208 | <|skeleton|>
class MyUserManager:
def create_user(self, email, name, phone1, password=None, signed_up=timezone.localtime()):
"""Creates and saves a User with the given email, name and password."""
<|body_0|>
def create_superuser(self, email, name, phone1, password=None, signed_up=timezone.loca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyUserManager:
def create_user(self, email, name, phone1, password=None, signed_up=timezone.localtime()):
"""Creates and saves a User with the given email, name and password."""
if not email:
raise ValueError(_('Users must have an email address'))
user = self.model(email=se... | the_stack_v2_python_sparse | join/models.py | lcbiplove/frutonp | train | 0 | |
1ef8ba287584d71e198f658916eebde474377e8c | [
"def check(mid: int) -> bool:\n pre, suf = (nums[:mid], nums[-mid:])\n return all((2 * pre[i] <= suf[i] for i in range(mid)))\nnums.sort()\nn = len(nums)\nleft, right = (1, n // 2)\nwhile left <= right:\n mid = (left + right) // 2\n if check(mid):\n left = mid + 1\n else:\n right = mid ... | <|body_start_0|>
def check(mid: int) -> bool:
pre, suf = (nums[:mid], nums[-mid:])
return all((2 * pre[i] <= suf[i] for i in range(mid)))
nums.sort()
n = len(nums)
left, right = (1, n // 2)
while left <= right:
mid = (left + right) // 2
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxNumOfMarkedIndices(self, nums: List[int]) -> int:
"""binary search"""
<|body_0|>
def maxNumOfMarkedIndices2(self, nums: List[int]) -> int:
"""two pointers"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def check(mid: int) -> bool:
... | stack_v2_sparse_classes_36k_train_003255 | 2,510 | no_license | [
{
"docstring": "binary search",
"name": "maxNumOfMarkedIndices",
"signature": "def maxNumOfMarkedIndices(self, nums: List[int]) -> int"
},
{
"docstring": "two pointers",
"name": "maxNumOfMarkedIndices2",
"signature": "def maxNumOfMarkedIndices2(self, nums: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxNumOfMarkedIndices(self, nums: List[int]) -> int: binary search
- def maxNumOfMarkedIndices2(self, nums: List[int]) -> int: two pointers | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxNumOfMarkedIndices(self, nums: List[int]) -> int: binary search
- def maxNumOfMarkedIndices2(self, nums: List[int]) -> int: two pointers
<|skeleton|>
class Solution:
... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def maxNumOfMarkedIndices(self, nums: List[int]) -> int:
"""binary search"""
<|body_0|>
def maxNumOfMarkedIndices2(self, nums: List[int]) -> int:
"""two pointers"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxNumOfMarkedIndices(self, nums: List[int]) -> int:
"""binary search"""
def check(mid: int) -> bool:
pre, suf = (nums[:mid], nums[-mid:])
return all((2 * pre[i] <= suf[i] for i in range(mid)))
nums.sort()
n = len(nums)
left, right ... | the_stack_v2_python_sparse | 15_双指针/2576. 求出最多标记下标.py | 981377660LMT/algorithm-study | train | 225 | |
5a1e23cc95062a28064aa862cfa32faf0e31e156 | [
"self.loginpage.openLoginPage()\nself.log('PO-gjs 뵽Ŀҳ ')\nself.loginpage.login_gjs_pro(self.readusername(1), self.readpassword(1))\nself.log('PO-gjs ȷû ')\nself.assertEqual(self.loginpage.get_assertText(), self.exceptText(1))\nself.log('PO-gjs ¼ɹȡϢж ')\nSaveImage(self.dr, 'login_success.png')\nself.log('PO-gjs ¼ɹȡͼ... | <|body_start_0|>
self.loginpage.openLoginPage()
self.log('PO-gjs 뵽Ŀҳ ')
self.loginpage.login_gjs_pro(self.readusername(1), self.readpassword(1))
self.log('PO-gjs ȷû ')
self.assertEqual(self.loginpage.get_assertText(), self.exceptText(1))
self.log('PO-gjs ¼ɹȡϢж ')
... | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
def testlogin(self):
"""ȷû"""
<|body_0|>
def test_user_null(self):
"""Ϊ"""
<|body_1|>
def test_username_null(self):
"""ûΪ"""
<|body_2|>
def test_user_passwd_null(self):
"""û / Ϊ"""
<|body_3|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_003256 | 2,841 | no_license | [
{
"docstring": "ȷû",
"name": "testlogin",
"signature": "def testlogin(self)"
},
{
"docstring": "Ϊ",
"name": "test_user_null",
"signature": "def test_user_null(self)"
},
{
"docstring": "ûΪ",
"name": "test_username_null",
"signature": "def test_username_null(self)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_010735 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def testlogin(self): ȷû
- def test_user_null(self): Ϊ
- def test_username_null(self): ûΪ
- def test_user_passwd_null(self): û / Ϊ | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def testlogin(self): ȷû
- def test_user_null(self): Ϊ
- def test_username_null(self): ûΪ
- def test_user_passwd_null(self): û / Ϊ
<|skeleton|>
class TestLogin:
def testlo... | 910bcf91dacb8ef699c700709b42dec771b504d0 | <|skeleton|>
class TestLogin:
def testlogin(self):
"""ȷû"""
<|body_0|>
def test_user_null(self):
"""Ϊ"""
<|body_1|>
def test_username_null(self):
"""ûΪ"""
<|body_2|>
def test_user_passwd_null(self):
"""û / Ϊ"""
<|body_3|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLogin:
def testlogin(self):
"""ȷû"""
self.loginpage.openLoginPage()
self.log('PO-gjs 뵽Ŀҳ ')
self.loginpage.login_gjs_pro(self.readusername(1), self.readpassword(1))
self.log('PO-gjs ȷû ')
self.assertEqual(self.loginpage.get_assertText(), self.exceptText(1))
... | the_stack_v2_python_sparse | 2.15章节源码/testCases/test_Login.py | luruifeng/myBookCode | train | 3 | |
a741dfcd258ff21e4a0b2bc8f2f3db547f731910 | [
"assert 'LYA_EMU_REPO' in os.environ, 'export LYA_EMU_REPO'\nrepo = os.environ['LYA_EMU_REPO']\nbasedir = repo + '/p1d_data//data_files/Chabanier2019/'\nz, k, Pk, cov = self._setup_from_file(basedir, add_syst)\nif zmin or zmax:\n z, k, Pk, cov = base_p1d_data._drop_zbins(z, k, Pk, cov, zmin, zmax)\nbase_p1d_data... | <|body_start_0|>
assert 'LYA_EMU_REPO' in os.environ, 'export LYA_EMU_REPO'
repo = os.environ['LYA_EMU_REPO']
basedir = repo + '/p1d_data//data_files/Chabanier2019/'
z, k, Pk, cov = self._setup_from_file(basedir, add_syst)
if zmin or zmax:
z, k, Pk, cov = base_p1d_dat... | Class containing P1D from Chabanier et al. (2019). | P1D_Chabanier2019 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class P1D_Chabanier2019:
"""Class containing P1D from Chabanier et al. (2019)."""
def __init__(self, zmin=None, zmax=None, add_syst=True):
"""Read measured P1D from Chabanier et al. (2019)."""
<|body_0|>
def _setup_from_file(self, basedir, add_syst):
"""Reconstruct cov... | stack_v2_sparse_classes_36k_train_003257 | 2,339 | no_license | [
{
"docstring": "Read measured P1D from Chabanier et al. (2019).",
"name": "__init__",
"signature": "def __init__(self, zmin=None, zmax=None, add_syst=True)"
},
{
"docstring": "Reconstruct covariance matrix from files.",
"name": "_setup_from_file",
"signature": "def _setup_from_file(self,... | 2 | stack_v2_sparse_classes_30k_train_012996 | Implement the Python class `P1D_Chabanier2019` described below.
Class description:
Class containing P1D from Chabanier et al. (2019).
Method signatures and docstrings:
- def __init__(self, zmin=None, zmax=None, add_syst=True): Read measured P1D from Chabanier et al. (2019).
- def _setup_from_file(self, basedir, add_s... | Implement the Python class `P1D_Chabanier2019` described below.
Class description:
Class containing P1D from Chabanier et al. (2019).
Method signatures and docstrings:
- def __init__(self, zmin=None, zmax=None, add_syst=True): Read measured P1D from Chabanier et al. (2019).
- def _setup_from_file(self, basedir, add_s... | 54658ffce6b69005ec2509074d1eafa9e4625372 | <|skeleton|>
class P1D_Chabanier2019:
"""Class containing P1D from Chabanier et al. (2019)."""
def __init__(self, zmin=None, zmax=None, add_syst=True):
"""Read measured P1D from Chabanier et al. (2019)."""
<|body_0|>
def _setup_from_file(self, basedir, add_syst):
"""Reconstruct cov... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class P1D_Chabanier2019:
"""Class containing P1D from Chabanier et al. (2019)."""
def __init__(self, zmin=None, zmax=None, add_syst=True):
"""Read measured P1D from Chabanier et al. (2019)."""
assert 'LYA_EMU_REPO' in os.environ, 'export LYA_EMU_REPO'
repo = os.environ['LYA_EMU_REPO']
... | the_stack_v2_python_sparse | p1d_data/py/data_Chabanier2019.py | diveshjain-phy/LyaCosmoParams | train | 0 |
981db8e6227436fa28617cab2656a7401f230519 | [
"app = self.get_argument('app', default='')\nstatus = self.get_argument('status', default='')\nauth = self.get_argument('auth', default='')\nself.set_header('content-type', 'application/json')\ntry:\n strategies = StrategyCustDao().list_all_strategies()\n if app:\n strategies = filter(lambda s: s.app =... | <|body_start_0|>
app = self.get_argument('app', default='')
status = self.get_argument('status', default='')
auth = self.get_argument('auth', default='')
self.set_header('content-type', 'application/json')
try:
strategies = StrategyCustDao().list_all_strategies()
... | StrategyListHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrategyListHandler:
def get(self):
"""list proper strategies @API summary: get proper strategy notes: "get strategies belong to some app or have some specific status" tags: - nebula parameters: - name: app in: query required: false type: string description: the app of the strategies tha... | stack_v2_sparse_classes_36k_train_003258 | 20,036 | permissive | [
{
"docstring": "list proper strategies @API summary: get proper strategy notes: \"get strategies belong to some app or have some specific status\" tags: - nebula parameters: - name: app in: query required: false type: string description: the app of the strategies that belong to - name: status in: query required... | 3 | stack_v2_sparse_classes_30k_train_008278 | Implement the Python class `StrategyListHandler` described below.
Class description:
Implement the StrategyListHandler class.
Method signatures and docstrings:
- def get(self): list proper strategies @API summary: get proper strategy notes: "get strategies belong to some app or have some specific status" tags: - nebu... | Implement the Python class `StrategyListHandler` described below.
Class description:
Implement the StrategyListHandler class.
Method signatures and docstrings:
- def get(self): list proper strategies @API summary: get proper strategy notes: "get strategies belong to some app or have some specific status" tags: - nebu... | 2e32e6e7b225e0bd87ee8c847c22862f12c51bb1 | <|skeleton|>
class StrategyListHandler:
def get(self):
"""list proper strategies @API summary: get proper strategy notes: "get strategies belong to some app or have some specific status" tags: - nebula parameters: - name: app in: query required: false type: string description: the app of the strategies tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StrategyListHandler:
def get(self):
"""list proper strategies @API summary: get proper strategy notes: "get strategies belong to some app or have some specific status" tags: - nebula parameters: - name: app in: query required: false type: string description: the app of the strategies that belong to - ... | the_stack_v2_python_sparse | nebula/views/strategy.py | threathunterX/nebula_web | train | 2 | |
785266a09c2528f1b2bf1f59c9895f1cba65d07d | [
"self.people = []\nself.tiles = []\nself.tileFilename = tileFilename\nfor i in range(rows):\n row = []\n for j in range(columns):\n tile = Tile(i, j, tileFilename)\n if j > 0:\n tile.connectToTile(row[j - 1], LEFT)\n if i > 0:\n tile.connectToTile(self.tiles[i - 1][j... | <|body_start_0|>
self.people = []
self.tiles = []
self.tileFilename = tileFilename
for i in range(rows):
row = []
for j in range(columns):
tile = Tile(i, j, tileFilename)
if j > 0:
tile.connectToTile(row[j - 1], ... | Represents a Zone in the Game | Zone | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Zone:
"""Represents a Zone in the Game"""
def __init__(self, rows, columns, tileFilename):
"""Initialize the Zone"""
<|body_0|>
def setCallbacks(self, callback):
"""Set Callbacks to allow each Person in the Zone to interact with the Window to display messages"""
... | stack_v2_sparse_classes_36k_train_003259 | 1,258 | no_license | [
{
"docstring": "Initialize the Zone",
"name": "__init__",
"signature": "def __init__(self, rows, columns, tileFilename)"
},
{
"docstring": "Set Callbacks to allow each Person in the Zone to interact with the Window to display messages",
"name": "setCallbacks",
"signature": "def setCallba... | 2 | null | Implement the Python class `Zone` described below.
Class description:
Represents a Zone in the Game
Method signatures and docstrings:
- def __init__(self, rows, columns, tileFilename): Initialize the Zone
- def setCallbacks(self, callback): Set Callbacks to allow each Person in the Zone to interact with the Window to... | Implement the Python class `Zone` described below.
Class description:
Represents a Zone in the Game
Method signatures and docstrings:
- def __init__(self, rows, columns, tileFilename): Initialize the Zone
- def setCallbacks(self, callback): Set Callbacks to allow each Person in the Zone to interact with the Window to... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class Zone:
"""Represents a Zone in the Game"""
def __init__(self, rows, columns, tileFilename):
"""Initialize the Zone"""
<|body_0|>
def setCallbacks(self, callback):
"""Set Callbacks to allow each Person in the Zone to interact with the Window to display messages"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Zone:
"""Represents a Zone in the Game"""
def __init__(self, rows, columns, tileFilename):
"""Initialize the Zone"""
self.people = []
self.tiles = []
self.tileFilename = tileFilename
for i in range(rows):
row = []
for j in range(columns):
... | the_stack_v2_python_sparse | src/Zone/zone.py | sgtnourry/Pokemon-Project | train | 0 |
3539527b682f97ad66921c9a4ac92ceca25fb235 | [
"self.internreferanse_field = internreferanse_field\nself.fodt_dato_field = APIHelper.RFC3339DateTime(fodt_dato_field) if fodt_dato_field else None\nself.fodt_dato_field_specified = fodt_dato_field_specified\nself.navn_field = navn_field\nself.adresse_field = adresse_field\nself.postnr_field = postnr_field\nself.po... | <|body_start_0|>
self.internreferanse_field = internreferanse_field
self.fodt_dato_field = APIHelper.RFC3339DateTime(fodt_dato_field) if fodt_dato_field else None
self.fodt_dato_field_specified = fodt_dato_field_specified
self.navn_field = navn_field
self.adresse_field = adresse_... | Implementation of the 'Person.FullmaktPerson' model. TODO: type model description here. Attributes: internreferanse_field (long|int): TODO: type description here. fodt_dato_field (datetime): TODO: type description here. fodt_dato_field_specified (bool): TODO: type description here. navn_field (string): TODO: type descr... | PersonFullmaktPerson | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonFullmaktPerson:
"""Implementation of the 'Person.FullmaktPerson' model. TODO: type model description here. Attributes: internreferanse_field (long|int): TODO: type description here. fodt_dato_field (datetime): TODO: type description here. fodt_dato_field_specified (bool): TODO: type descrip... | stack_v2_sparse_classes_36k_train_003260 | 7,883 | permissive | [
{
"docstring": "Constructor for the PersonFullmaktPerson class",
"name": "__init__",
"signature": "def __init__(self, internreferanse_field=None, fodt_dato_field=None, fodt_dato_field_specified=None, navn_field=None, adresse_field=None, postnr_field=None, poststed_field=None, fullmakt_type_kode_field=No... | 2 | null | Implement the Python class `PersonFullmaktPerson` described below.
Class description:
Implementation of the 'Person.FullmaktPerson' model. TODO: type model description here. Attributes: internreferanse_field (long|int): TODO: type description here. fodt_dato_field (datetime): TODO: type description here. fodt_dato_fie... | Implement the Python class `PersonFullmaktPerson` described below.
Class description:
Implementation of the 'Person.FullmaktPerson' model. TODO: type model description here. Attributes: internreferanse_field (long|int): TODO: type description here. fodt_dato_field (datetime): TODO: type description here. fodt_dato_fie... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class PersonFullmaktPerson:
"""Implementation of the 'Person.FullmaktPerson' model. TODO: type model description here. Attributes: internreferanse_field (long|int): TODO: type description here. fodt_dato_field (datetime): TODO: type description here. fodt_dato_field_specified (bool): TODO: type descrip... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersonFullmaktPerson:
"""Implementation of the 'Person.FullmaktPerson' model. TODO: type model description here. Attributes: internreferanse_field (long|int): TODO: type description here. fodt_dato_field (datetime): TODO: type description here. fodt_dato_field_specified (bool): TODO: type description here. na... | the_stack_v2_python_sparse | idfy_rest_client/models/person_fullmakt_person.py | dealflowteam/Idfy | train | 0 |
6e25cfa0fe1ee0c922d76a1c21fcdd8c31d02371 | [
"for key, value in self.replacements.items():\n string = string.replace(key, value)\nreturn string",
"if conversions:\n self.replacements.update(conversions)\ntry:\n self.validate(arguments)\n return {self.convert(key): val for key, val in arguments.items()}\nexcept SchemaError as e:\n logger.warni... | <|body_start_0|>
for key, value in self.replacements.items():
string = string.replace(key, value)
return string
<|end_body_0|>
<|body_start_1|>
if conversions:
self.replacements.update(conversions)
try:
self.validate(arguments)
return {sel... | Extends `Schema` adapting it to PA scripts validation strategies. Adds predefined schemata as class variables to be used in scripts' validation schemas as well as `validate_user_input` method which acts as `Schema.validate` but returns a dictionary with converted keys ready to be used as function keyword arguments, e.g... | ScriptSchema | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScriptSchema:
"""Extends `Schema` adapting it to PA scripts validation strategies. Adds predefined schemata as class variables to be used in scripts' validation schemas as well as `validate_user_input` method which acts as `Schema.validate` but returns a dictionary with converted keys ready to be... | stack_v2_sparse_classes_36k_train_003261 | 4,382 | permissive | [
{
"docstring": "Removes cli argument notation characters ('--', '<', '>' etc.). :param string: cli argument key to be converted to fit Python argument syntax.",
"name": "convert",
"signature": "def convert(self, string)"
},
{
"docstring": "Calls `Schema.validate` on provided `arguments`. Returns... | 2 | stack_v2_sparse_classes_30k_train_001006 | Implement the Python class `ScriptSchema` described below.
Class description:
Extends `Schema` adapting it to PA scripts validation strategies. Adds predefined schemata as class variables to be used in scripts' validation schemas as well as `validate_user_input` method which acts as `Schema.validate` but returns a dic... | Implement the Python class `ScriptSchema` described below.
Class description:
Extends `Schema` adapting it to PA scripts validation strategies. Adds predefined schemata as class variables to be used in scripts' validation schemas as well as `validate_user_input` method which acts as `Schema.validate` but returns a dic... | dff92d1c5f18f338847b3c371c07a73dd2642957 | <|skeleton|>
class ScriptSchema:
"""Extends `Schema` adapting it to PA scripts validation strategies. Adds predefined schemata as class variables to be used in scripts' validation schemas as well as `validate_user_input` method which acts as `Schema.validate` but returns a dictionary with converted keys ready to be... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScriptSchema:
"""Extends `Schema` adapting it to PA scripts validation strategies. Adds predefined schemata as class variables to be used in scripts' validation schemas as well as `validate_user_input` method which acts as `Schema.validate` but returns a dictionary with converted keys ready to be used as func... | the_stack_v2_python_sparse | pythonanywhere/scripts_commons.py | pythonanywhere/helper_scripts | train | 34 |
b2753a5f6c12395a1e39148bb0beadd96b9e8c95 | [
"if faceEngine is not None:\n self.faceEngine = faceEngine\n self.estimatorsCollection = FaceEstimatorsCollection(faceEngine=self.faceEngine)\nself._faceDetector: FaceDetector = self.faceEngine.createFaceDetector(detectorType)",
"detectRes = self._faceDetector.detectOne(image, detectArea, True, True)\nif de... | <|body_start_0|>
if faceEngine is not None:
self.faceEngine = faceEngine
self.estimatorsCollection = FaceEstimatorsCollection(faceEngine=self.faceEngine)
self._faceDetector: FaceDetector = self.faceEngine.createFaceDetector(detectorType)
<|end_body_0|>
<|body_start_1|>
d... | High level face detector. Return *VLFaceDetection* instead simple *FaceDetection*. Attributes: estimatorsCollection (FaceEstimatorsCollection): face estimator collections for new detections. _faceDetector (FaceDetector): face detector faceEngine (VLFaceEngine): face engine for detector and estimators, default *FACE_ENG... | VLFaceDetector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VLFaceDetector:
"""High level face detector. Return *VLFaceDetection* instead simple *FaceDetection*. Attributes: estimatorsCollection (FaceEstimatorsCollection): face estimator collections for new detections. _faceDetector (FaceDetector): face detector faceEngine (VLFaceEngine): face engine for ... | stack_v2_sparse_classes_36k_train_003262 | 17,671 | permissive | [
{
"docstring": "Init. Args: detectorType: detector type faceEngine: face engine for detector and estimators",
"name": "__init__",
"signature": "def __init__(self, detectorType: DetectorType=DetectorType.FACE_DET_DEFAULT, faceEngine: Optional[VLFaceEngine]=None)"
},
{
"docstring": "Detect just on... | 5 | stack_v2_sparse_classes_30k_train_002759 | Implement the Python class `VLFaceDetector` described below.
Class description:
High level face detector. Return *VLFaceDetection* instead simple *FaceDetection*. Attributes: estimatorsCollection (FaceEstimatorsCollection): face estimator collections for new detections. _faceDetector (FaceDetector): face detector face... | Implement the Python class `VLFaceDetector` described below.
Class description:
High level face detector. Return *VLFaceDetection* instead simple *FaceDetection*. Attributes: estimatorsCollection (FaceEstimatorsCollection): face estimator collections for new detections. _faceDetector (FaceDetector): face detector face... | 3d06968ddc6177b330454cfc53116ece393b486d | <|skeleton|>
class VLFaceDetector:
"""High level face detector. Return *VLFaceDetection* instead simple *FaceDetection*. Attributes: estimatorsCollection (FaceEstimatorsCollection): face estimator collections for new detections. _faceDetector (FaceDetector): face detector faceEngine (VLFaceEngine): face engine for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VLFaceDetector:
"""High level face detector. Return *VLFaceDetection* instead simple *FaceDetection*. Attributes: estimatorsCollection (FaceEstimatorsCollection): face estimator collections for new detections. _faceDetector (FaceDetector): face detector faceEngine (VLFaceEngine): face engine for detector and ... | the_stack_v2_python_sparse | lunavl/sdk/luna_faces.py | DeusAnimo/lunasdk | train | 1 |
4b0a65bef9915f8dc51f3df7c6568a48896e096d | [
"res = 0\nself.grid = grid\nself.visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]\nfor i in range(len(grid)):\n for j in range(len(grid[0])):\n res = max(res, self.dfs(i, j))\nreturn res",
"if i < 0 or i >= len(self.grid) or j < 0 or (j >= len(self.grid[0])) or (not self.grid[i... | <|body_start_0|>
res = 0
self.grid = grid
self.visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
res = max(res, self.dfs(i, j))
return res
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxAreaOfIsland(self, grid):
"""Args: grid: list[list[int]] Return: int"""
<|body_0|>
def dfs(self, i, j):
"""Args: i: int j: int Return: area: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
self.grid = grid
... | stack_v2_sparse_classes_36k_train_003263 | 1,091 | no_license | [
{
"docstring": "Args: grid: list[list[int]] Return: int",
"name": "maxAreaOfIsland",
"signature": "def maxAreaOfIsland(self, grid)"
},
{
"docstring": "Args: i: int j: int Return: area: int",
"name": "dfs",
"signature": "def dfs(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017724 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaOfIsland(self, grid): Args: grid: list[list[int]] Return: int
- def dfs(self, i, j): Args: i: int j: int Return: area: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaOfIsland(self, grid): Args: grid: list[list[int]] Return: int
- def dfs(self, i, j): Args: i: int j: int Return: area: int
<|skeleton|>
class Solution:
def maxAr... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def maxAreaOfIsland(self, grid):
"""Args: grid: list[list[int]] Return: int"""
<|body_0|>
def dfs(self, i, j):
"""Args: i: int j: int Return: area: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxAreaOfIsland(self, grid):
"""Args: grid: list[list[int]] Return: int"""
res = 0
self.grid = grid
self.visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
... | the_stack_v2_python_sparse | code/695. 岛屿的最大面积.py | AiZhanghan/Leetcode | train | 0 | |
683859b8ebbb5d83222e3e406b7333fa266a277e | [
"t = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]])\nres = fn.sum_(t)\nassert isinstance(res, np.ndarray)\nassert fn.allclose(res, 2.1)",
"t = tf.Variable([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]])\nres = fn.sum_(t)\nassert isinstance(res, tf.Tensor)\nassert fn.allclose(res, 2.1)",
"t = torch.tensor([[0.1, 0.2, 0.3], [0... | <|body_start_0|>
t = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]])
res = fn.sum_(t)
assert isinstance(res, np.ndarray)
assert fn.allclose(res, 2.1)
<|end_body_0|>
<|body_start_1|>
t = tf.Variable([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]])
res = fn.sum_(t)
assert isinstan... | Tests for the summation function | TestSum | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSum:
"""Tests for the summation function"""
def test_array(self):
"""Test that sum, called without the axis arguments, returns a scalar"""
<|body_0|>
def test_tensorflow(self):
"""Test that sum, called without the axis arguments, returns a scalar"""
<... | stack_v2_sparse_classes_36k_train_003264 | 47,600 | permissive | [
{
"docstring": "Test that sum, called without the axis arguments, returns a scalar",
"name": "test_array",
"signature": "def test_array(self)"
},
{
"docstring": "Test that sum, called without the axis arguments, returns a scalar",
"name": "test_tensorflow",
"signature": "def test_tensorf... | 6 | null | Implement the Python class `TestSum` described below.
Class description:
Tests for the summation function
Method signatures and docstrings:
- def test_array(self): Test that sum, called without the axis arguments, returns a scalar
- def test_tensorflow(self): Test that sum, called without the axis arguments, returns ... | Implement the Python class `TestSum` described below.
Class description:
Tests for the summation function
Method signatures and docstrings:
- def test_array(self): Test that sum, called without the axis arguments, returns a scalar
- def test_tensorflow(self): Test that sum, called without the axis arguments, returns ... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class TestSum:
"""Tests for the summation function"""
def test_array(self):
"""Test that sum, called without the axis arguments, returns a scalar"""
<|body_0|>
def test_tensorflow(self):
"""Test that sum, called without the axis arguments, returns a scalar"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSum:
"""Tests for the summation function"""
def test_array(self):
"""Test that sum, called without the axis arguments, returns a scalar"""
t = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]])
res = fn.sum_(t)
assert isinstance(res, np.ndarray)
assert fn.allclose(re... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits_backup/pennylane/pennylane#1081/before/test_functions.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
2bdd5461f975adb1f134e5843778291667383320 | [
"cfg_path = os.path.join(base_path, HOST_CONFIG_FILE)\nif not os.path.exists(cfg_path):\n return False\nwith open(cfg_path, 'rb') as f:\n record = yaml.safe_load(f)\n if record and cls.KEY in record:\n return True\nreturn False",
"if not os.path.exists(base_path):\n os.makedirs(base_path)\ncfg_... | <|body_start_0|>
cfg_path = os.path.join(base_path, HOST_CONFIG_FILE)
if not os.path.exists(cfg_path):
return False
with open(cfg_path, 'rb') as f:
record = yaml.safe_load(f)
if record and cls.KEY in record:
return True
return False
<|e... | ConfigMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigMixin:
def exists(cls, base_path):
"""Check that the configuration file exists and the key for this config type exists in the file"""
<|body_0|>
def save(self, base_path):
"""Serialize configuration to a YAML file for future use"""
<|body_1|>
def l... | stack_v2_sparse_classes_36k_train_003265 | 5,461 | permissive | [
{
"docstring": "Check that the configuration file exists and the key for this config type exists in the file",
"name": "exists",
"signature": "def exists(cls, base_path)"
},
{
"docstring": "Serialize configuration to a YAML file for future use",
"name": "save",
"signature": "def save(sel... | 5 | stack_v2_sparse_classes_30k_train_000940 | Implement the Python class `ConfigMixin` described below.
Class description:
Implement the ConfigMixin class.
Method signatures and docstrings:
- def exists(cls, base_path): Check that the configuration file exists and the key for this config type exists in the file
- def save(self, base_path): Serialize configuratio... | Implement the Python class `ConfigMixin` described below.
Class description:
Implement the ConfigMixin class.
Method signatures and docstrings:
- def exists(cls, base_path): Check that the configuration file exists and the key for this config type exists in the file
- def save(self, base_path): Serialize configuratio... | 5cf8f159183a80d2364e05bb30362e2798a7af37 | <|skeleton|>
class ConfigMixin:
def exists(cls, base_path):
"""Check that the configuration file exists and the key for this config type exists in the file"""
<|body_0|>
def save(self, base_path):
"""Serialize configuration to a YAML file for future use"""
<|body_1|>
def l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigMixin:
def exists(cls, base_path):
"""Check that the configuration file exists and the key for this config type exists in the file"""
cfg_path = os.path.join(base_path, HOST_CONFIG_FILE)
if not os.path.exists(cfg_path):
return False
with open(cfg_path, 'rb') a... | the_stack_v2_python_sparse | python_modules/libraries/dagster-aws/dagster_aws/cli/config.py | zzztimbo/dagster | train | 1 | |
e75b195857bc5b39955c42f6062fbd425a0a51d2 | [
"BaseWorkerThread.__init__(self)\nself.queue = queue\nself.config = config\nself.reqmgr2Svc = ReqMgr(self.config.TaskArchiver.ReqMgr2ServiceURL)\nself.abortedAndForceCompleteWorkflowCache = self.reqmgr2Svc.getAbortedAndForceCompleteRequestsFromMemoryCache()",
"t = random.randrange(self.idleTime)\nself.logger.info... | <|body_start_0|>
BaseWorkerThread.__init__(self)
self.queue = queue
self.config = config
self.reqmgr2Svc = ReqMgr(self.config.TaskArchiver.ReqMgr2ServiceURL)
self.abortedAndForceCompleteWorkflowCache = self.reqmgr2Svc.getAbortedAndForceCompleteRequestsFromMemoryCache()
<|end_body... | Cleans expired items, updates element status. | WorkQueueManagerCleaner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkQueueManagerCleaner:
"""Cleans expired items, updates element status."""
def __init__(self, queue, config):
"""Initialise class members"""
<|body_0|>
def setup(self, parameters):
"""Called at startup - introduce random delay to avoid workers all starting at o... | stack_v2_sparse_classes_36k_train_003266 | 1,967 | no_license | [
{
"docstring": "Initialise class members",
"name": "__init__",
"signature": "def __init__(self, queue, config)"
},
{
"docstring": "Called at startup - introduce random delay to avoid workers all starting at once",
"name": "setup",
"signature": "def setup(self, parameters)"
},
{
"... | 3 | null | Implement the Python class `WorkQueueManagerCleaner` described below.
Class description:
Cleans expired items, updates element status.
Method signatures and docstrings:
- def __init__(self, queue, config): Initialise class members
- def setup(self, parameters): Called at startup - introduce random delay to avoid work... | Implement the Python class `WorkQueueManagerCleaner` described below.
Class description:
Cleans expired items, updates element status.
Method signatures and docstrings:
- def __init__(self, queue, config): Initialise class members
- def setup(self, parameters): Called at startup - introduce random delay to avoid work... | f4cb398de940560e40491ba676b704e1489d4682 | <|skeleton|>
class WorkQueueManagerCleaner:
"""Cleans expired items, updates element status."""
def __init__(self, queue, config):
"""Initialise class members"""
<|body_0|>
def setup(self, parameters):
"""Called at startup - introduce random delay to avoid workers all starting at o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkQueueManagerCleaner:
"""Cleans expired items, updates element status."""
def __init__(self, queue, config):
"""Initialise class members"""
BaseWorkerThread.__init__(self)
self.queue = queue
self.config = config
self.reqmgr2Svc = ReqMgr(self.config.TaskArchiver.... | the_stack_v2_python_sparse | src/python/WMComponent/WorkQueueManager/WorkQueueManagerCleaner.py | PerilousApricot/WMCore | train | 1 |
93175f0d589c8284b9a50e8c284dad4391f32619 | [
"book = Book(title, author, reader)\ncls.book_list.append(book)\nprint('书本 %s 添加成功!' % book)",
"target_book = None\nfor book in cls.book_list:\n if book.title == title and book.author == author:\n target_book = book\n break\nif target_book:\n cls.book_list.remove(target_book)\n print('书本 %s... | <|body_start_0|>
book = Book(title, author, reader)
cls.book_list.append(book)
print('书本 %s 添加成功!' % book)
<|end_body_0|>
<|body_start_1|>
target_book = None
for book in cls.book_list:
if book.title == title and book.author == author:
target_book = bo... | Library | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Library:
def add_book(cls, title, author, reader=None):
"""添加一本书"""
<|body_0|>
def del_book(cls, title, author):
"""删除一本书"""
<|body_1|>
def find_book(cls, title, author=None):
"""根据书名查找一本书 如果不存在则返回 -1,存在则返回 1"""
<|body_2|>
def add_re... | stack_v2_sparse_classes_36k_train_003267 | 2,899 | no_license | [
{
"docstring": "添加一本书",
"name": "add_book",
"signature": "def add_book(cls, title, author, reader=None)"
},
{
"docstring": "删除一本书",
"name": "del_book",
"signature": "def del_book(cls, title, author)"
},
{
"docstring": "根据书名查找一本书 如果不存在则返回 -1,存在则返回 1",
"name": "find_book",
... | 6 | stack_v2_sparse_classes_30k_train_008087 | Implement the Python class `Library` described below.
Class description:
Implement the Library class.
Method signatures and docstrings:
- def add_book(cls, title, author, reader=None): 添加一本书
- def del_book(cls, title, author): 删除一本书
- def find_book(cls, title, author=None): 根据书名查找一本书 如果不存在则返回 -1,存在则返回 1
- def add_rea... | Implement the Python class `Library` described below.
Class description:
Implement the Library class.
Method signatures and docstrings:
- def add_book(cls, title, author, reader=None): 添加一本书
- def del_book(cls, title, author): 删除一本书
- def find_book(cls, title, author=None): 根据书名查找一本书 如果不存在则返回 -1,存在则返回 1
- def add_rea... | 5a562d76830faf78feec81bc11190b71eae3a799 | <|skeleton|>
class Library:
def add_book(cls, title, author, reader=None):
"""添加一本书"""
<|body_0|>
def del_book(cls, title, author):
"""删除一本书"""
<|body_1|>
def find_book(cls, title, author=None):
"""根据书名查找一本书 如果不存在则返回 -1,存在则返回 1"""
<|body_2|>
def add_re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Library:
def add_book(cls, title, author, reader=None):
"""添加一本书"""
book = Book(title, author, reader)
cls.book_list.append(book)
print('书本 %s 添加成功!' % book)
def del_book(cls, title, author):
"""删除一本书"""
target_book = None
for book in cls.book_list:... | the_stack_v2_python_sparse | FundamentalsOfPythonDataStructures/ProgrammingProject/chapter1/project_10.py | xjr7670/book_practice | train | 3 | |
8c69b04818eb1c529b6ad11ac1a9de153b213ba5 | [
"self.ds_type = 10\nself.num_elements = num_elements\nself.element_multiplier = element_multiplier\nself.image = 0\nself.name_len = 8\nself.Name = 'E000001\\x00'\nself.Velocities = []\nfor bins in range(num_elements):\n bins = []\n for beams in range(element_multiplier):\n bins.append([Ensemble().BadVe... | <|body_start_0|>
self.ds_type = 10
self.num_elements = num_elements
self.element_multiplier = element_multiplier
self.image = 0
self.name_len = 8
self.Name = 'E000001\x00'
self.Velocities = []
for bins in range(num_elements):
bins = []
... | Beam Velocity DataSet. [Bin x Beam] data. | BeamVelocity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BeamVelocity:
"""Beam Velocity DataSet. [Bin x Beam] data."""
def __init__(self, num_elements, element_multiplier):
"""Beam Velocity data. :param num_elements: Number of bins :param element_multiplier: Number of beams."""
<|body_0|>
def decode(self, data):
"""Tak... | stack_v2_sparse_classes_36k_train_003268 | 4,649 | no_license | [
{
"docstring": "Beam Velocity data. :param num_elements: Number of bins :param element_multiplier: Number of beams.",
"name": "__init__",
"signature": "def __init__(self, num_elements, element_multiplier)"
},
{
"docstring": "Take the data bytearray. Decode the data to populate the velocities. :p... | 5 | null | Implement the Python class `BeamVelocity` described below.
Class description:
Beam Velocity DataSet. [Bin x Beam] data.
Method signatures and docstrings:
- def __init__(self, num_elements, element_multiplier): Beam Velocity data. :param num_elements: Number of bins :param element_multiplier: Number of beams.
- def de... | Implement the Python class `BeamVelocity` described below.
Class description:
Beam Velocity DataSet. [Bin x Beam] data.
Method signatures and docstrings:
- def __init__(self, num_elements, element_multiplier): Beam Velocity data. :param num_elements: Number of bins :param element_multiplier: Number of beams.
- def de... | 384edef9c14ae5296d7e123eec473b29905a8a58 | <|skeleton|>
class BeamVelocity:
"""Beam Velocity DataSet. [Bin x Beam] data."""
def __init__(self, num_elements, element_multiplier):
"""Beam Velocity data. :param num_elements: Number of bins :param element_multiplier: Number of beams."""
<|body_0|>
def decode(self, data):
"""Tak... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BeamVelocity:
"""Beam Velocity DataSet. [Bin x Beam] data."""
def __init__(self, num_elements, element_multiplier):
"""Beam Velocity data. :param num_elements: Number of bins :param element_multiplier: Number of beams."""
self.ds_type = 10
self.num_elements = num_elements
... | the_stack_v2_python_sparse | Ensemble/BeamVelocity.py | ricorx7/rti_python-1 | train | 0 |
3a22897ae9fbf3a754be03343fbd247a0f715fc0 | [
"expected = np.array([[0, 20, 50, 80, 100]])\ninput_array = np.array([[20, 50, 80]])\nresult = concatenate_2d_array_with_2d_array_endpoints(input_array, 0, 100)\nself.assertIsInstance(result, np.ndarray)\nself.assertArrayAlmostEqual(result, expected)",
"input_array = np.array([-40, 200, 1000])\nmsg = 'Expected 2D... | <|body_start_0|>
expected = np.array([[0, 20, 50, 80, 100]])
input_array = np.array([[20, 50, 80]])
result = concatenate_2d_array_with_2d_array_endpoints(input_array, 0, 100)
self.assertIsInstance(result, np.ndarray)
self.assertArrayAlmostEqual(result, expected)
<|end_body_0|>
<... | Test the concatenate_2d_array_with_2d_array_endpoints. | Test_concatenate_2d_array_with_2d_array_endpoints | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_concatenate_2d_array_with_2d_array_endpoints:
"""Test the concatenate_2d_array_with_2d_array_endpoints."""
def test_basic(self):
"""Test that result is a numpy array with the expected contents."""
<|body_0|>
def test_1d_input(self):
"""Test 1D input results ... | stack_v2_sparse_classes_36k_train_003269 | 28,421 | permissive | [
{
"docstring": "Test that result is a numpy array with the expected contents.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test 1D input results in the expected error",
"name": "test_1d_input",
"signature": "def test_1d_input(self)"
},
{
"docstri... | 3 | null | Implement the Python class `Test_concatenate_2d_array_with_2d_array_endpoints` described below.
Class description:
Test the concatenate_2d_array_with_2d_array_endpoints.
Method signatures and docstrings:
- def test_basic(self): Test that result is a numpy array with the expected contents.
- def test_1d_input(self): T... | Implement the Python class `Test_concatenate_2d_array_with_2d_array_endpoints` described below.
Class description:
Test the concatenate_2d_array_with_2d_array_endpoints.
Method signatures and docstrings:
- def test_basic(self): Test that result is a numpy array with the expected contents.
- def test_1d_input(self): T... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_concatenate_2d_array_with_2d_array_endpoints:
"""Test the concatenate_2d_array_with_2d_array_endpoints."""
def test_basic(self):
"""Test that result is a numpy array with the expected contents."""
<|body_0|>
def test_1d_input(self):
"""Test 1D input results ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_concatenate_2d_array_with_2d_array_endpoints:
"""Test the concatenate_2d_array_with_2d_array_endpoints."""
def test_basic(self):
"""Test that result is a numpy array with the expected contents."""
expected = np.array([[0, 20, 50, 80, 100]])
input_array = np.array([[20, 50, 80... | the_stack_v2_python_sparse | improver_tests/ensemble_copula_coupling/test_utilities.py | metoppv/improver | train | 101 |
381a16638e685ddfbfd49186e95822bd224d27c7 | [
"super(AttnModel, self).__init__()\nself.feat_dim = feat_dim\nself.time_dim = time_dim\nself.edge_in_dim = feat_dim + edge_dim + time_dim\nself.model_dim = self.edge_in_dim\nself.merger = MergeLayer(self.model_dim, feat_dim, feat_dim, feat_dim)\nassert self.model_dim % n_head == 0\nself.logger = logging.getLogger(_... | <|body_start_0|>
super(AttnModel, self).__init__()
self.feat_dim = feat_dim
self.time_dim = time_dim
self.edge_in_dim = feat_dim + edge_dim + time_dim
self.model_dim = self.edge_in_dim
self.merger = MergeLayer(self.model_dim, feat_dim, feat_dim, feat_dim)
assert s... | Attention based temporal layers | AttnModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttnModel:
"""Attention based temporal layers"""
def __init__(self, feat_dim, edge_dim, time_dim, attn_mode='prod', n_head=2, drop_out=0.1):
"""args: feat_dim: dim for the node features edge_dim: dim for the temporal edge features time_dim: dim for the time encoding attn_mode: choose... | stack_v2_sparse_classes_36k_train_003270 | 25,350 | no_license | [
{
"docstring": "args: feat_dim: dim for the node features edge_dim: dim for the temporal edge features time_dim: dim for the time encoding attn_mode: choose from 'prod' and 'map' n_head: number of heads in attention drop_out: probability of dropping a neural.",
"name": "__init__",
"signature": "def __in... | 2 | stack_v2_sparse_classes_30k_train_011412 | Implement the Python class `AttnModel` described below.
Class description:
Attention based temporal layers
Method signatures and docstrings:
- def __init__(self, feat_dim, edge_dim, time_dim, attn_mode='prod', n_head=2, drop_out=0.1): args: feat_dim: dim for the node features edge_dim: dim for the temporal edge featu... | Implement the Python class `AttnModel` described below.
Class description:
Attention based temporal layers
Method signatures and docstrings:
- def __init__(self, feat_dim, edge_dim, time_dim, attn_mode='prod', n_head=2, drop_out=0.1): args: feat_dim: dim for the node features edge_dim: dim for the temporal edge featu... | 951f74f15734b3da52232758ad6c8af8f768e6fd | <|skeleton|>
class AttnModel:
"""Attention based temporal layers"""
def __init__(self, feat_dim, edge_dim, time_dim, attn_mode='prod', n_head=2, drop_out=0.1):
"""args: feat_dim: dim for the node features edge_dim: dim for the temporal edge features time_dim: dim for the time encoding attn_mode: choose... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttnModel:
"""Attention based temporal layers"""
def __init__(self, feat_dim, edge_dim, time_dim, attn_mode='prod', n_head=2, drop_out=0.1):
"""args: feat_dim: dim for the node features edge_dim: dim for the temporal edge features time_dim: dim for the time encoding attn_mode: choose from 'prod' ... | the_stack_v2_python_sparse | model/TGAT.py | katrina-m/RecModels_Pytorch | train | 0 |
7a94ad9d127a18976a1a955a87de10af5a8a8653 | [
"item = response.meta['item']\ning_list = []\ning_li = response.xpath('//*[@id=\"__layout\"]//ul[@class=\"recipe-ingredients__list\"]/li')\nfor li in ing_li:\n ing = li.xpath('.//a/text()').extract_first()\n if ing is not None:\n ing_list.append(ing.strip())\nitem['ingredients'] = ', '.join(ing_list)\n... | <|body_start_0|>
item = response.meta['item']
ing_list = []
ing_li = response.xpath('//*[@id="__layout"]//ul[@class="recipe-ingredients__list"]/li')
for li in ing_li:
ing = li.xpath('.//a/text()').extract_first()
if ing is not None:
ing_list.append... | RecipeSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecipeSpider:
def parse_detail(self, response):
"""parse the detail page :param response: :return:"""
<|body_0|>
def parse(self, response):
"""parse the search page :param response: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
item = res... | stack_v2_sparse_classes_36k_train_003271 | 2,885 | no_license | [
{
"docstring": "parse the detail page :param response: :return:",
"name": "parse_detail",
"signature": "def parse_detail(self, response)"
},
{
"docstring": "parse the search page :param response: :return:",
"name": "parse",
"signature": "def parse(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012745 | Implement the Python class `RecipeSpider` described below.
Class description:
Implement the RecipeSpider class.
Method signatures and docstrings:
- def parse_detail(self, response): parse the detail page :param response: :return:
- def parse(self, response): parse the search page :param response: :return: | Implement the Python class `RecipeSpider` described below.
Class description:
Implement the RecipeSpider class.
Method signatures and docstrings:
- def parse_detail(self, response): parse the detail page :param response: :return:
- def parse(self, response): parse the search page :param response: :return:
<|skeleton... | 24deb2f2ca7f859a351ecafe6fb03123a1b7685d | <|skeleton|>
class RecipeSpider:
def parse_detail(self, response):
"""parse the detail page :param response: :return:"""
<|body_0|>
def parse(self, response):
"""parse the search page :param response: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecipeSpider:
def parse_detail(self, response):
"""parse the detail page :param response: :return:"""
item = response.meta['item']
ing_list = []
ing_li = response.xpath('//*[@id="__layout"]//ul[@class="recipe-ingredients__list"]/li')
for li in ing_li:
ing = ... | the_stack_v2_python_sparse | recipespiders/recipespiders/spiders/recipe.py | yefeichen99/RecipeSE | train | 0 | |
0d3bf325e608e0a0cac75a853141f031a78b6af4 | [
"dic = {}\nfor c in s:\n dic[c] = not c in dic\nfor c in s:\n if dic[c]:\n return c\nreturn ' '",
"dic = {}\nfor c in s:\n dic[c] = not c in dic\nfor k, v in dic.items():\n if v:\n return k\nreturn ' '"
] | <|body_start_0|>
dic = {}
for c in s:
dic[c] = not c in dic
for c in s:
if dic[c]:
return c
return ' '
<|end_body_0|>
<|body_start_1|>
dic = {}
for c in s:
dic[c] = not c in dic
for k, v in dic.items():
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstUniqChar_1(self, s: str) -> str:
"""方法一:哈希表 时间复杂度 O(N) : N 为字符串 s 的长度;需遍历 s 两轮,使用 O(N) ;HashMap 查找的操作复杂度为 O(1) ; 空间复杂度 O(N) : HashMap 需存储 N 个字符的键值对,使用 O(N) 大小的额外空间。 :param s: :return:"""
<|body_0|>
def firstUniqChar_2(self, s: str) -> str:
"""方法二:有... | stack_v2_sparse_classes_36k_train_003272 | 1,971 | no_license | [
{
"docstring": "方法一:哈希表 时间复杂度 O(N) : N 为字符串 s 的长度;需遍历 s 两轮,使用 O(N) ;HashMap 查找的操作复杂度为 O(1) ; 空间复杂度 O(N) : HashMap 需存储 N 个字符的键值对,使用 O(N) 大小的额外空间。 :param s: :return:",
"name": "firstUniqChar_1",
"signature": "def firstUniqChar_1(self, s: str) -> str"
},
{
"docstring": "方法二:有序哈希表 基本原理:python 3.6后的字... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar_1(self, s: str) -> str: 方法一:哈希表 时间复杂度 O(N) : N 为字符串 s 的长度;需遍历 s 两轮,使用 O(N) ;HashMap 查找的操作复杂度为 O(1) ; 空间复杂度 O(N) : HashMap 需存储 N 个字符的键值对,使用 O(N) 大小的额外空间。 :param ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar_1(self, s: str) -> str: 方法一:哈希表 时间复杂度 O(N) : N 为字符串 s 的长度;需遍历 s 两轮,使用 O(N) ;HashMap 查找的操作复杂度为 O(1) ; 空间复杂度 O(N) : HashMap 需存储 N 个字符的键值对,使用 O(N) 大小的额外空间。 :param ... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def firstUniqChar_1(self, s: str) -> str:
"""方法一:哈希表 时间复杂度 O(N) : N 为字符串 s 的长度;需遍历 s 两轮,使用 O(N) ;HashMap 查找的操作复杂度为 O(1) ; 空间复杂度 O(N) : HashMap 需存储 N 个字符的键值对,使用 O(N) 大小的额外空间。 :param s: :return:"""
<|body_0|>
def firstUniqChar_2(self, s: str) -> str:
"""方法二:有... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstUniqChar_1(self, s: str) -> str:
"""方法一:哈希表 时间复杂度 O(N) : N 为字符串 s 的长度;需遍历 s 两轮,使用 O(N) ;HashMap 查找的操作复杂度为 O(1) ; 空间复杂度 O(N) : HashMap 需存储 N 个字符的键值对,使用 O(N) 大小的额外空间。 :param s: :return:"""
dic = {}
for c in s:
dic[c] = not c in dic
for c in s:
... | the_stack_v2_python_sparse | 剑指 Offer(第 2 版)/firstUniqChar.py | MaoningGuan/LeetCode | train | 3 | |
6067ea210d2b75e44fe5784d66f07bb67beae91d | [
"if digits is None or len(digits) == 0:\n return [1]\ntemp = [str(i) for i in digits]\nnumber = int(''.join(temp))\nreturn [int(i) for i in list(str(number + 1))]",
"if digits is None or len(digits) == 0:\n return [1]\nmove_one = 0\ndigits[-1] += 1\nfor i in reversed(range(len(digits))):\n if move_one + ... | <|body_start_0|>
if digits is None or len(digits) == 0:
return [1]
temp = [str(i) for i in digits]
number = int(''.join(temp))
return [int(i) for i in list(str(number + 1))]
<|end_body_0|>
<|body_start_1|>
if digits is None or len(digits) == 0:
return [1]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plusOne_test1(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if digits is None or len(di... | stack_v2_sparse_classes_36k_train_003273 | 1,166 | no_license | [
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne_test1",
"signature": "def plusOne_test1(self, digits)"
},
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne",
"signature": "def plusOne(self, digits)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne_test1(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne_test1(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int]
<|skeleton|>
class Solution:
... | 09b7121628df824f432b8cdd25c55f045b013c0b | <|skeleton|>
class Solution:
def plusOne_test1(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def plusOne_test1(self, digits):
""":type digits: List[int] :rtype: List[int]"""
if digits is None or len(digits) == 0:
return [1]
temp = [str(i) for i in digits]
number = int(''.join(temp))
return [int(i) for i in list(str(number + 1))]
def p... | the_stack_v2_python_sparse | array_66.py | cainingning/leetcode | train | 1 | |
b188cb26da96f57214e1dff8e4b8839a5ee3cb35 | [
"if not isinstance(style_image, np.ndarray) or len(style_image.shape) != 3 or style_image.shape[2] != 3:\n msg = 'style_image must be a numpy.ndarray with shape (h, w, 3)'\n raise TypeError(msg)\nif not isinstance(content_image, np.ndarray) or len(content_image.shape) != 3 or content_image.shape[2] != 3:\n ... | <|body_start_0|>
if not isinstance(style_image, np.ndarray) or len(style_image.shape) != 3 or style_image.shape[2] != 3:
msg = 'style_image must be a numpy.ndarray with shape (h, w, 3)'
raise TypeError(msg)
if not isinstance(content_image, np.ndarray) or len(content_image.shape) ... | class NTS | NST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NST:
"""class NTS"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""- style_image - the image used as a style reference, stored as a numpy.ndarray - content_image - the image used as a content reference, stored as a numpy.ndarray - alpha - the weight for co... | stack_v2_sparse_classes_36k_train_003274 | 3,522 | no_license | [
{
"docstring": "- style_image - the image used as a style reference, stored as a numpy.ndarray - content_image - the image used as a content reference, stored as a numpy.ndarray - alpha - the weight for content cost - beta - the weight for style cost if style_image is not a np.ndarray with the shape (h, w, 3), ... | 2 | null | Implement the Python class `NST` described below.
Class description:
class NTS
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): - style_image - the image used as a style reference, stored as a numpy.ndarray - content_image - the image used as a content referen... | Implement the Python class `NST` described below.
Class description:
class NTS
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): - style_image - the image used as a style reference, stored as a numpy.ndarray - content_image - the image used as a content referen... | e10b4e9b6f3fa00639e6e9e5b35f0cdb43a339a3 | <|skeleton|>
class NST:
"""class NTS"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""- style_image - the image used as a style reference, stored as a numpy.ndarray - content_image - the image used as a content reference, stored as a numpy.ndarray - alpha - the weight for co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NST:
"""class NTS"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""- style_image - the image used as a style reference, stored as a numpy.ndarray - content_image - the image used as a content reference, stored as a numpy.ndarray - alpha - the weight for content cost - ... | the_stack_v2_python_sparse | supervised_learning/0x0C-neural_style_transfer/0-neural_style.py | HeimerR/holbertonschool-machine_learning | train | 0 |
bc7944b49b909ba4cc58b54103ff442e53e06a61 | [
"a = range(10)\nself.assertTrue(isinstance(a, Iterable), 'should be Iterable')\nself.assertFalse(isinstance(a, Iterator), 'should not be Iterator')\nself.assertFalse(isinstance(a, Generator))",
"b = list((1, 2, 3))\nself.assertTrue(isinstance(b, Collection))\nself.assertFalse(isinstance(b, Hashable))"
] | <|body_start_0|>
a = range(10)
self.assertTrue(isinstance(a, Iterable), 'should be Iterable')
self.assertFalse(isinstance(a, Iterator), 'should not be Iterator')
self.assertFalse(isinstance(a, Generator))
<|end_body_0|>
<|body_start_1|>
b = list((1, 2, 3))
self.assertTru... | test_collections_abc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_collections_abc:
def test1(self):
"""check if range is Iterable / Iterator"""
<|body_0|>
def test2(self):
"""check if list is Collection / Hashable"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
a = range(10)
self.assertTrue(isinstance... | stack_v2_sparse_classes_36k_train_003275 | 690 | no_license | [
{
"docstring": "check if range is Iterable / Iterator",
"name": "test1",
"signature": "def test1(self)"
},
{
"docstring": "check if list is Collection / Hashable",
"name": "test2",
"signature": "def test2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008303 | Implement the Python class `test_collections_abc` described below.
Class description:
Implement the test_collections_abc class.
Method signatures and docstrings:
- def test1(self): check if range is Iterable / Iterator
- def test2(self): check if list is Collection / Hashable | Implement the Python class `test_collections_abc` described below.
Class description:
Implement the test_collections_abc class.
Method signatures and docstrings:
- def test1(self): check if range is Iterable / Iterator
- def test2(self): check if list is Collection / Hashable
<|skeleton|>
class test_collections_abc:... | 3fee49a50f05430f9f0c4cc7f7bd905a490fe201 | <|skeleton|>
class test_collections_abc:
def test1(self):
"""check if range is Iterable / Iterator"""
<|body_0|>
def test2(self):
"""check if list is Collection / Hashable"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_collections_abc:
def test1(self):
"""check if range is Iterable / Iterator"""
a = range(10)
self.assertTrue(isinstance(a, Iterable), 'should be Iterable')
self.assertFalse(isinstance(a, Iterator), 'should not be Iterator')
self.assertFalse(isinstance(a, Generator))... | the_stack_v2_python_sparse | Package_And_Syntax/collections/abc.py | AaronYXZ/PyFullStack | train | 0 | |
c9006bda98f9120331d6fe47d375fa35fc3a3152 | [
"while dup_char != s[left]:\n ch_set.remove(s[left])\n left += 1\nreturn left + 1",
"s_len = len(s)\nif s_len <= 1:\n return s_len\nch_set = set()\nch_set.add(s[0])\nmax_len = 1\nleft = 0\nright = 1\nwhile right < s_len:\n ch = s[right]\n if ch not in ch_set:\n ch_set.add(ch)\n max_le... | <|body_start_0|>
while dup_char != s[left]:
ch_set.remove(s[left])
left += 1
return left + 1
<|end_body_0|>
<|body_start_1|>
s_len = len(s)
if s_len <= 1:
return s_len
ch_set = set()
ch_set.add(s[0])
max_len = 1
left = ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def update_left_index_and_char_set(self, s, left, dup_char, ch_set):
"""1. find the index of dup char in s[left: right+1]. 2.1. if index of dup char == s[left] then no need to add s[right] in ch_set. 2.2. if index of dup char != s[left] then ch_set should only have chars which ... | stack_v2_sparse_classes_36k_train_003276 | 1,891 | permissive | [
{
"docstring": "1. find the index of dup char in s[left: right+1]. 2.1. if index of dup char == s[left] then no need to add s[right] in ch_set. 2.2. if index of dup char != s[left] then ch_set should only have chars which is in s[index of dup char: right+1].",
"name": "update_left_index_and_char_set",
"... | 2 | stack_v2_sparse_classes_30k_train_009208 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def update_left_index_and_char_set(self, s, left, dup_char, ch_set): 1. find the index of dup char in s[left: right+1]. 2.1. if index of dup char == s[left] then no need to add s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def update_left_index_and_char_set(self, s, left, dup_char, ch_set): 1. find the index of dup char in s[left: right+1]. 2.1. if index of dup char == s[left] then no need to add s... | c7e5b6692ad6772b38de8be029bddf0e273e0bce | <|skeleton|>
class Solution:
def update_left_index_and_char_set(self, s, left, dup_char, ch_set):
"""1. find the index of dup char in s[left: right+1]. 2.1. if index of dup char == s[left] then no need to add s[right] in ch_set. 2.2. if index of dup char != s[left] then ch_set should only have chars which ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def update_left_index_and_char_set(self, s, left, dup_char, ch_set):
"""1. find the index of dup char in s[left: right+1]. 2.1. if index of dup char == s[left] then no need to add s[right] in ch_set. 2.2. if index of dup char != s[left] then ch_set should only have chars which is in s[index ... | the_stack_v2_python_sparse | arr_str/longest_substring_without_repeating_chars.py | mantoshkumar1/interview_preparation | train | 1 | |
160446a2f3e1d695680252c4458d31cf4d6f8173 | [
"dp = [0] * (amount + 1)\ndp[0] = 1\nfor coin in coins:\n for i in range(coin, amount + 1):\n dp[i] += dp[i - coin]\nreturn dp[amount]",
"dp = [0] * (amount + 1)\ndp[0] = 1\ncoins.sort()\nfor i in range(1, amount + 1):\n for coin in coins:\n if i - coin > -1:\n dp[i] += dp[i - coin]... | <|body_start_0|>
dp = [0] * (amount + 1)
dp[0] = 1
for coin in coins:
for i in range(coin, amount + 1):
dp[i] += dp[i - coin]
return dp[amount]
<|end_body_0|>
<|body_start_1|>
dp = [0] * (amount + 1)
dp[0] = 1
coins.sort()
for ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def change_Wrong(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_003277 | 2,543 | no_license | [
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change",
"signature": "def change(self, amount, coins)"
},
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change_Wrong",
"signature": "def change_Wrong(self, amount, coins)"
... | 2 | stack_v2_sparse_classes_30k_train_020077 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def change_Wrong(self, amount, coins): :type amount: int :type coins: List[int] :rtype: in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def change_Wrong(self, amount, coins): :type amount: int :type coins: List[int] :rtype: in... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def change_Wrong(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
dp = [0] * (amount + 1)
dp[0] = 1
for coin in coins:
for i in range(coin, amount + 1):
dp[i] += dp[i - coin]
return dp[amount]
def chan... | the_stack_v2_python_sparse | code518CoinChange2.py | cybelewang/leetcode-python | train | 0 | |
78db134fffac10f1e3c757a6506cbf1135214a5f | [
"rawline = self.file.readline()\nwhile rawline:\n rematch = self.line_re.match(rawline)\n if not rematch:\n rawline = self.file.readline()\n continue\n while rematch:\n rep = Replica()\n self.reps.append(rep)\n rep.index = [0 for i in range(self.numexchg)]\n rep.pr... | <|body_start_0|>
rawline = self.file.readline()
while rawline:
rematch = self.line_re.match(rawline)
if not rematch:
rawline = self.file.readline()
continue
while rematch:
rep = Replica()
self.reps.append... | A class for a rem.log file in pH exchange | pHRemLog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pHRemLog:
"""A class for a rem.log file in pH exchange"""
def _get_replicas(self):
"""Gets all of the replica information from the first block of repinfo"""
<|body_0|>
def _parse(self):
"""Parses the rem.log file and loads the data arrays"""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_003278 | 12,296 | no_license | [
{
"docstring": "Gets all of the replica information from the first block of repinfo",
"name": "_get_replicas",
"signature": "def _get_replicas(self)"
},
{
"docstring": "Parses the rem.log file and loads the data arrays",
"name": "_parse",
"signature": "def _parse(self)"
}
] | 2 | null | Implement the Python class `pHRemLog` described below.
Class description:
A class for a rem.log file in pH exchange
Method signatures and docstrings:
- def _get_replicas(self): Gets all of the replica information from the first block of repinfo
- def _parse(self): Parses the rem.log file and loads the data arrays | Implement the Python class `pHRemLog` described below.
Class description:
A class for a rem.log file in pH exchange
Method signatures and docstrings:
- def _get_replicas(self): Gets all of the replica information from the first block of repinfo
- def _parse(self): Parses the rem.log file and loads the data arrays
<|... | 5cec8112637be7a19c4aac893f612aa8c354b733 | <|skeleton|>
class pHRemLog:
"""A class for a rem.log file in pH exchange"""
def _get_replicas(self):
"""Gets all of the replica information from the first block of repinfo"""
<|body_0|>
def _parse(self):
"""Parses the rem.log file and loads the data arrays"""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class pHRemLog:
"""A class for a rem.log file in pH exchange"""
def _get_replicas(self):
"""Gets all of the replica information from the first block of repinfo"""
rawline = self.file.readline()
while rawline:
rematch = self.line_re.match(rawline)
if not rematch:
... | the_stack_v2_python_sparse | remd.py | jeff-wang/JmsScripts | train | 0 |
bf1b0bda59cd12f84b4b2d773bf8c8b5572cf2db | [
"farthest_index_possible = 0\nfor i, n in enumerate(nums):\n if i > farthest_index_possible:\n return False\n farthest_index_possible = max(farthest_index_possible, i + n)\nreturn True",
"goal = len(nums) - 1\nfor i in range(len(nums))[::-1]:\n if i + nums[i] >= goal:\n goal = i\nreturn goa... | <|body_start_0|>
farthest_index_possible = 0
for i, n in enumerate(nums):
if i > farthest_index_possible:
return False
farthest_index_possible = max(farthest_index_possible, i + n)
return True
<|end_body_0|>
<|body_start_1|>
goal = len(nums) - 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def can_jump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def can_jump2(self, nums):
"""going back version"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
farthest_index_possible = 0
for i, n in enumerate(nums):... | stack_v2_sparse_classes_36k_train_003279 | 608 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "can_jump",
"signature": "def can_jump(self, nums)"
},
{
"docstring": "going back version",
"name": "can_jump2",
"signature": "def can_jump2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def can_jump(self, nums): :type nums: List[int] :rtype: bool
- def can_jump2(self, nums): going back version | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def can_jump(self, nums): :type nums: List[int] :rtype: bool
- def can_jump2(self, nums): going back version
<|skeleton|>
class Solution:
def can_jump(self, nums):
... | 2b7f4a9fefbfd358f8ff31362d60e2007641ca29 | <|skeleton|>
class Solution:
def can_jump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def can_jump2(self, nums):
"""going back version"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def can_jump(self, nums):
""":type nums: List[int] :rtype: bool"""
farthest_index_possible = 0
for i, n in enumerate(nums):
if i > farthest_index_possible:
return False
farthest_index_possible = max(farthest_index_possible, i + n)
... | the_stack_v2_python_sparse | Week_03/G20190343020166/LeetCode_55_0166.py | algorithm005-class01/algorithm005-class01 | train | 27 | |
987d42df036be470f2e3fad417894d620094dcb2 | [
"if not self.context['user'].check_password(data['old_password']):\n raise serializers.ValidationError('Wrong password.')\nif data['password_confirmation'] != data['password']:\n raise serializers.ValidationError('Password don´t match')\npassword_validation.validate_password(data['password'])\nreturn data",
... | <|body_start_0|>
if not self.context['user'].check_password(data['old_password']):
raise serializers.ValidationError('Wrong password.')
if data['password_confirmation'] != data['password']:
raise serializers.ValidationError('Password don´t match')
password_validation.vali... | Update user's password serializer. | UpdatePasswordSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdatePasswordSerializer:
"""Update user's password serializer."""
def validate(self, data):
"""Check password."""
<|body_0|>
def save(self):
"""Update user's password."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.context['user'].... | stack_v2_sparse_classes_36k_train_003280 | 8,178 | no_license | [
{
"docstring": "Check password.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Update user's password.",
"name": "save",
"signature": "def save(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008898 | Implement the Python class `UpdatePasswordSerializer` described below.
Class description:
Update user's password serializer.
Method signatures and docstrings:
- def validate(self, data): Check password.
- def save(self): Update user's password. | Implement the Python class `UpdatePasswordSerializer` described below.
Class description:
Update user's password serializer.
Method signatures and docstrings:
- def validate(self, data): Check password.
- def save(self): Update user's password.
<|skeleton|>
class UpdatePasswordSerializer:
"""Update user's passwo... | fae5c0b2e388239e2e32a3fbf52aa7cfd48a7cbb | <|skeleton|>
class UpdatePasswordSerializer:
"""Update user's password serializer."""
def validate(self, data):
"""Check password."""
<|body_0|>
def save(self):
"""Update user's password."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdatePasswordSerializer:
"""Update user's password serializer."""
def validate(self, data):
"""Check password."""
if not self.context['user'].check_password(data['old_password']):
raise serializers.ValidationError('Wrong password.')
if data['password_confirmation'] !=... | the_stack_v2_python_sparse | facebook/app/users/serializers/users.py | ricagome/Api-Facebook-Clone | train | 0 |
61bfc19da0779244235db93beb4dbfee8bedc1fd | [
"self.name = 'legendre associated'\nself.m = m\nself.lmax = lmax\nself.n = lmax - m + 1\nself.jc = '1'",
"def b(i, m):\n return (2.0 * float(i) - 1.0) / float(i - m)\n\ndef c(i, m):\n return (-float(i + m) + 1.0) / float(i - m)\n\ndef double_factorial(n):\n m = n\n f = 1\n while m > 1:\n f *... | <|body_start_0|>
self.name = 'legendre associated'
self.m = m
self.lmax = lmax
self.n = lmax - m + 1
self.jc = '1'
<|end_body_0|>
<|body_start_1|>
def b(i, m):
return (2.0 * float(i) - 1.0) / float(i - m)
def c(i, m):
return (-float(i + m... | associated legendre functions | LegendreAssociated | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LegendreAssociated:
"""associated legendre functions"""
def __init__(self, lmax, m):
"""P^(m)_l, l=m,lmax lmax.....number of functions"""
<|body_0|>
def val(self, q):
"""values and derivatives up to ORDER n (degree n-1)"""
<|body_1|>
def normY(self, ... | stack_v2_sparse_classes_36k_train_003281 | 10,347 | no_license | [
{
"docstring": "P^(m)_l, l=m,lmax lmax.....number of functions",
"name": "__init__",
"signature": "def __init__(self, lmax, m)"
},
{
"docstring": "values and derivatives up to ORDER n (degree n-1)",
"name": "val",
"signature": "def val(self, q)"
},
{
"docstring": "norm for spheri... | 3 | stack_v2_sparse_classes_30k_train_003863 | Implement the Python class `LegendreAssociated` described below.
Class description:
associated legendre functions
Method signatures and docstrings:
- def __init__(self, lmax, m): P^(m)_l, l=m,lmax lmax.....number of functions
- def val(self, q): values and derivatives up to ORDER n (degree n-1)
- def normY(self, l, m... | Implement the Python class `LegendreAssociated` described below.
Class description:
associated legendre functions
Method signatures and docstrings:
- def __init__(self, lmax, m): P^(m)_l, l=m,lmax lmax.....number of functions
- def val(self, q): values and derivatives up to ORDER n (degree n-1)
- def normY(self, l, m... | 149563c91a44db6badc0b93af81f107313952a88 | <|skeleton|>
class LegendreAssociated:
"""associated legendre functions"""
def __init__(self, lmax, m):
"""P^(m)_l, l=m,lmax lmax.....number of functions"""
<|body_0|>
def val(self, q):
"""values and derivatives up to ORDER n (degree n-1)"""
<|body_1|>
def normY(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LegendreAssociated:
"""associated legendre functions"""
def __init__(self, lmax, m):
"""P^(m)_l, l=m,lmax lmax.....number of functions"""
self.name = 'legendre associated'
self.m = m
self.lmax = lmax
self.n = lmax - m + 1
self.jc = '1'
def val(self, q)... | the_stack_v2_python_sparse | python/basisfunction.py | deyh2020/Thesis-Theoretikum | train | 0 |
4df5eb94212597bef293f643dc197a4fe86c3856 | [
"if name == 'quiet':\n return self.level >= VERB_QUIET\nelif name == 'low':\n return self.level >= VERB_LOW\nelif name == 'medium':\n return self.level >= VERB_MEDIUM\nelif name == 'high':\n return self.level >= VERB_HIGH\nelif name == 'debug':\n return self.level >= VERB_DEBUG\nelif name == 'trace':... | <|body_start_0|>
if name == 'quiet':
return self.level >= VERB_QUIET
elif name == 'low':
return self.level >= VERB_LOW
elif name == 'medium':
return self.level >= VERB_MEDIUM
elif name == 'high':
return self.level >= VERB_HIGH
elif ... | Class used to determine what to print to standard output. Attributes: level: Determines what level of output to print. | Verbosity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Verbosity:
"""Class used to determine what to print to standard output. Attributes: level: Determines what level of output to print."""
def __getattr__(self, name):
"""Determines whether a certain verbosity level is less than or greater than the stored value. Used to decide whether o... | stack_v2_sparse_classes_36k_train_003282 | 4,128 | no_license | [
{
"docstring": "Determines whether a certain verbosity level is less than or greater than the stored value. Used to decide whether or not a certain info or warning string should be output. Args: name: The verbosity level at which the info/warning string will be output.",
"name": "__getattr__",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_017308 | Implement the Python class `Verbosity` described below.
Class description:
Class used to determine what to print to standard output. Attributes: level: Determines what level of output to print.
Method signatures and docstrings:
- def __getattr__(self, name): Determines whether a certain verbosity level is less than o... | Implement the Python class `Verbosity` described below.
Class description:
Class used to determine what to print to standard output. Attributes: level: Determines what level of output to print.
Method signatures and docstrings:
- def __getattr__(self, name): Determines whether a certain verbosity level is less than o... | 57f255266d4668bafef0881d1e7cbf8a27270ddd | <|skeleton|>
class Verbosity:
"""Class used to determine what to print to standard output. Attributes: level: Determines what level of output to print."""
def __getattr__(self, name):
"""Determines whether a certain verbosity level is less than or greater than the stored value. Used to decide whether o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Verbosity:
"""Class used to determine what to print to standard output. Attributes: level: Determines what level of output to print."""
def __getattr__(self, name):
"""Determines whether a certain verbosity level is less than or greater than the stored value. Used to decide whether or not a certa... | the_stack_v2_python_sparse | ipi/utils/messages.py | i-pi/i-pi | train | 170 |
5c4de32d56e40c3287fb1827e6cca6cf0be20ef9 | [
"self.conf = dict(conf.items('recognizer'))\ndefault = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'defaults', type(self).__name__.lower() + '.cfg')\napply_defaults(self.conf, default)\nself.expdir = expdir\nself.model = model\ninput_sections = [self.conf[i].split(' ') for i in self.model.input_names]... | <|body_start_0|>
self.conf = dict(conf.items('recognizer'))
default = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'defaults', type(self).__name__.lower() + '.cfg')
apply_defaults(self.conf, default)
self.expdir = expdir
self.model = model
input_sections = [s... | a Recognizer can use a model to produce decode stores the results on disk | Recognizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Recognizer:
"""a Recognizer can use a model to produce decode stores the results on disk"""
def __init__(self, model, conf, dataconf, expdir):
"""Recognizer constructor Args: model: the model to be tested conf: the recognizer configuration as a configparser modelconf: the model confi... | stack_v2_sparse_classes_36k_train_003283 | 5,170 | permissive | [
{
"docstring": "Recognizer constructor Args: model: the model to be tested conf: the recognizer configuration as a configparser modelconf: the model configuration as a configparser dataconf: the database configuration as a configparser expdir: the experiments directory",
"name": "__init__",
"signature":... | 2 | null | Implement the Python class `Recognizer` described below.
Class description:
a Recognizer can use a model to produce decode stores the results on disk
Method signatures and docstrings:
- def __init__(self, model, conf, dataconf, expdir): Recognizer constructor Args: model: the model to be tested conf: the recognizer c... | Implement the Python class `Recognizer` described below.
Class description:
a Recognizer can use a model to produce decode stores the results on disk
Method signatures and docstrings:
- def __init__(self, model, conf, dataconf, expdir): Recognizer constructor Args: model: the model to be tested conf: the recognizer c... | 313018a46f68cec1d4a7eb15b8b1cf68111a959c | <|skeleton|>
class Recognizer:
"""a Recognizer can use a model to produce decode stores the results on disk"""
def __init__(self, model, conf, dataconf, expdir):
"""Recognizer constructor Args: model: the model to be tested conf: the recognizer configuration as a configparser modelconf: the model confi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Recognizer:
"""a Recognizer can use a model to produce decode stores the results on disk"""
def __init__(self, model, conf, dataconf, expdir):
"""Recognizer constructor Args: model: the model to be tested conf: the recognizer configuration as a configparser modelconf: the model configuration as a... | the_stack_v2_python_sparse | nabu/neuralnetworks/recognizer.py | ishandutta2007/nabu | train | 0 |
a70e8c7d6e009e2e4edd8c0a16d64ea8c954f8b7 | [
"UserModel = get_user_model()\ntry:\n user = UserModel._default_manager.get(social_profile_id=username)\n if user.check_password(password):\n return user\nexcept UserModel.DoesNotExist:\n return None",
"UserModel = get_user_model()\ntry:\n return UserModel.objects.get(pk=user_id)\nexcept UserMo... | <|body_start_0|>
UserModel = get_user_model()
try:
user = UserModel._default_manager.get(social_profile_id=username)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
return None
<|end_body_0|>
<|body_start_1|>
... | This Authentication Backend Authenticates a User Against the Social Id | SocialProfileIdAuthenticationBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SocialProfileIdAuthenticationBackend:
"""This Authentication Backend Authenticates a User Against the Social Id"""
def authenticate(self, username=None, password=None):
"""Authenticate Using the Mobile/password And Return a User"""
<|body_0|>
def get_user(self, user_id):... | stack_v2_sparse_classes_36k_train_003284 | 2,708 | no_license | [
{
"docstring": "Authenticate Using the Mobile/password And Return a User",
"name": "authenticate",
"signature": "def authenticate(self, username=None, password=None)"
},
{
"docstring": "Returns a User Against a Given User Id",
"name": "get_user",
"signature": "def get_user(self, user_id)... | 2 | stack_v2_sparse_classes_30k_train_003380 | Implement the Python class `SocialProfileIdAuthenticationBackend` described below.
Class description:
This Authentication Backend Authenticates a User Against the Social Id
Method signatures and docstrings:
- def authenticate(self, username=None, password=None): Authenticate Using the Mobile/password And Return a Use... | Implement the Python class `SocialProfileIdAuthenticationBackend` described below.
Class description:
This Authentication Backend Authenticates a User Against the Social Id
Method signatures and docstrings:
- def authenticate(self, username=None, password=None): Authenticate Using the Mobile/password And Return a Use... | 3bb9fe2e3fe8d876519631233fb29c7e04e2e8c3 | <|skeleton|>
class SocialProfileIdAuthenticationBackend:
"""This Authentication Backend Authenticates a User Against the Social Id"""
def authenticate(self, username=None, password=None):
"""Authenticate Using the Mobile/password And Return a User"""
<|body_0|>
def get_user(self, user_id):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SocialProfileIdAuthenticationBackend:
"""This Authentication Backend Authenticates a User Against the Social Id"""
def authenticate(self, username=None, password=None):
"""Authenticate Using the Mobile/password And Return a User"""
UserModel = get_user_model()
try:
use... | the_stack_v2_python_sparse | accounts/backends.py | Mr4x3/competition_mania | train | 0 |
ec962d1305685fc8f3b715e27d1555bcb3ae559c | [
"objs = query.order_by(order_by).limit(results_per_page + 1).offset((page - 1) * results_per_page).all()\nextra = objs.pop() if len(objs) > results_per_page else None\ncollection = {'page': page, 'next_page': page + (1 if extra else 0), 'prev_page': max(page - 1, 1), 'results_per_page': results_per_page, 'collectio... | <|body_start_0|>
objs = query.order_by(order_by).limit(results_per_page + 1).offset((page - 1) * results_per_page).all()
extra = objs.pop() if len(objs) > results_per_page else None
collection = {'page': page, 'next_page': page + (1 if extra else 0), 'prev_page': max(page - 1, 1), 'results_per_p... | Base DOM Resource | Resource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resource:
"""Base DOM Resource"""
def paged(cls, query, page, results_per_page, order_by, **kwargs):
"""Return a collection-like dict for a paginated (not cursored) collection results set"""
<|body_0|>
def generic_insert(cls, db, api, Model, data, url_field, url_cls=None... | stack_v2_sparse_classes_36k_train_003285 | 11,612 | no_license | [
{
"docstring": "Return a collection-like dict for a paginated (not cursored) collection results set",
"name": "paged",
"signature": "def paged(cls, query, page, results_per_page, order_by, **kwargs)"
},
{
"docstring": "Post helper method",
"name": "generic_insert",
"signature": "def gene... | 4 | stack_v2_sparse_classes_30k_train_010774 | Implement the Python class `Resource` described below.
Class description:
Base DOM Resource
Method signatures and docstrings:
- def paged(cls, query, page, results_per_page, order_by, **kwargs): Return a collection-like dict for a paginated (not cursored) collection results set
- def generic_insert(cls, db, api, Mode... | Implement the Python class `Resource` described below.
Class description:
Base DOM Resource
Method signatures and docstrings:
- def paged(cls, query, page, results_per_page, order_by, **kwargs): Return a collection-like dict for a paginated (not cursored) collection results set
- def generic_insert(cls, db, api, Mode... | dbba9f3b292ffef6ea924608fa54237171f0aaeb | <|skeleton|>
class Resource:
"""Base DOM Resource"""
def paged(cls, query, page, results_per_page, order_by, **kwargs):
"""Return a collection-like dict for a paginated (not cursored) collection results set"""
<|body_0|>
def generic_insert(cls, db, api, Model, data, url_field, url_cls=None... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Resource:
"""Base DOM Resource"""
def paged(cls, query, page, results_per_page, order_by, **kwargs):
"""Return a collection-like dict for a paginated (not cursored) collection results set"""
objs = query.order_by(order_by).limit(results_per_page + 1).offset((page - 1) * results_per_page).... | the_stack_v2_python_sparse | lib/python/core/directorofme/flask/api.py | DirectorOfMe/directorof.me | train | 0 |
6698bf23c0b2c56e9ed01eb69856858c1476a036 | [
"if action == 'LEFT':\n tower_chosen = self.world.objects.find(name='tower', label=0)[0]\nelif action == 'DOWN':\n tower_chosen = self.world.objects.find(name='tower', label=1)[0]\nelif action == 'RIGHT':\n tower_chosen = self.world.objects.find(name='tower', label=2)[0]\nelse:\n return\nif self._active... | <|body_start_0|>
if action == 'LEFT':
tower_chosen = self.world.objects.find(name='tower', label=0)[0]
elif action == 'DOWN':
tower_chosen = self.world.objects.find(name='tower', label=1)[0]
elif action == 'RIGHT':
tower_chosen = self.world.objects.find(name='... | Attribute that lets the player use LEFT, DOWN, RIGHT actions to play Hanoi. | PlaysHanoiClickObjectAttribute | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaysHanoiClickObjectAttribute:
"""Attribute that lets the player use LEFT, DOWN, RIGHT actions to play Hanoi."""
def _execute_action(self, obj, t, dt, agent_id, action):
"""Listen for LEFT/DOWN/RIGHT commands and manipulate the disks. Parameters ---------- obj : Object The object th... | stack_v2_sparse_classes_36k_train_003286 | 10,404 | permissive | [
{
"docstring": "Listen for LEFT/DOWN/RIGHT commands and manipulate the disks. Parameters ---------- obj : Object The object that has the 'gripper' attribute. t : number The simulation time. dt : number The time since the last step. agent_id : int The id of the agent that is currently stepping. action : string T... | 2 | null | Implement the Python class `PlaysHanoiClickObjectAttribute` described below.
Class description:
Attribute that lets the player use LEFT, DOWN, RIGHT actions to play Hanoi.
Method signatures and docstrings:
- def _execute_action(self, obj, t, dt, agent_id, action): Listen for LEFT/DOWN/RIGHT commands and manipulate th... | Implement the Python class `PlaysHanoiClickObjectAttribute` described below.
Class description:
Attribute that lets the player use LEFT, DOWN, RIGHT actions to play Hanoi.
Method signatures and docstrings:
- def _execute_action(self, obj, t, dt, agent_id, action): Listen for LEFT/DOWN/RIGHT commands and manipulate th... | 4a287e820fbb62bfc2b3b3d08df282329df4c2b1 | <|skeleton|>
class PlaysHanoiClickObjectAttribute:
"""Attribute that lets the player use LEFT, DOWN, RIGHT actions to play Hanoi."""
def _execute_action(self, obj, t, dt, agent_id, action):
"""Listen for LEFT/DOWN/RIGHT commands and manipulate the disks. Parameters ---------- obj : Object The object th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlaysHanoiClickObjectAttribute:
"""Attribute that lets the player use LEFT, DOWN, RIGHT actions to play Hanoi."""
def _execute_action(self, obj, t, dt, agent_id, action):
"""Listen for LEFT/DOWN/RIGHT commands and manipulate the disks. Parameters ---------- obj : Object The object that has the 'g... | the_stack_v2_python_sparse | pixelworld/envs/pixelworld/library/world/hanoi.py | fenfeibani/pixelworld | train | 0 |
3be89b0d9fdef12c76500bab4265a77e579a1583 | [
"cleaned_data = super(UserSignUpForm, self).clean()\ntry:\n original_password = cleaned_data['password']\n confirm_password = cleaned_data['password_confirm']\nexcept KeyError:\n return cleaned_data\nif original_password != confirm_password:\n raise forms.ValidationError('الباسورد مش متطابق.')\nreturn c... | <|body_start_0|>
cleaned_data = super(UserSignUpForm, self).clean()
try:
original_password = cleaned_data['password']
confirm_password = cleaned_data['password_confirm']
except KeyError:
return cleaned_data
if original_password != confirm_password:
... | UserSignUpForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSignUpForm:
def clean(self):
"""cleaned_data -> ValidationError if possible Returns Validation error if and only if: - Confirm_password != original_password"""
<|body_0|>
def clean_password(self):
"""Takes the given password and call django's built-in validators ... | stack_v2_sparse_classes_36k_train_003287 | 3,210 | permissive | [
{
"docstring": "cleaned_data -> ValidationError if possible Returns Validation error if and only if: - Confirm_password != original_password",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Takes the given password and call django's built-in validators on it.",
"name": "c... | 4 | null | Implement the Python class `UserSignUpForm` described below.
Class description:
Implement the UserSignUpForm class.
Method signatures and docstrings:
- def clean(self): cleaned_data -> ValidationError if possible Returns Validation error if and only if: - Confirm_password != original_password
- def clean_password(sel... | Implement the Python class `UserSignUpForm` described below.
Class description:
Implement the UserSignUpForm class.
Method signatures and docstrings:
- def clean(self): cleaned_data -> ValidationError if possible Returns Validation error if and only if: - Confirm_password != original_password
- def clean_password(sel... | 70638c121ea85ff0e6a650c5f2641b0b3b04d6d0 | <|skeleton|>
class UserSignUpForm:
def clean(self):
"""cleaned_data -> ValidationError if possible Returns Validation error if and only if: - Confirm_password != original_password"""
<|body_0|>
def clean_password(self):
"""Takes the given password and call django's built-in validators ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSignUpForm:
def clean(self):
"""cleaned_data -> ValidationError if possible Returns Validation error if and only if: - Confirm_password != original_password"""
cleaned_data = super(UserSignUpForm, self).clean()
try:
original_password = cleaned_data['password']
... | the_stack_v2_python_sparse | users/forms.py | Ibrahem3amer/bala7 | train | 0 | |
067ed5baa300e1f69d74d4c22d1583fe8aafdfa1 | [
"self.iter1 = iter(v1)\nself.iter2 = iter(v2)\nself.ind1 = len(v1)\nself.ind2 = len(v2)\nself.flag = True",
"if self.ind1 > 0 and self.ind2 > 0:\n if self.flag:\n self.flag = False\n self.ind1 -= 1\n return next(self.iter1)\n else:\n self.flag = True\n self.ind2 -= 1\n ... | <|body_start_0|>
self.iter1 = iter(v1)
self.iter2 = iter(v2)
self.ind1 = len(v1)
self.ind2 = len(v2)
self.flag = True
<|end_body_0|>
<|body_start_1|>
if self.ind1 > 0 and self.ind2 > 0:
if self.flag:
self.flag = False
self.ind1... | ZigzagIterator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_36k_train_003288 | 1,240 | permissive | [
{
"docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]",
"name": "__init__",
"signature": "def __init__(self, v1, v2)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name"... | 3 | stack_v2_sparse_classes_30k_train_000495 | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | e7a6906ecc5bce665dec5d0f057b302a64d50f40 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
self.iter1 = iter(v1)
self.iter2 = iter(v2)
self.ind1 = len(v1)
self.ind2 = len(v2)
self.flag = True
def next(self):
""":r... | the_stack_v2_python_sparse | design/ZigzagIterator.py | mengyangbai/leetcode | train | 0 | |
ccf35e15e8a3733d23717b9fe248d3ebdb681fd0 | [
"user_model = get_user_model()\nuser_inum = get_user_info(access_token)\nidp_uuid = user_inum.get('inum', '')\nuser = None\ntry:\n user = user_model.objects.get(idp_uuid=idp_uuid)\nexcept user_model.DoesNotExist:\n user = user_model(idp_uuid=idp_uuid)\nuser_info = get_user(idp_uuid)\ntry:\n user.update_fro... | <|body_start_0|>
user_model = get_user_model()
user_inum = get_user_info(access_token)
idp_uuid = user_inum.get('inum', '')
user = None
try:
user = user_model.objects.get(idp_uuid=idp_uuid)
except user_model.DoesNotExist:
user = user_model(idp_uuid... | OpenIdBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenIdBackend:
def authenticate(self, request, access_token=None, id_token=None):
"""Authenticate against IDP using access token gotten after callback. :param request: request object to set user to. :param access_token: Access token after login is successful. (Gotten from authorization c... | stack_v2_sparse_classes_36k_train_003289 | 1,723 | no_license | [
{
"docstring": "Authenticate against IDP using access token gotten after callback. :param request: request object to set user to. :param access_token: Access token after login is successful. (Gotten from authorization code returned during the callback.) :param id_token: Id token to be used as hint during logout... | 2 | stack_v2_sparse_classes_30k_train_015885 | Implement the Python class `OpenIdBackend` described below.
Class description:
Implement the OpenIdBackend class.
Method signatures and docstrings:
- def authenticate(self, request, access_token=None, id_token=None): Authenticate against IDP using access token gotten after callback. :param request: request object to ... | Implement the Python class `OpenIdBackend` described below.
Class description:
Implement the OpenIdBackend class.
Method signatures and docstrings:
- def authenticate(self, request, access_token=None, id_token=None): Authenticate against IDP using access token gotten after callback. :param request: request object to ... | 1a950a4227c3160170892ad77ce99ce53e70bf4c | <|skeleton|>
class OpenIdBackend:
def authenticate(self, request, access_token=None, id_token=None):
"""Authenticate against IDP using access token gotten after callback. :param request: request object to set user to. :param access_token: Access token after login is successful. (Gotten from authorization c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenIdBackend:
def authenticate(self, request, access_token=None, id_token=None):
"""Authenticate against IDP using access token gotten after callback. :param request: request object to set user to. :param access_token: Access token after login is successful. (Gotten from authorization code returned d... | the_stack_v2_python_sparse | oxd/authentication.py | lifelonglearner127/gluru-backend | train | 0 | |
d35ee51f0b5f8719bcaf23426219d957fc69b013 | [
"vals = []\ncur, stack = (root, [])\nwhile cur or stack:\n while cur:\n vals.append(cur.val)\n stack.append(cur)\n cur = cur.left\n cur = stack.pop()\n cur = cur.right\nreturn ' '.join(map(str, vals))",
"vals = list(map(int, data.split()))\n\ndef build(vals):\n if not vals:\n ... | <|body_start_0|>
vals = []
cur, stack = (root, [])
while cur or stack:
while cur:
vals.append(cur.val)
stack.append(cur)
cur = cur.left
cur = stack.pop()
cur = cur.right
return ' '.join(map(str, vals))
<|... | 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_003290 | 1,361 | 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:... | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | <|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"""
vals = []
cur, stack = (root, [])
while cur or stack:
while cur:
vals.append(cur.val)
stack.append(cur)
cur = ... | the_stack_v2_python_sparse | Python3/0449-Serialize-and-Deserialize-BST/soln-1.py | wyaadarsh/LeetCode-Solutions | train | 0 | |
aacc37bced323ce54f74f856cd1b8297641445b3 | [
"legalMoves = gameState.getLegalActions()\nscores = [self.evaluationFunction(gameState, action) for action in legalMoves]\nbestScore = max(scores)\nbestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\nchosenIndex = random.choice(bestIndices)\n'Add more of your code here if you want t... | <|body_start_0|>
legalMoves = gameState.getLegalActions()
scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
chosenIndex = random.choice(bestInd... | A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. | ReflexAgent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReflexAgent:
"""A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers."""
def getAction(sel... | stack_v2_sparse_classes_36k_train_003291 | 14,208 | no_license | [
{
"docstring": "You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop}",
"... | 2 | null | Implement the Python class `ReflexAgent` described below.
Class description:
A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our me... | Implement the Python class `ReflexAgent` described below.
Class description:
A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our me... | 20d8df6172906337f81583dabb841d66b8f31857 | <|skeleton|>
class ReflexAgent:
"""A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers."""
def getAction(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReflexAgent:
"""A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers."""
def getAction(self, gameState)... | the_stack_v2_python_sparse | new_algs/Optimization+algorithms/Min+conflicts+algorithm/multiAgents.py | coolsnake/JupyterNotebook | train | 0 |
9f4b4e793e2ba1cfd1d562ca89ae425754350eba | [
"field_list = []\ncond = int(hash(tup))\nfor field in tup.fields:\n if cond in annotator.relay_ids:\n field_list.append(compiler_begin(super().visit(field), annotator.compiler))\n else:\n field_list.append(super().visit(field))\nif cond in annotator.relay_ids:\n return compiler_end(Tuple(fiel... | <|body_start_0|>
field_list = []
cond = int(hash(tup))
for field in tup.fields:
if cond in annotator.relay_ids:
field_list.append(compiler_begin(super().visit(field), annotator.compiler))
else:
field_list.append(super().visit(field))
... | Annotator for Vitis-AI DPU accelerators | Annotator | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"Zlib",
"LLVM-exception",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Annotator:
"""Annotator for Vitis-AI DPU accelerators"""
def visit_tuple(self, tup):
"""Add compiler_begin and compiler_end annotations to Tuple"""
<|body_0|>
def visit_tuple_getitem(self, op):
"""Add compiler_begin and compiler_end annotations to TupleGetItem"""... | stack_v2_sparse_classes_36k_train_003292 | 7,525 | permissive | [
{
"docstring": "Add compiler_begin and compiler_end annotations to Tuple",
"name": "visit_tuple",
"signature": "def visit_tuple(self, tup)"
},
{
"docstring": "Add compiler_begin and compiler_end annotations to TupleGetItem",
"name": "visit_tuple_getitem",
"signature": "def visit_tuple_ge... | 3 | null | Implement the Python class `Annotator` described below.
Class description:
Annotator for Vitis-AI DPU accelerators
Method signatures and docstrings:
- def visit_tuple(self, tup): Add compiler_begin and compiler_end annotations to Tuple
- def visit_tuple_getitem(self, op): Add compiler_begin and compiler_end annotatio... | Implement the Python class `Annotator` described below.
Class description:
Annotator for Vitis-AI DPU accelerators
Method signatures and docstrings:
- def visit_tuple(self, tup): Add compiler_begin and compiler_end annotations to Tuple
- def visit_tuple_getitem(self, op): Add compiler_begin and compiler_end annotatio... | d75083cd97ede706338ab413dbc964009456d01b | <|skeleton|>
class Annotator:
"""Annotator for Vitis-AI DPU accelerators"""
def visit_tuple(self, tup):
"""Add compiler_begin and compiler_end annotations to Tuple"""
<|body_0|>
def visit_tuple_getitem(self, op):
"""Add compiler_begin and compiler_end annotations to TupleGetItem"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Annotator:
"""Annotator for Vitis-AI DPU accelerators"""
def visit_tuple(self, tup):
"""Add compiler_begin and compiler_end annotations to Tuple"""
field_list = []
cond = int(hash(tup))
for field in tup.fields:
if cond in annotator.relay_ids:
fi... | the_stack_v2_python_sparse | python/tvm/relay/op/contrib/vitis_ai.py | apache/tvm | train | 4,575 |
22904627e083c0a6c499277dc3315e90328f7250 | [
"result = 1\nmax_result = 0\nmax_list = []\nnums = self.zip(nums)\nreturn max_result",
"num_1 = []\nfor i in range(len(nums)):\n count = 1\n numbers = 0\n if nums[i] != 1 and nums[i] != -1:\n if numbers > 1:\n num_1.append(count)\n num_1.append(nums[i])\n else:\n ... | <|body_start_0|>
result = 1
max_result = 0
max_list = []
nums = self.zip(nums)
return max_result
<|end_body_0|>
<|body_start_1|>
num_1 = []
for i in range(len(nums)):
count = 1
numbers = 0
if nums[i] != 1 and nums[i] != -1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProduct(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def zip(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = 1
max_result = 0
max_li... | stack_v2_sparse_classes_36k_train_003293 | 39,159 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxProduct",
"signature": "def maxProduct(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "zip",
"signature": "def zip(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005453 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, nums): :type nums: List[int] :rtype: int
- def zip(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, nums): :type nums: List[int] :rtype: int
- def zip(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class Solution:
def maxProduct(sel... | f71112f3880b5e77f633c88e075989a9ff2b25b7 | <|skeleton|>
class Solution:
def maxProduct(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def zip(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProduct(self, nums):
""":type nums: List[int] :rtype: int"""
result = 1
max_result = 0
max_list = []
nums = self.zip(nums)
return max_result
def zip(self, nums):
""":type nums: List[int] :rtype: List[int]"""
num_1 = []
... | the_stack_v2_python_sparse | 152. Maximum Product Subarray.py | sherlock1987/Leetcode | train | 0 | |
c471ee1f458492395e2777dbb0d1b023c90e5408 | [
"cur = head\nlength = 0\nwhile cur:\n length += 1\n cur = cur.next\nreturn length",
"head_length = self.length(head)\nbreak_point = head_length // k\nif k == 0 or break_point == 0:\n return head\nb_count = 1\ncur = head\nres_node = ListNode(1)\nres_cur = res_node\nwhile cur and b_count <= break_point:\n ... | <|body_start_0|>
cur = head
length = 0
while cur:
length += 1
cur = cur.next
return length
<|end_body_0|>
<|body_start_1|>
head_length = self.length(head)
break_point = head_length // k
if k == 0 or break_point == 0:
return hea... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def length(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cur = head
lengt... | stack_v2_sparse_classes_36k_train_003294 | 1,292 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "length",
"signature": "def length(self, head)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "reverseKGroup",
"signature": "def reverseKGroup(self, head, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021278 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def length(self, head): :type head: ListNode :rtype: ListNode
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def length(self, head): :type head: ListNode :rtype: ListNode
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
<|skeleton|>
class Solution:... | 9bd2d706f014ce84356ba38fc7801da0285a91d3 | <|skeleton|>
class Solution:
def length(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def length(self, head):
""":type head: ListNode :rtype: ListNode"""
cur = head
length = 0
while cur:
length += 1
cur = cur.next
return length
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: Li... | the_stack_v2_python_sparse | leetcode/reverseKGroup-25.py | pittcat/Algorithm_Practice | train | 0 | |
c166be213f75d32e4cb236b34f1927c601ff7bbc | [
"with patch.object(tasks, 'retrieve_image_data') as retrieve_image_data:\n self.image = Image.objects.create(data_url='https://example.com/1')\nretrieve_image_data.s.assert_called_with(self.image.pk, if_not_retrieved_since=None)\nretrieve_image_data.s.return_value.delay.assert_called_with()",
"with patch.objec... | <|body_start_0|>
with patch.object(tasks, 'retrieve_image_data') as retrieve_image_data:
self.image = Image.objects.create(data_url='https://example.com/1')
retrieve_image_data.s.assert_called_with(self.image.pk, if_not_retrieved_since=None)
retrieve_image_data.s.return_value.delay.a... | TestSignalHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSignalHandler:
def test_queues_retrieve_when_image_created(self):
"""Test signal handler queues retrieve when image created."""
<|body_0|>
def test_doesnt_queue_retrieve_when_retrieved_is_set(self):
"""Test signal handler doesnt queue retrieve when retrieved is s... | stack_v2_sparse_classes_36k_train_003295 | 37,991 | no_license | [
{
"docstring": "Test signal handler queues retrieve when image created.",
"name": "test_queues_retrieve_when_image_created",
"signature": "def test_queues_retrieve_when_image_created(self)"
},
{
"docstring": "Test signal handler doesnt queue retrieve when retrieved is set.",
"name": "test_do... | 3 | null | Implement the Python class `TestSignalHandler` described below.
Class description:
Implement the TestSignalHandler class.
Method signatures and docstrings:
- def test_queues_retrieve_when_image_created(self): Test signal handler queues retrieve when image created.
- def test_doesnt_queue_retrieve_when_retrieved_is_se... | Implement the Python class `TestSignalHandler` described below.
Class description:
Implement the TestSignalHandler class.
Method signatures and docstrings:
- def test_queues_retrieve_when_image_created(self): Test signal handler queues retrieve when image created.
- def test_doesnt_queue_retrieve_when_retrieved_is_se... | 0075ea457f764cbb67acecb584e927bf58d2e7a8 | <|skeleton|>
class TestSignalHandler:
def test_queues_retrieve_when_image_created(self):
"""Test signal handler queues retrieve when image created."""
<|body_0|>
def test_doesnt_queue_retrieve_when_retrieved_is_set(self):
"""Test signal handler doesnt queue retrieve when retrieved is s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSignalHandler:
def test_queues_retrieve_when_image_created(self):
"""Test signal handler queues retrieve when image created."""
with patch.object(tasks, 'retrieve_image_data') as retrieve_image_data:
self.image = Image.objects.create(data_url='https://example.com/1')
re... | the_stack_v2_python_sparse | linotak/images/tests.py | pdc/linotak | train | 0 | |
1d10bdb2cbc2fdaa8034e47c3b04e3904a4d46ab | [
"nparts = 1\nsuper().__init__(((3, nparts), None, np.dtype('float64')))\nself._makeAttributeAndRegister('nparts', 'a0', 'delta', localVars=locals(), readOnly=True)\nself._makeAttributeAndRegister('u0', localVars=locals())",
"f = self.dtype_f(((3, self.nparts), self.init[1], self.init[2]))\nR = np.linalg.norm(part... | <|body_start_0|>
nparts = 1
super().__init__(((3, nparts), None, np.dtype('float64')))
self._makeAttributeAndRegister('nparts', 'a0', 'delta', localVars=locals(), readOnly=True)
self._makeAttributeAndRegister('u0', localVars=locals())
<|end_body_0|>
<|body_start_1|>
f = self.dty... | Example implementing a single particle spiraling in a trap | planewave_single | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class planewave_single:
"""Example implementing a single particle spiraling in a trap"""
def __init__(self, u0, a0, delta):
"""Initialization routine Args: cparams: custom parameters for the example dtype_u: particle data type (will be passed parent class) dtype_f: fields data type (will b... | stack_v2_sparse_classes_36k_train_003296 | 4,111 | permissive | [
{
"docstring": "Initialization routine Args: cparams: custom parameters for the example dtype_u: particle data type (will be passed parent class) dtype_f: fields data type (will be passed parent class)",
"name": "__init__",
"signature": "def __init__(self, u0, a0, delta)"
},
{
"docstring": "Rout... | 5 | null | Implement the Python class `planewave_single` described below.
Class description:
Example implementing a single particle spiraling in a trap
Method signatures and docstrings:
- def __init__(self, u0, a0, delta): Initialization routine Args: cparams: custom parameters for the example dtype_u: particle data type (will ... | Implement the Python class `planewave_single` described below.
Class description:
Example implementing a single particle spiraling in a trap
Method signatures and docstrings:
- def __init__(self, u0, a0, delta): Initialization routine Args: cparams: custom parameters for the example dtype_u: particle data type (will ... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class planewave_single:
"""Example implementing a single particle spiraling in a trap"""
def __init__(self, u0, a0, delta):
"""Initialization routine Args: cparams: custom parameters for the example dtype_u: particle data type (will be passed parent class) dtype_f: fields data type (will b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class planewave_single:
"""Example implementing a single particle spiraling in a trap"""
def __init__(self, u0, a0, delta):
"""Initialization routine Args: cparams: custom parameters for the example dtype_u: particle data type (will be passed parent class) dtype_f: fields data type (will be passed pare... | the_stack_v2_python_sparse | pySDC/playgrounds/Boris/spiraling_particle_ProblemClass.py | Parallel-in-Time/pySDC | train | 30 |
82d3b242eaffbae5137afece02c5254d0b438f74 | [
"lead_time = datetime.timedelta(0)\nlead_times = cls.search([])\nif lead_times:\n lead_time = sum((r.lead_time for r in lead_times if r.lead_time), datetime.timedelta(0))\nextra_lead_times = cls._get_extra_lead_times()\nif extra_lead_times:\n lead_time += max(extra_lead_times)\nreturn lead_time",
"pool = Po... | <|body_start_0|>
lead_time = datetime.timedelta(0)
lead_times = cls.search([])
if lead_times:
lead_time = sum((r.lead_time for r in lead_times if r.lead_time), datetime.timedelta(0))
extra_lead_times = cls._get_extra_lead_times()
if extra_lead_times:
lead_... | LocationLeadTime | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocationLeadTime:
def get_max_lead_time(cls):
"""Return the biggest lead time increased by the maximum extra lead times"""
<|body_0|>
def _get_extra_lead_times(cls):
"""Return a list of extra lead time"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_003297 | 2,143 | no_license | [
{
"docstring": "Return the biggest lead time increased by the maximum extra lead times",
"name": "get_max_lead_time",
"signature": "def get_max_lead_time(cls)"
},
{
"docstring": "Return a list of extra lead time",
"name": "_get_extra_lead_times",
"signature": "def _get_extra_lead_times(c... | 2 | null | Implement the Python class `LocationLeadTime` described below.
Class description:
Implement the LocationLeadTime class.
Method signatures and docstrings:
- def get_max_lead_time(cls): Return the biggest lead time increased by the maximum extra lead times
- def _get_extra_lead_times(cls): Return a list of extra lead t... | Implement the Python class `LocationLeadTime` described below.
Class description:
Implement the LocationLeadTime class.
Method signatures and docstrings:
- def get_max_lead_time(cls): Return the biggest lead time increased by the maximum extra lead times
- def _get_extra_lead_times(cls): Return a list of extra lead t... | 94bd3a4e3fd86556725cdff33b314274dcb20afd | <|skeleton|>
class LocationLeadTime:
def get_max_lead_time(cls):
"""Return the biggest lead time increased by the maximum extra lead times"""
<|body_0|>
def _get_extra_lead_times(cls):
"""Return a list of extra lead time"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocationLeadTime:
def get_max_lead_time(cls):
"""Return the biggest lead time increased by the maximum extra lead times"""
lead_time = datetime.timedelta(0)
lead_times = cls.search([])
if lead_times:
lead_time = sum((r.lead_time for r in lead_times if r.lead_time), ... | the_stack_v2_python_sparse | stock_supply/location.py | saifkazi/tryton_modules | train | 0 | |
548ee70f460f3e609c69a598a2d2f1f1482ec1c9 | [
"super().__init__(parent)\nself.extent = extent\nself.width = width\nself.inner_color = inner_color\nself.outer_color = outer_color",
"pygame.draw.rect(window, self.inner_color, pygame.Rect(self.transform.get_world_position().tuple(), self.extent.tuple()))\nif self.width > 0:\n o = self.transform.get_world_pos... | <|body_start_0|>
super().__init__(parent)
self.extent = extent
self.width = width
self.inner_color = inner_color
self.outer_color = outer_color
<|end_body_0|>
<|body_start_1|>
pygame.draw.rect(window, self.inner_color, pygame.Rect(self.transform.get_world_position().tupl... | Rectangle primitive. Gets rendered as a rectangle on the screen. Attributes: origin The position of the rectangle's top-left corner. extent The position of the rectangle's bottom-right corner. width The width of the rectangle's line. inner_color The color of the rectangle's contents. outer_color The color of the line o... | RectGameObject | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RectGameObject:
"""Rectangle primitive. Gets rendered as a rectangle on the screen. Attributes: origin The position of the rectangle's top-left corner. extent The position of the rectangle's bottom-right corner. width The width of the rectangle's line. inner_color The color of the rectangle's con... | stack_v2_sparse_classes_36k_train_003298 | 3,693 | permissive | [
{
"docstring": "Class constructor. Creates a new instance and defines its values. :param extent The extent of the rectangle. :param width The width of the outline. :param inner_color The color of the inside of the rectangle. :param outer_color The color of the outline of the rectangle.",
"name": "__init__",... | 2 | null | Implement the Python class `RectGameObject` described below.
Class description:
Rectangle primitive. Gets rendered as a rectangle on the screen. Attributes: origin The position of the rectangle's top-left corner. extent The position of the rectangle's bottom-right corner. width The width of the rectangle's line. inner... | Implement the Python class `RectGameObject` described below.
Class description:
Rectangle primitive. Gets rendered as a rectangle on the screen. Attributes: origin The position of the rectangle's top-left corner. extent The position of the rectangle's bottom-right corner. width The width of the rectangle's line. inner... | a2b2d7b6221977e615ce0a0dbc18cb7c1fce05f1 | <|skeleton|>
class RectGameObject:
"""Rectangle primitive. Gets rendered as a rectangle on the screen. Attributes: origin The position of the rectangle's top-left corner. extent The position of the rectangle's bottom-right corner. width The width of the rectangle's line. inner_color The color of the rectangle's con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RectGameObject:
"""Rectangle primitive. Gets rendered as a rectangle on the screen. Attributes: origin The position of the rectangle's top-left corner. extent The position of the rectangle's bottom-right corner. width The width of the rectangle's line. inner_color The color of the rectangle's contents. outer_... | the_stack_v2_python_sparse | engine/logic/Primitives.py | yShimoka/Python-Bataille-Navale | train | 0 |
20a9fac12f7fa89c5539adf2684192258cace31c | [
"dataReaderPaths = self.getDataReaderPaths()\nfor dataReaderPath in dataReaderPaths:\n dataReaderName = splitext(basename(dataReaderPath))[0]\n dataReaderModule = imp.load_source(dataReaderName, dataReaderPath)\n dataReader = getattr(dataReaderModule, dataReaderName)\n testDataReader = dataReader()\n ... | <|body_start_0|>
dataReaderPaths = self.getDataReaderPaths()
for dataReaderPath in dataReaderPaths:
dataReaderName = splitext(basename(dataReaderPath))[0]
dataReaderModule = imp.load_source(dataReaderName, dataReaderPath)
dataReader = getattr(dataReaderModule, dataRea... | Provides functionality to return appropriate product reader for a data product at a specified file path :Methods: .. py:method:: setDataReader(...): Return the appropriate data reader for a data product at a specified file path .. py:method:: getDataReaderPaths(...): Return paths of all available data readers in *eopy.... | ProductDataReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductDataReader:
"""Provides functionality to return appropriate product reader for a data product at a specified file path :Methods: .. py:method:: setDataReader(...): Return the appropriate data reader for a data product at a specified file path .. py:method:: getDataReaderPaths(...): Return ... | stack_v2_sparse_classes_36k_train_003299 | 3,142 | no_license | [
{
"docstring": "Return the appropriate data reader for a data product at a specified file path :type product_path: str :param product_path: The data product file path :return: :DataReader: *eopy.dataIO.AbstractDataReader.AbstractDataReader* Product Data reader",
"name": "setDataReader",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_004950 | Implement the Python class `ProductDataReader` described below.
Class description:
Provides functionality to return appropriate product reader for a data product at a specified file path :Methods: .. py:method:: setDataReader(...): Return the appropriate data reader for a data product at a specified file path .. py:me... | Implement the Python class `ProductDataReader` described below.
Class description:
Provides functionality to return appropriate product reader for a data product at a specified file path :Methods: .. py:method:: setDataReader(...): Return the appropriate data reader for a data product at a specified file path .. py:me... | bea8becf9e71d0acd59121781ae4b029873a3141 | <|skeleton|>
class ProductDataReader:
"""Provides functionality to return appropriate product reader for a data product at a specified file path :Methods: .. py:method:: setDataReader(...): Return the appropriate data reader for a data product at a specified file path .. py:method:: getDataReaderPaths(...): Return ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductDataReader:
"""Provides functionality to return appropriate product reader for a data product at a specified file path :Methods: .. py:method:: setDataReader(...): Return the appropriate data reader for a data product at a specified file path .. py:method:: getDataReaderPaths(...): Return paths of all ... | the_stack_v2_python_sparse | product/productIO/ProductDataReader.py | shunt16/eopy | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.