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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8332f78ab88d09e057188b60ab90513169ab3b8d | [
"matplotlib.use('TkAgg')\nself.fig, self.axs = plt.subplots(1, 1)\nself.title = title\nself.axis_labels = axis_labels\nself.axis_lims = axis_lims\nself.path_store = path_store\nself.prev_name = ''",
"self.axs.cla()\nif self.title:\n self.axs.set_title(self.title)\nif self.axis_labels:\n self.axs.set_xlabel(... | <|body_start_0|>
matplotlib.use('TkAgg')
self.fig, self.axs = plt.subplots(1, 1)
self.title = title
self.axis_labels = axis_labels
self.axis_lims = axis_lims
self.path_store = path_store
self.prev_name = ''
<|end_body_0|>
<|body_start_1|>
self.axs.cla()
... | Class to plot cool RL stuff. | RLPlotter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLPlotter:
"""Class to plot cool RL stuff."""
def __init__(self, title: str=None, axis_labels: Tuple=None, axis_lims: List=None, path_store: str='./saved_elements'):
"""Init class to create a figure. :param title: <str> Title of the figure. :param axis_labels: <str> Axis labels. :par... | stack_v2_sparse_classes_36k_train_005900 | 3,607 | permissive | [
{
"docstring": "Init class to create a figure. :param title: <str> Title of the figure. :param axis_labels: <str> Axis labels. :param axis_lims: <str> Axis limits.",
"name": "__init__",
"signature": "def __init__(self, title: str=None, axis_labels: Tuple=None, axis_lims: List=None, path_store: str='./sa... | 3 | null | Implement the Python class `RLPlotter` described below.
Class description:
Class to plot cool RL stuff.
Method signatures and docstrings:
- def __init__(self, title: str=None, axis_labels: Tuple=None, axis_lims: List=None, path_store: str='./saved_elements'): Init class to create a figure. :param title: <str> Title o... | Implement the Python class `RLPlotter` described below.
Class description:
Class to plot cool RL stuff.
Method signatures and docstrings:
- def __init__(self, title: str=None, axis_labels: Tuple=None, axis_lims: List=None, path_store: str='./saved_elements'): Init class to create a figure. :param title: <str> Title o... | 0e25886083ccefc6cbb6250605c58f018f70a2e9 | <|skeleton|>
class RLPlotter:
"""Class to plot cool RL stuff."""
def __init__(self, title: str=None, axis_labels: Tuple=None, axis_lims: List=None, path_store: str='./saved_elements'):
"""Init class to create a figure. :param title: <str> Title of the figure. :param axis_labels: <str> Axis labels. :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RLPlotter:
"""Class to plot cool RL stuff."""
def __init__(self, title: str=None, axis_labels: Tuple=None, axis_lims: List=None, path_store: str='./saved_elements'):
"""Init class to create a figure. :param title: <str> Title of the figure. :param axis_labels: <str> Axis labels. :param axis_lims:... | the_stack_v2_python_sparse | rl4cs/utils/plotter.py | mit-ccrg/ml4c3-mirror | train | 0 |
04dad3bde5b6e1bb63397c9dfd3492892a45195b | [
"if not nums:\n self.data = []\n return\nn = len(nums) + 1\ndata = [0 for _ in range(n)]\ns = 0\nfor i, v in enumerate(nums):\n s += v\n data[i + 1] = s\nself.data = data",
"if not self.data:\n return 0\nreturn self.data[j + 1] - self.data[i]"
] | <|body_start_0|>
if not nums:
self.data = []
return
n = len(nums) + 1
data = [0 for _ in range(n)]
s = 0
for i, v in enumerate(nums):
s += v
data[i + 1] = s
self.data = data
<|end_body_0|>
<|body_start_1|>
if not se... | NumArray | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
self.data = []
return
... | stack_v2_sparse_classes_36k_train_005901 | 1,212 | permissive | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | 2830c7e2ada8dfd3dcdda7c06846116d4f944a27 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
if not nums:
self.data = []
return
n = len(nums) + 1
data = [0 for _ in range(n)]
s = 0
for i, v in enumerate(nums):
s += v
data[i + 1] = s
se... | the_stack_v2_python_sparse | leetcode/easy/Range_Sum_Query_Immutable.py | shhuan/algorithms | train | 0 | |
ec2de037caa934fae26890a823a4795a64c0cc2f | [
"try:\n sh.zfs('list', '-t', 'filesystem', self.name)\nexcept sh.ErrorReturnCode_1:\n return False\nreturn True",
"try:\n sh.zfs('create', self.name)\nexcept sh.ErrorReturnCode_1:\n raise\nreturn True",
"if not confirm:\n raise LoggedException('Destroy of storage filesystem requires confirm=True'... | <|body_start_0|>
try:
sh.zfs('list', '-t', 'filesystem', self.name)
except sh.ErrorReturnCode_1:
return False
return True
<|end_body_0|>
<|body_start_1|>
try:
sh.zfs('create', self.name)
except sh.ErrorReturnCode_1:
raise
r... | Filesystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Filesystem:
def exists(self):
"""Checks if filesystem exists. filesystem = Filesystem('dpool/tmp/test0') filesystem.exists()"""
<|body_0|>
def create(self):
"""Creates storage filesystem. filesystem = Filesystem('dpool/tmp/test0') filesystem.create()"""
<|bod... | stack_v2_sparse_classes_36k_train_005902 | 13,193 | no_license | [
{
"docstring": "Checks if filesystem exists. filesystem = Filesystem('dpool/tmp/test0') filesystem.exists()",
"name": "exists",
"signature": "def exists(self)"
},
{
"docstring": "Creates storage filesystem. filesystem = Filesystem('dpool/tmp/test0') filesystem.create()",
"name": "create",
... | 4 | stack_v2_sparse_classes_30k_train_009607 | Implement the Python class `Filesystem` described below.
Class description:
Implement the Filesystem class.
Method signatures and docstrings:
- def exists(self): Checks if filesystem exists. filesystem = Filesystem('dpool/tmp/test0') filesystem.exists()
- def create(self): Creates storage filesystem. filesystem = Fil... | Implement the Python class `Filesystem` described below.
Class description:
Implement the Filesystem class.
Method signatures and docstrings:
- def exists(self): Checks if filesystem exists. filesystem = Filesystem('dpool/tmp/test0') filesystem.exists()
- def create(self): Creates storage filesystem. filesystem = Fil... | 9bc47e6eeff2944f98a0db4fcab32c5dd95fd025 | <|skeleton|>
class Filesystem:
def exists(self):
"""Checks if filesystem exists. filesystem = Filesystem('dpool/tmp/test0') filesystem.exists()"""
<|body_0|>
def create(self):
"""Creates storage filesystem. filesystem = Filesystem('dpool/tmp/test0') filesystem.create()"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Filesystem:
def exists(self):
"""Checks if filesystem exists. filesystem = Filesystem('dpool/tmp/test0') filesystem.exists()"""
try:
sh.zfs('list', '-t', 'filesystem', self.name)
except sh.ErrorReturnCode_1:
return False
return True
def create(self)... | the_stack_v2_python_sparse | solarsanweb/storage/dataset.py | akatrevorjay/solarsanweb | train | 1 | |
4dee331a8972b0091f2b72085c9fc1f39448707e | [
"path = self.get_path(file_extension_provider)\nif self.logger is not None:\n self.logger.info('Reading {0}', path)\nfileobj = None\ntry:\n fileobj = open(path, 'rb')\nexcept FileNotFoundError as ex:\n if self.must_exist():\n raise ex\nreturn fileobj",
"path = self.get_path(file_extension_provider... | <|body_start_0|>
path = self.get_path(file_extension_provider)
if self.logger is not None:
self.logger.info('Reading {0}', path)
fileobj = None
try:
fileobj = open(path, 'rb')
except FileNotFoundError as ex:
if self.must_exist():
... | Implementation of AbstractPersistenceMechanism which saves objects to a local file. | LocalFilePersistenceMechanism | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalFilePersistenceMechanism:
"""Implementation of AbstractPersistenceMechanism which saves objects to a local file."""
def open_source_for_read(self, read_to_fileobj, file_extension_provider=None):
""":param read_to_fileobj: A fileobj into which we will put all data read in from th... | stack_v2_sparse_classes_36k_train_005903 | 2,635 | no_license | [
{
"docstring": ":param read_to_fileobj: A fileobj into which we will put all data read in from the persisted instance. :param file_extension_provider: An implementation of the FileExtensionProvider interface which is often related to the Serialization implementation. :param logger: A logger to send messaging to... | 2 | null | Implement the Python class `LocalFilePersistenceMechanism` described below.
Class description:
Implementation of AbstractPersistenceMechanism which saves objects to a local file.
Method signatures and docstrings:
- def open_source_for_read(self, read_to_fileobj, file_extension_provider=None): :param read_to_fileobj: ... | Implement the Python class `LocalFilePersistenceMechanism` described below.
Class description:
Implementation of AbstractPersistenceMechanism which saves objects to a local file.
Method signatures and docstrings:
- def open_source_for_read(self, read_to_fileobj, file_extension_provider=None): :param read_to_fileobj: ... | 99c2f401d6c4b203ee439ed607985a918d0c3c7e | <|skeleton|>
class LocalFilePersistenceMechanism:
"""Implementation of AbstractPersistenceMechanism which saves objects to a local file."""
def open_source_for_read(self, read_to_fileobj, file_extension_provider=None):
""":param read_to_fileobj: A fileobj into which we will put all data read in from th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalFilePersistenceMechanism:
"""Implementation of AbstractPersistenceMechanism which saves objects to a local file."""
def open_source_for_read(self, read_to_fileobj, file_extension_provider=None):
""":param read_to_fileobj: A fileobj into which we will put all data read in from the persisted i... | the_stack_v2_python_sparse | servicecommon/persistence/mechanism/local_file_persistence_mechanism.py | Cognizant-CDB-AIA-BAI-AI-OI/LEAF-ENN-Training-V2 | train | 0 |
146a1a6b8036c47888f602fbe76fa0beb662bab4 | [
"blocked = self.get_config(C_BLOCKED_MODULES)\nif blocked:\n return frozenset(blocked)\nreturn BLOCKED_MODULES",
"try:\n mod = task['action']['__ansible_module__']\n if mod in self.blocked_modules():\n return f'{self.shortdesc}: {mod}'\nexcept KeyError:\n pass\nreturn False"
] | <|body_start_0|>
blocked = self.get_config(C_BLOCKED_MODULES)
if blocked:
return frozenset(blocked)
return BLOCKED_MODULES
<|end_body_0|>
<|body_start_1|>
try:
mod = task['action']['__ansible_module__']
if mod in self.blocked_modules():
... | Lint rule class to test if variables defined by users follow the namging conventions and guildelines. | BlockedModules | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlockedModules:
"""Lint rule class to test if variables defined by users follow the namging conventions and guildelines."""
def blocked_modules(self):
""".. seealso:: rules.DebugRule.DebugRule.enabled"""
<|body_0|>
def matchtask(self, task: typing.Dict[str, typing.Any], ... | stack_v2_sparse_classes_36k_train_005904 | 1,954 | permissive | [
{
"docstring": ".. seealso:: rules.DebugRule.DebugRule.enabled",
"name": "blocked_modules",
"signature": "def blocked_modules(self)"
},
{
"docstring": ".. seealso:: ansiblelint.rules.AnsibleLintRule.matchtasks",
"name": "matchtask",
"signature": "def matchtask(self, task: typing.Dict[str... | 2 | stack_v2_sparse_classes_30k_train_019265 | Implement the Python class `BlockedModules` described below.
Class description:
Lint rule class to test if variables defined by users follow the namging conventions and guildelines.
Method signatures and docstrings:
- def blocked_modules(self): .. seealso:: rules.DebugRule.DebugRule.enabled
- def matchtask(self, task... | Implement the Python class `BlockedModules` described below.
Class description:
Lint rule class to test if variables defined by users follow the namging conventions and guildelines.
Method signatures and docstrings:
- def blocked_modules(self): .. seealso:: rules.DebugRule.DebugRule.enabled
- def matchtask(self, task... | 1021976e9db1f7d28634f42f2af8c5d30465994b | <|skeleton|>
class BlockedModules:
"""Lint rule class to test if variables defined by users follow the namging conventions and guildelines."""
def blocked_modules(self):
""".. seealso:: rules.DebugRule.DebugRule.enabled"""
<|body_0|>
def matchtask(self, task: typing.Dict[str, typing.Any], ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlockedModules:
"""Lint rule class to test if variables defined by users follow the namging conventions and guildelines."""
def blocked_modules(self):
""".. seealso:: rules.DebugRule.DebugRule.enabled"""
blocked = self.get_config(C_BLOCKED_MODULES)
if blocked:
return f... | the_stack_v2_python_sparse | rules/BlockedModules.py | ssato/ansible-lint-custom-rules | train | 11 |
686136ad0690d407166c4d7614390e870668b8a5 | [
"record = {}\nvid = [bytes(row['id']).decode('utf-8')]\nrecord[self.alias] = vid\nreturn record",
"record = dict()\nrecord[self.alias] = []\nfor instance in batch:\n record[self.alias].extend(instance[self.alias])\nreturn record"
] | <|body_start_0|>
record = {}
vid = [bytes(row['id']).decode('utf-8')]
record[self.alias] = vid
return record
<|end_body_0|>
<|body_start_1|>
record = dict()
record[self.alias] = []
for instance in batch:
record[self.alias].extend(instance[self.alias])... | VidParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VidParser:
def parse(self, row, training=False):
""":param row: raw feature map {key1: raw_feature1, key2: raw_feature2, ...} :param training: training or not can behave different :return: id feature with {self.alias: feature}"""
<|body_0|>
def collate(self, batch):
... | stack_v2_sparse_classes_36k_train_005905 | 5,031 | no_license | [
{
"docstring": ":param row: raw feature map {key1: raw_feature1, key2: raw_feature2, ...} :param training: training or not can behave different :return: id feature with {self.alias: feature}",
"name": "parse",
"signature": "def parse(self, row, training=False)"
},
{
"docstring": ":param batch: l... | 2 | null | Implement the Python class `VidParser` described below.
Class description:
Implement the VidParser class.
Method signatures and docstrings:
- def parse(self, row, training=False): :param row: raw feature map {key1: raw_feature1, key2: raw_feature2, ...} :param training: training or not can behave different :return: i... | Implement the Python class `VidParser` described below.
Class description:
Implement the VidParser class.
Method signatures and docstrings:
- def parse(self, row, training=False): :param row: raw feature map {key1: raw_feature1, key2: raw_feature2, ...} :param training: training or not can behave different :return: i... | 6c28ee71417eb12e637ea362dfbc8057ba88c9c8 | <|skeleton|>
class VidParser:
def parse(self, row, training=False):
""":param row: raw feature map {key1: raw_feature1, key2: raw_feature2, ...} :param training: training or not can behave different :return: id feature with {self.alias: feature}"""
<|body_0|>
def collate(self, batch):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VidParser:
def parse(self, row, training=False):
""":param row: raw feature map {key1: raw_feature1, key2: raw_feature2, ...} :param training: training or not can behave different :return: id feature with {self.alias: feature}"""
record = {}
vid = [bytes(row['id']).decode('utf-8')]
... | the_stack_v2_python_sparse | module/feature_parser.py | jiyt17/qq_transformer | train | 1 | |
308ce6e3e2ede56fd03b641b8023be0ebec50f0c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AppLogCollectionRequest()",
"from .app_log_upload_state import AppLogUploadState\nfrom .entity import Entity\nfrom .app_log_upload_state import AppLogUploadState\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AppLogCollectionRequest()
<|end_body_0|>
<|body_start_1|>
from .app_log_upload_state import AppLogUploadState
from .entity import Entity
from .app_log_upload_state import AppLogU... | Entity for AppLogCollectionRequest contains all logs values. | AppLogCollectionRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppLogCollectionRequest:
"""Entity for AppLogCollectionRequest contains all logs values."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppLogCollectionRequest:
"""Creates a new instance of the appropriate class based on discriminator value Args: pars... | stack_v2_sparse_classes_36k_train_005906 | 3,193 | 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: AppLogCollectionRequest",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimin... | 3 | stack_v2_sparse_classes_30k_train_005711 | Implement the Python class `AppLogCollectionRequest` described below.
Class description:
Entity for AppLogCollectionRequest contains all logs values.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppLogCollectionRequest: Creates a new instance of the ... | Implement the Python class `AppLogCollectionRequest` described below.
Class description:
Entity for AppLogCollectionRequest contains all logs values.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppLogCollectionRequest: Creates a new instance of the ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AppLogCollectionRequest:
"""Entity for AppLogCollectionRequest contains all logs values."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppLogCollectionRequest:
"""Creates a new instance of the appropriate class based on discriminator value Args: pars... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppLogCollectionRequest:
"""Entity for AppLogCollectionRequest contains all logs values."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppLogCollectionRequest:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | the_stack_v2_python_sparse | msgraph/generated/models/app_log_collection_request.py | microsoftgraph/msgraph-sdk-python | train | 135 |
f53e8d47c874f62e63b8b4e7a2f1b6c2e94f4df6 | [
"results = None\ntry:\n with datastore_services.get_ndb_context():\n results = exp_services.regenerate_missing_stats_for_exploration(exp_id)\nexcept Exception as e:\n logging.exception(e)\n return result.Err((exp_id, e))\nreturn result.Ok((exp_id, results))",
"unmigrated_exploration_models = self.... | <|body_start_0|>
results = None
try:
with datastore_services.get_ndb_context():
results = exp_services.regenerate_missing_stats_for_exploration(exp_id)
except Exception as e:
logging.exception(e)
return result.Err((exp_id, e))
return re... | Job that regenerates missing exploration stats models. | RegenerateMissingExplorationStatsModelsJob | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegenerateMissingExplorationStatsModelsJob:
"""Job that regenerates missing exploration stats models."""
def _regenerate_stats_models(exp_id: str, unused_exp_model: exp_models.ExplorationModel) -> result.Result[Tuple[str, exp_domain.Exploration], Tuple[str, Exception]]:
"""Regenerate... | stack_v2_sparse_classes_36k_train_005907 | 28,752 | permissive | [
{
"docstring": "Regenerates missing exploration stats models. Args: exp_id: str. The ID of the exploration. unused_exp_model: ExplorationModel. Exploration model. Returns: Result((str, Exploration), (str, Exception)). Result containing tuple that consists of exploration ID and either Exploration object or Excep... | 2 | stack_v2_sparse_classes_30k_train_014964 | Implement the Python class `RegenerateMissingExplorationStatsModelsJob` described below.
Class description:
Job that regenerates missing exploration stats models.
Method signatures and docstrings:
- def _regenerate_stats_models(exp_id: str, unused_exp_model: exp_models.ExplorationModel) -> result.Result[Tuple[str, ex... | Implement the Python class `RegenerateMissingExplorationStatsModelsJob` described below.
Class description:
Job that regenerates missing exploration stats models.
Method signatures and docstrings:
- def _regenerate_stats_models(exp_id: str, unused_exp_model: exp_models.ExplorationModel) -> result.Result[Tuple[str, ex... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class RegenerateMissingExplorationStatsModelsJob:
"""Job that regenerates missing exploration stats models."""
def _regenerate_stats_models(exp_id: str, unused_exp_model: exp_models.ExplorationModel) -> result.Result[Tuple[str, exp_domain.Exploration], Tuple[str, Exception]]:
"""Regenerate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegenerateMissingExplorationStatsModelsJob:
"""Job that regenerates missing exploration stats models."""
def _regenerate_stats_models(exp_id: str, unused_exp_model: exp_models.ExplorationModel) -> result.Result[Tuple[str, exp_domain.Exploration], Tuple[str, Exception]]:
"""Regenerates missing exp... | the_stack_v2_python_sparse | core/jobs/batch_jobs/exp_migration_jobs.py | oppia/oppia | train | 6,172 |
ad8f2d53ee52bfd72922b5a549a2dd17d3acf5e1 | [
"self.id = id\nself.provider_id = provider_id\nself.server_time = server_time\nself.vehicle_id = vehicle_id\nself.date_time = date_time\nself.location = location",
"if dictionary is None:\n return None\nid = dictionary.get('id')\nprovider_id = dictionary.get('providerId')\nserver_time = dictionary.get('serverT... | <|body_start_0|>
self.id = id
self.provider_id = provider_id
self.server_time = server_time
self.vehicle_id = vehicle_id
self.date_time = date_time
self.location = location
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
id ... | Implementation of the 'Vehicle Location Time' model. TODO: type model description here. Attributes: id (string): The unique identifier for the specific Entity object in the system. provider_id (string): The unique 'Provider ID' of the TSP. server_time (string): Date and time when this object was received at the TSP veh... | VehicleLocationTime | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VehicleLocationTime:
"""Implementation of the 'Vehicle Location Time' model. TODO: type model description here. Attributes: id (string): The unique identifier for the specific Entity object in the system. provider_id (string): The unique 'Provider ID' of the TSP. server_time (string): Date and ti... | stack_v2_sparse_classes_36k_train_005908 | 2,615 | permissive | [
{
"docstring": "Constructor for the VehicleLocationTime class",
"name": "__init__",
"signature": "def __init__(self, id=None, provider_id=None, server_time=None, vehicle_id=None, date_time=None, location=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictiona... | 2 | stack_v2_sparse_classes_30k_train_014557 | Implement the Python class `VehicleLocationTime` described below.
Class description:
Implementation of the 'Vehicle Location Time' model. TODO: type model description here. Attributes: id (string): The unique identifier for the specific Entity object in the system. provider_id (string): The unique 'Provider ID' of the... | Implement the Python class `VehicleLocationTime` described below.
Class description:
Implementation of the 'Vehicle Location Time' model. TODO: type model description here. Attributes: id (string): The unique identifier for the specific Entity object in the system. provider_id (string): The unique 'Provider ID' of the... | 729e9391879e273545a4818558677b2e47261f08 | <|skeleton|>
class VehicleLocationTime:
"""Implementation of the 'Vehicle Location Time' model. TODO: type model description here. Attributes: id (string): The unique identifier for the specific Entity object in the system. provider_id (string): The unique 'Provider ID' of the TSP. server_time (string): Date and ti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VehicleLocationTime:
"""Implementation of the 'Vehicle Location Time' model. TODO: type model description here. Attributes: id (string): The unique identifier for the specific Entity object in the system. provider_id (string): The unique 'Provider ID' of the TSP. server_time (string): Date and time when this ... | the_stack_v2_python_sparse | sdk/python/v0.1-rc.4/opentelematicsapi/models/vehicle_location_time.py | nmfta-repo/nmfta-opentelematics-prototype | train | 2 |
6fdbb45f1266e953964fbe6e539a6c4880df45ff | [
"course_key, course = _get_course_with_access(request, course_key_string)\nif not cohort_id:\n all_cohorts = cohorts.get_course_cohorts(course)\n paginator = NamespacedPageNumberPagination()\n paginator.max_page_size = MAX_PAGE_SIZE\n page = paginator.paginate_queryset(all_cohorts, request)\n respons... | <|body_start_0|>
course_key, course = _get_course_with_access(request, course_key_string)
if not cohort_id:
all_cohorts = cohorts.get_course_cohorts(course)
paginator = NamespacedPageNumberPagination()
paginator.max_page_size = MAX_PAGE_SIZE
page = paginat... | **Use Cases** Get the current cohorts in a course. Create a new cohort in a course. Modify a cohort in a course. **Example Requests**: GET /api/cohorts/v1/courses/{course_id}/cohorts POST /api/cohorts/v1/courses/{course_id}/cohorts GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id} PATCH /api/cohorts/v1/course... | CohortHandler | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CohortHandler:
"""**Use Cases** Get the current cohorts in a course. Create a new cohort in a course. Modify a cohort in a course. **Example Requests**: GET /api/cohorts/v1/courses/{course_id}/cohorts POST /api/cohorts/v1/courses/{course_id}/cohorts GET /api/cohorts/v1/courses/{course_id}/cohorts... | stack_v2_sparse_classes_36k_train_005909 | 31,213 | permissive | [
{
"docstring": "Endpoint to get either one or all cohorts.",
"name": "get",
"signature": "def get(self, request, course_key_string, cohort_id=None)"
},
{
"docstring": "Endpoint to create a new cohort, must not include cohort_id.",
"name": "post",
"signature": "def post(self, request, cou... | 3 | null | Implement the Python class `CohortHandler` described below.
Class description:
**Use Cases** Get the current cohorts in a course. Create a new cohort in a course. Modify a cohort in a course. **Example Requests**: GET /api/cohorts/v1/courses/{course_id}/cohorts POST /api/cohorts/v1/courses/{course_id}/cohorts GET /api... | Implement the Python class `CohortHandler` described below.
Class description:
**Use Cases** Get the current cohorts in a course. Create a new cohort in a course. Modify a cohort in a course. **Example Requests**: GET /api/cohorts/v1/courses/{course_id}/cohorts POST /api/cohorts/v1/courses/{course_id}/cohorts GET /api... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class CohortHandler:
"""**Use Cases** Get the current cohorts in a course. Create a new cohort in a course. Modify a cohort in a course. **Example Requests**: GET /api/cohorts/v1/courses/{course_id}/cohorts POST /api/cohorts/v1/courses/{course_id}/cohorts GET /api/cohorts/v1/courses/{course_id}/cohorts... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CohortHandler:
"""**Use Cases** Get the current cohorts in a course. Create a new cohort in a course. Modify a cohort in a course. **Example Requests**: GET /api/cohorts/v1/courses/{course_id}/cohorts POST /api/cohorts/v1/courses/{course_id}/cohorts GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id} ... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/course_groups/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
71ac0b72eab8c115312ed7736acd44609de6eefa | [
"self.foodToScore = defaultdict(int)\nself.foodToCuision = defaultdict(str)\nself.cuisionRank = defaultdict(lambda: SortedList(key=lambda x: (-x[0], x[1])))\nfor food, cuision, score in zip(foods, cuisines, ratings):\n self.foodToScore[food] = score\n self.foodToCuision[food] = cuision\n self.cuisionRank[c... | <|body_start_0|>
self.foodToScore = defaultdict(int)
self.foodToCuision = defaultdict(str)
self.cuisionRank = defaultdict(lambda: SortedList(key=lambda x: (-x[0], x[1])))
for food, cuision, score in zip(foods, cuisines, ratings):
self.foodToScore[food] = score
sel... | FoodRatings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FoodRatings:
def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
"""foods[i] 是第 i 种食物的名字。 cuisines[i] 是第 i 种食物的烹饪方式。 ratings[i] 是第 i 种食物的最初评分。"""
<|body_0|>
def changeRating(self, food: str, newRating: int) -> None:
"""修改名字为 food 的食物的评分。删除旧... | stack_v2_sparse_classes_36k_train_005910 | 1,858 | no_license | [
{
"docstring": "foods[i] 是第 i 种食物的名字。 cuisines[i] 是第 i 种食物的烹饪方式。 ratings[i] 是第 i 种食物的最初评分。",
"name": "__init__",
"signature": "def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int])"
},
{
"docstring": "修改名字为 food 的食物的评分。删除旧的,添加新的",
"name": "changeRating",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_014188 | Implement the Python class `FoodRatings` described below.
Class description:
Implement the FoodRatings class.
Method signatures and docstrings:
- def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]): foods[i] 是第 i 种食物的名字。 cuisines[i] 是第 i 种食物的烹饪方式。 ratings[i] 是第 i 种食物的最初评分。
- def changeRating... | Implement the Python class `FoodRatings` described below.
Class description:
Implement the FoodRatings class.
Method signatures and docstrings:
- def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]): foods[i] 是第 i 种食物的名字。 cuisines[i] 是第 i 种食物的烹饪方式。 ratings[i] 是第 i 种食物的最初评分。
- def changeRating... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class FoodRatings:
def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
"""foods[i] 是第 i 种食物的名字。 cuisines[i] 是第 i 种食物的烹饪方式。 ratings[i] 是第 i 种食物的最初评分。"""
<|body_0|>
def changeRating(self, food: str, newRating: int) -> None:
"""修改名字为 food 的食物的评分。删除旧... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FoodRatings:
def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
"""foods[i] 是第 i 种食物的名字。 cuisines[i] 是第 i 种食物的烹饪方式。 ratings[i] 是第 i 种食物的最初评分。"""
self.foodToScore = defaultdict(int)
self.foodToCuision = defaultdict(str)
self.cuisionRank = defaultdict(... | the_stack_v2_python_sparse | 4_set/有序集合/字典加SortedList设计类/6126. 设计食物评分系统.py | 981377660LMT/algorithm-study | train | 225 | |
f750b15d57b3e32da9858b3b8938fa848df618cc | [
"if filename:\n self._set_name(filename)\nelse:\n self._set_name()",
"existing_name_list = []\ntry:\n name_file = open(existing_names, 'r')\n for name in name_file:\n existing_name_list.append(name)\n name_file.close()\nexcept FileNotFoundError:\n pass\nwhile True:\n name = [chr(randin... | <|body_start_0|>
if filename:
self._set_name(filename)
else:
self._set_name()
<|end_body_0|>
<|body_start_1|>
existing_name_list = []
try:
name_file = open(existing_names, 'r')
for name in name_file:
existing_name_list.appe... | Class that represents an industrial robot | Robot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Robot:
"""Class that represents an industrial robot"""
def __init__(self, **filename):
"""Creates a new robot with a unique name, using a list of names from a given file or using a default file"""
<|body_0|>
def _set_name(self, existing_names='RobotNames.txt'):
"... | stack_v2_sparse_classes_36k_train_005911 | 1,527 | no_license | [
{
"docstring": "Creates a new robot with a unique name, using a list of names from a given file or using a default file",
"name": "__init__",
"signature": "def __init__(self, **filename)"
},
{
"docstring": "Creates a name for the robot and checks a file to ensure the name is unique. If it is, th... | 3 | null | Implement the Python class `Robot` described below.
Class description:
Class that represents an industrial robot
Method signatures and docstrings:
- def __init__(self, **filename): Creates a new robot with a unique name, using a list of names from a given file or using a default file
- def _set_name(self, existing_na... | Implement the Python class `Robot` described below.
Class description:
Class that represents an industrial robot
Method signatures and docstrings:
- def __init__(self, **filename): Creates a new robot with a unique name, using a list of names from a given file or using a default file
- def _set_name(self, existing_na... | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | <|skeleton|>
class Robot:
"""Class that represents an industrial robot"""
def __init__(self, **filename):
"""Creates a new robot with a unique name, using a list of names from a given file or using a default file"""
<|body_0|>
def _set_name(self, existing_names='RobotNames.txt'):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Robot:
"""Class that represents an industrial robot"""
def __init__(self, **filename):
"""Creates a new robot with a unique name, using a list of names from a given file or using a default file"""
if filename:
self._set_name(filename)
else:
self._set_name()... | the_stack_v2_python_sparse | all_data/exercism_data/python/robot-name/d5d34f1892bb442b9f741a122e382b50.py | itsolutionscorp/AutoStyle-Clustering | train | 4 |
2f6ea72923272f8ca7a3cde91340343e71543b3b | [
"if niter is None:\n niter = self._default_hops\nif self._shotgun:\n res_shotgun = self._optimize_shotgun(x0.copy(), minimizer_kwargs, self._shotgun)\n if res_shotgun:\n x0 = res_shotgun.x.copy()\nelse:\n res_shotgun = None\nresult = basinhopping(func=self.objective, x0=x0, minimizer_kwargs=minim... | <|body_start_0|>
if niter is None:
niter = self._default_hops
if self._shotgun:
res_shotgun = self._optimize_shotgun(x0.copy(), minimizer_kwargs, self._shotgun)
if res_shotgun:
x0 = res_shotgun.x.copy()
else:
res_shotgun = None
... | Implement non-convex optimization. | BaseNonConvexOptimizer | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseNonConvexOptimizer:
"""Implement non-convex optimization."""
def _optimization_basinhopping(self, x0, minimizer_kwargs, niter):
"""Perform a non-convex optimization. This uses scipy.optimize.basinhopping, a simulated annealing-like algorithm. Parameters ---------- x0 : ndarray, N... | stack_v2_sparse_classes_36k_train_005912 | 45,689 | permissive | [
{
"docstring": "Perform a non-convex optimization. This uses scipy.optimize.basinhopping, a simulated annealing-like algorithm. Parameters ---------- x0 : ndarray, None Initial optimization vector. If None, use a random vector. minimizer_kwargs : dict A dictionary of keyword arguments to pass to the optimizer. ... | 3 | stack_v2_sparse_classes_30k_train_015198 | Implement the Python class `BaseNonConvexOptimizer` described below.
Class description:
Implement non-convex optimization.
Method signatures and docstrings:
- def _optimization_basinhopping(self, x0, minimizer_kwargs, niter): Perform a non-convex optimization. This uses scipy.optimize.basinhopping, a simulated anneal... | Implement the Python class `BaseNonConvexOptimizer` described below.
Class description:
Implement non-convex optimization.
Method signatures and docstrings:
- def _optimization_basinhopping(self, x0, minimizer_kwargs, niter): Perform a non-convex optimization. This uses scipy.optimize.basinhopping, a simulated anneal... | b13c5020a2b8524527a4a0db5a81d8549142228c | <|skeleton|>
class BaseNonConvexOptimizer:
"""Implement non-convex optimization."""
def _optimization_basinhopping(self, x0, minimizer_kwargs, niter):
"""Perform a non-convex optimization. This uses scipy.optimize.basinhopping, a simulated annealing-like algorithm. Parameters ---------- x0 : ndarray, N... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseNonConvexOptimizer:
"""Implement non-convex optimization."""
def _optimization_basinhopping(self, x0, minimizer_kwargs, niter):
"""Perform a non-convex optimization. This uses scipy.optimize.basinhopping, a simulated annealing-like algorithm. Parameters ---------- x0 : ndarray, None Initial o... | the_stack_v2_python_sparse | dit/algorithms/optimization.py | dit/dit | train | 468 |
64f1e2b29ac21392fcbd783f4a878e697dda92f3 | [
"if ConfigurationsManager().contains_key('channel'):\n channel = ConfigurationsManager().get_str_for_key('channel')\n resource_dir_path = os.path.join('resources', channel)\n if os.path.exists(resource_dir_path):\n for root, dirs, files in os.walk(resource_dir_path):\n for file in files:\... | <|body_start_0|>
if ConfigurationsManager().contains_key('channel'):
channel = ConfigurationsManager().get_str_for_key('channel')
resource_dir_path = os.path.join('resources', channel)
if os.path.exists(resource_dir_path):
for root, dirs, files in os.walk(reso... | This class will load all locators stored in ini of plist files as per the channel name and save key-value pairs in configurations manager. | LocatorUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocatorUtil:
"""This class will load all locators stored in ini of plist files as per the channel name and save key-value pairs in configurations manager."""
def load_locators(self):
"""This method will load ini and plist file as per the channel name. Returns: None"""
<|body_... | stack_v2_sparse_classes_36k_train_005913 | 2,277 | no_license | [
{
"docstring": "This method will load ini and plist file as per the channel name. Returns: None",
"name": "load_locators",
"signature": "def load_locators(self)"
},
{
"docstring": "This method will load key-value pairs store in ini file and stores them in configuration manager. Args: file_path(s... | 3 | stack_v2_sparse_classes_30k_train_007714 | Implement the Python class `LocatorUtil` described below.
Class description:
This class will load all locators stored in ini of plist files as per the channel name and save key-value pairs in configurations manager.
Method signatures and docstrings:
- def load_locators(self): This method will load ini and plist file ... | Implement the Python class `LocatorUtil` described below.
Class description:
This class will load all locators stored in ini of plist files as per the channel name and save key-value pairs in configurations manager.
Method signatures and docstrings:
- def load_locators(self): This method will load ini and plist file ... | ef514424902e28321ffa4cc7fe886ce1009842dd | <|skeleton|>
class LocatorUtil:
"""This class will load all locators stored in ini of plist files as per the channel name and save key-value pairs in configurations manager."""
def load_locators(self):
"""This method will load ini and plist file as per the channel name. Returns: None"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocatorUtil:
"""This class will load all locators stored in ini of plist files as per the channel name and save key-value pairs in configurations manager."""
def load_locators(self):
"""This method will load ini and plist file as per the channel name. Returns: None"""
if ConfigurationsMan... | the_stack_v2_python_sparse | infostretch/automation/util/locator_util.py | QMetryDev/QAS-Python-Behave-Sample | train | 0 |
7e36bd0a93c1562ad212bf7e819cba0634f51dbe | [
"self.root = root\nself.split = split\nself.filename = self.imagery['img']\nself.transforms = transforms\nself.checksum = checksum\nassert split in {'train', 'test'}, 'Invalid split'\nif split == 'test':\n self.collections = ['sn7_test_source']\nelse:\n self.collections = ['sn7_train_source', 'sn7_train_label... | <|body_start_0|>
self.root = root
self.split = split
self.filename = self.imagery['img']
self.transforms = transforms
self.checksum = checksum
assert split in {'train', 'test'}, 'Invalid split'
if split == 'test':
self.collections = ['sn7_test_source']... | SpaceNet 7: Multi-Temporal Urban Development Challenge. `SpaceNet 7 <https://spacenet.ai/sn7-challenge/>`_ is a dataset which consist of medium resolution (4.0m) satellite imagery mosaics acquired from Planet Labs’ Dove constellation between 2017 and 2020. It includes ≈ 24 images (one per month) covering > 100 unique g... | SpaceNet7 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpaceNet7:
"""SpaceNet 7: Multi-Temporal Urban Development Challenge. `SpaceNet 7 <https://spacenet.ai/sn7-challenge/>`_ is a dataset which consist of medium resolution (4.0m) satellite imagery mosaics acquired from Planet Labs’ Dove constellation between 2017 and 2020. It includes ≈ 24 images (o... | stack_v2_sparse_classes_36k_train_005914 | 45,367 | permissive | [
{
"docstring": "Initialize a new SpaceNet 7 Dataset instance. Args: root: root directory where dataset can be found split: split selection which must be in [\"train\", \"test\"] transforms: a function/transform that takes input sample and its target as entry and returns a transformed version download: if True, ... | 3 | null | Implement the Python class `SpaceNet7` described below.
Class description:
SpaceNet 7: Multi-Temporal Urban Development Challenge. `SpaceNet 7 <https://spacenet.ai/sn7-challenge/>`_ is a dataset which consist of medium resolution (4.0m) satellite imagery mosaics acquired from Planet Labs’ Dove constellation between 20... | Implement the Python class `SpaceNet7` described below.
Class description:
SpaceNet 7: Multi-Temporal Urban Development Challenge. `SpaceNet 7 <https://spacenet.ai/sn7-challenge/>`_ is a dataset which consist of medium resolution (4.0m) satellite imagery mosaics acquired from Planet Labs’ Dove constellation between 20... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class SpaceNet7:
"""SpaceNet 7: Multi-Temporal Urban Development Challenge. `SpaceNet 7 <https://spacenet.ai/sn7-challenge/>`_ is a dataset which consist of medium resolution (4.0m) satellite imagery mosaics acquired from Planet Labs’ Dove constellation between 2017 and 2020. It includes ≈ 24 images (o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpaceNet7:
"""SpaceNet 7: Multi-Temporal Urban Development Challenge. `SpaceNet 7 <https://spacenet.ai/sn7-challenge/>`_ is a dataset which consist of medium resolution (4.0m) satellite imagery mosaics acquired from Planet Labs’ Dove constellation between 2017 and 2020. It includes ≈ 24 images (one per month)... | the_stack_v2_python_sparse | torchgeo/datasets/spacenet.py | microsoft/torchgeo | train | 1,724 |
85a49d2f9085f149f8311fc61507e5d9fbd93550 | [
"self.cluster_count = cluster_count\nself.end_time_usecs = end_time_usecs\nself.error = error\nself.job_count = job_count\nself.name = name\nself.search_job_status = search_job_status\nself.search_job_uid = search_job_uid\nself.start_time_usecs = start_time_usecs\nself.vault_id = vault_id\nself.vault_name = vault_n... | <|body_start_0|>
self.cluster_count = cluster_count
self.end_time_usecs = end_time_usecs
self.error = error
self.job_count = job_count
self.name = name
self.search_job_status = search_job_status
self.search_job_uid = search_job_uid
self.start_time_usecs = ... | Implementation of the 'RemoteVaultSearchJobInformation' model. Specifies information about a search of a remote Vault. Attributes: cluster_count (int): Specifies number of Clusters that have archived to the remote Vault and match the search criteria for this job, up to this point in the search. If the search is complet... | RemoteVaultSearchJobInformation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteVaultSearchJobInformation:
"""Implementation of the 'RemoteVaultSearchJobInformation' model. Specifies information about a search of a remote Vault. Attributes: cluster_count (int): Specifies number of Clusters that have archived to the remote Vault and match the search criteria for this jo... | stack_v2_sparse_classes_36k_train_005915 | 5,384 | permissive | [
{
"docstring": "Constructor for the RemoteVaultSearchJobInformation class",
"name": "__init__",
"signature": "def __init__(self, cluster_count=None, end_time_usecs=None, error=None, job_count=None, name=None, search_job_status=None, search_job_uid=None, start_time_usecs=None, vault_id=None, vault_name=N... | 2 | stack_v2_sparse_classes_30k_train_019853 | Implement the Python class `RemoteVaultSearchJobInformation` described below.
Class description:
Implementation of the 'RemoteVaultSearchJobInformation' model. Specifies information about a search of a remote Vault. Attributes: cluster_count (int): Specifies number of Clusters that have archived to the remote Vault an... | Implement the Python class `RemoteVaultSearchJobInformation` described below.
Class description:
Implementation of the 'RemoteVaultSearchJobInformation' model. Specifies information about a search of a remote Vault. Attributes: cluster_count (int): Specifies number of Clusters that have archived to the remote Vault an... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RemoteVaultSearchJobInformation:
"""Implementation of the 'RemoteVaultSearchJobInformation' model. Specifies information about a search of a remote Vault. Attributes: cluster_count (int): Specifies number of Clusters that have archived to the remote Vault and match the search criteria for this jo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RemoteVaultSearchJobInformation:
"""Implementation of the 'RemoteVaultSearchJobInformation' model. Specifies information about a search of a remote Vault. Attributes: cluster_count (int): Specifies number of Clusters that have archived to the remote Vault and match the search criteria for this job, up to this... | the_stack_v2_python_sparse | cohesity_management_sdk/models/remote_vault_search_job_information.py | cohesity/management-sdk-python | train | 24 |
21790df1a4bc34589c2f8b438ac17a548ce5ff2b | [
"for shebang in shebangs:\n self.results = []\n node = TestNode()\n stream = StringIO.StringIO(shebang)\n stream.fileno = lambda: fileno\n self.checker._check_shebang(node, stream)\n self.assertEqual(len(self.results), exp, msg='processing shebang failed: %r' % shebang)",
"shebangs = ('#!/usr/bi... | <|body_start_0|>
for shebang in shebangs:
self.results = []
node = TestNode()
stream = StringIO.StringIO(shebang)
stream.fileno = lambda: fileno
self.checker._check_shebang(node, stream)
self.assertEqual(len(self.results), exp, msg='process... | Tests for SourceChecker module | SourceCheckerTest | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceCheckerTest:
"""Tests for SourceChecker module"""
def _testShebang(self, shebangs, exp, fileno):
"""Helper for shebang tests"""
<|body_0|>
def testBadShebangNoExec(self):
"""Verify _check_shebang rejects bad shebangs"""
<|body_1|>
def testGoodS... | stack_v2_sparse_classes_36k_train_005916 | 11,497 | permissive | [
{
"docstring": "Helper for shebang tests",
"name": "_testShebang",
"signature": "def _testShebang(self, shebangs, exp, fileno)"
},
{
"docstring": "Verify _check_shebang rejects bad shebangs",
"name": "testBadShebangNoExec",
"signature": "def testBadShebangNoExec(self)"
},
{
"docs... | 5 | null | Implement the Python class `SourceCheckerTest` described below.
Class description:
Tests for SourceChecker module
Method signatures and docstrings:
- def _testShebang(self, shebangs, exp, fileno): Helper for shebang tests
- def testBadShebangNoExec(self): Verify _check_shebang rejects bad shebangs
- def testGoodSheba... | Implement the Python class `SourceCheckerTest` described below.
Class description:
Tests for SourceChecker module
Method signatures and docstrings:
- def _testShebang(self, shebangs, exp, fileno): Helper for shebang tests
- def testBadShebangNoExec(self): Verify _check_shebang rejects bad shebangs
- def testGoodSheba... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class SourceCheckerTest:
"""Tests for SourceChecker module"""
def _testShebang(self, shebangs, exp, fileno):
"""Helper for shebang tests"""
<|body_0|>
def testBadShebangNoExec(self):
"""Verify _check_shebang rejects bad shebangs"""
<|body_1|>
def testGoodS... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SourceCheckerTest:
"""Tests for SourceChecker module"""
def _testShebang(self, shebangs, exp, fileno):
"""Helper for shebang tests"""
for shebang in shebangs:
self.results = []
node = TestNode()
stream = StringIO.StringIO(shebang)
stream.fil... | the_stack_v2_python_sparse | third_party/chromite/cli/cros/lint_unittest.py | metux/chromium-suckless | train | 5 |
fd7314c67a918b5781ec187583d193a3724051b2 | [
"self.X = X\nself.y = y\nself.sigma_0 = sigma_0\nself.tau = tau\nself.gamma = gamma\nself.d = X.shape[1]",
"w = z[:, 0:self.d]\nlamb = z[:, self.d:]\nvar = self.sigma_0 ** 2 / self.gamma\nlog_p_y = torch.sum(-0.5 * np.log(2 * np.pi * var) - 0.5 * ((self.y - w @ self.X.T) ** 2 / var), dim=1)\nlog_p_z = torch.sum(-... | <|body_start_0|>
self.X = X
self.y = y
self.sigma_0 = sigma_0
self.tau = tau
self.gamma = gamma
self.d = X.shape[1]
<|end_body_0|>
<|body_start_1|>
w = z[:, 0:self.d]
lamb = z[:, self.d:]
var = self.sigma_0 ** 2 / self.gamma
log_p_y = torc... | HorseshoeTarget | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HorseshoeTarget:
def __init__(self, X, y, tau, sigma_0, gamma=1):
"""X (n, d) y (n,) gamma is an annealing parameter where for the likelihood instead of using N(y|x^Tw, sigma_0**2) use N(y|x^Tw, sigma_0**2/gamma) and slowly increase gamma to 1 to make a series of easy targets"""
... | stack_v2_sparse_classes_36k_train_005917 | 1,306 | permissive | [
{
"docstring": "X (n, d) y (n,) gamma is an annealing parameter where for the likelihood instead of using N(y|x^Tw, sigma_0**2) use N(y|x^Tw, sigma_0**2/gamma) and slowly increase gamma to 1 to make a series of easy targets",
"name": "__init__",
"signature": "def __init__(self, X, y, tau, sigma_0, gamma... | 2 | stack_v2_sparse_classes_30k_train_010621 | Implement the Python class `HorseshoeTarget` described below.
Class description:
Implement the HorseshoeTarget class.
Method signatures and docstrings:
- def __init__(self, X, y, tau, sigma_0, gamma=1): X (n, d) y (n,) gamma is an annealing parameter where for the likelihood instead of using N(y|x^Tw, sigma_0**2) use... | Implement the Python class `HorseshoeTarget` described below.
Class description:
Implement the HorseshoeTarget class.
Method signatures and docstrings:
- def __init__(self, X, y, tau, sigma_0, gamma=1): X (n, d) y (n,) gamma is an annealing parameter where for the likelihood instead of using N(y|x^Tw, sigma_0**2) use... | a0464cd80000c7cd45a388d6a5f76c0f1a76104d | <|skeleton|>
class HorseshoeTarget:
def __init__(self, X, y, tau, sigma_0, gamma=1):
"""X (n, d) y (n,) gamma is an annealing parameter where for the likelihood instead of using N(y|x^Tw, sigma_0**2) use N(y|x^Tw, sigma_0**2/gamma) and slowly increase gamma to 1 to make a series of easy targets"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HorseshoeTarget:
def __init__(self, X, y, tau, sigma_0, gamma=1):
"""X (n, d) y (n,) gamma is an annealing parameter where for the likelihood instead of using N(y|x^Tw, sigma_0**2) use N(y|x^Tw, sigma_0**2/gamma) and slowly increase gamma to 1 to make a series of easy targets"""
self.X = X
... | the_stack_v2_python_sparse | compressed-sensing/core/target.py | pkulwj1994/hmc-hyperparameter-tuning | train | 0 | |
bbabdd8dcb523a539fc0cba2f95ba346e0000c55 | [
"if level != 0:\n image1 = ImageExtender.extend_image(image, int(image.width), int(image.height))\n image2 = GaussianNoiseGenerator.generate_gaussian_noise_by_level(image1, level, image.width)\n return BoundedImageCropper.crop_bounded_image_inverse(image2, (255, 255, 255, 0))\nelse:\n return image",
"... | <|body_start_0|>
if level != 0:
image1 = ImageExtender.extend_image(image, int(image.width), int(image.height))
image2 = GaussianNoiseGenerator.generate_gaussian_noise_by_level(image1, level, image.width)
return BoundedImageCropper.crop_bounded_image_inverse(image2, (255, 255... | NoisedImageGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoisedImageGenerator:
def generate_noised_image_by_level(image, level):
"""Blur an image with the intended noise level :param image: the image to modify :param level: the level of the noise (more explanation in gaussian_noise_generator) :type image: an image file :type level: int (prefer... | stack_v2_sparse_classes_36k_train_005918 | 1,670 | permissive | [
{
"docstring": "Blur an image with the intended noise level :param image: the image to modify :param level: the level of the noise (more explanation in gaussian_noise_generator) :type image: an image file :type level: int (preferably from 0 to 100)",
"name": "generate_noised_image_by_level",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_000723 | Implement the Python class `NoisedImageGenerator` described below.
Class description:
Implement the NoisedImageGenerator class.
Method signatures and docstrings:
- def generate_noised_image_by_level(image, level): Blur an image with the intended noise level :param image: the image to modify :param level: the level of... | Implement the Python class `NoisedImageGenerator` described below.
Class description:
Implement the NoisedImageGenerator class.
Method signatures and docstrings:
- def generate_noised_image_by_level(image, level): Blur an image with the intended noise level :param image: the image to modify :param level: the level of... | 8931c8859878692134f5113d4c6c3e17561f0196 | <|skeleton|>
class NoisedImageGenerator:
def generate_noised_image_by_level(image, level):
"""Blur an image with the intended noise level :param image: the image to modify :param level: the level of the noise (more explanation in gaussian_noise_generator) :type image: an image file :type level: int (prefer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoisedImageGenerator:
def generate_noised_image_by_level(image, level):
"""Blur an image with the intended noise level :param image: the image to modify :param level: the level of the noise (more explanation in gaussian_noise_generator) :type image: an image file :type level: int (preferably from 0 to... | the_stack_v2_python_sparse | UpdatedSyntheticDataset/SyntheticDataset2/ElementsCreator/noised_image_generator.py | FlintHill/SUAS-Competition | train | 5 | |
13eee321fe9978b4e737bf1fd7100d76d5fff16d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BookingCustomQuestion()",
"from .answer_input_type import AnswerInputType\nfrom .entity import Entity\nfrom .answer_input_type import AnswerInputType\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'answerInput... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return BookingCustomQuestion()
<|end_body_0|>
<|body_start_1|>
from .answer_input_type import AnswerInputType
from .entity import Entity
from .answer_input_type import AnswerInputType
... | Represents a custom question of the business. | BookingCustomQuestion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookingCustomQuestion:
"""Represents a custom question of the business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomQuestion:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse n... | stack_v2_sparse_classes_36k_train_005919 | 2,839 | 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: BookingCustomQuestion",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | null | Implement the Python class `BookingCustomQuestion` described below.
Class description:
Represents a custom question of the business.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomQuestion: Creates a new instance of the appropriate class b... | Implement the Python class `BookingCustomQuestion` described below.
Class description:
Represents a custom question of the business.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomQuestion: Creates a new instance of the appropriate class b... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BookingCustomQuestion:
"""Represents a custom question of the business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomQuestion:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookingCustomQuestion:
"""Represents a custom question of the business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomQuestion:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to... | the_stack_v2_python_sparse | msgraph/generated/models/booking_custom_question.py | microsoftgraph/msgraph-sdk-python | train | 135 |
cb82c6fd958fd9f2a6dc5b2d445a99f30cbc4a12 | [
"if Arm64e.check_valid_pointer_format(pointer_format):\n raise NotImplementedError('Arm64e is not implemented yet')\nelif Generic64.check_valid_pointer_format(pointer_format):\n if self.generic64.bind.bind:\n return (self.generic64.bind.ordinal, self.generic64.bind.addend)\n else:\n return No... | <|body_start_0|>
if Arm64e.check_valid_pointer_format(pointer_format):
raise NotImplementedError('Arm64e is not implemented yet')
elif Generic64.check_valid_pointer_format(pointer_format):
if self.generic64.bind.bind:
return (self.generic64.bind.ordinal, self.gene... | the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141 | ChainedFixupPointerOnDisk | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChainedFixupPointerOnDisk:
"""the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141"""
def isBind(self, pointer_format: DyldChainedPtrFormats) -> Optional[Tuple[int, int]]:
"""Port of ChainedFixupP... | stack_v2_sparse_classes_36k_train_005920 | 13,909 | permissive | [
{
"docstring": "Port of ChainedFixupPointerOnDisk::isBind(uint16_t pointerFormat, uint32_t& bindOrdinal, int64_t& addend) https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.cpp#L1098-L1147 Returns None if not a bind (so `if struct.isBind()` works), :return:",
"name": "isBind",
"signat... | 2 | stack_v2_sparse_classes_30k_train_004551 | Implement the Python class `ChainedFixupPointerOnDisk` described below.
Class description:
the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141
Method signatures and docstrings:
- def isBind(self, pointer_format: DyldChainedPtrFor... | Implement the Python class `ChainedFixupPointerOnDisk` described below.
Class description:
the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141
Method signatures and docstrings:
- def isBind(self, pointer_format: DyldChainedPtrFor... | 23edc1e95b0b1bace308ca80b5a8189bf8cbf8f3 | <|skeleton|>
class ChainedFixupPointerOnDisk:
"""the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141"""
def isBind(self, pointer_format: DyldChainedPtrFormats) -> Optional[Tuple[int, int]]:
"""Port of ChainedFixupP... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChainedFixupPointerOnDisk:
"""the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141"""
def isBind(self, pointer_format: DyldChainedPtrFormats) -> Optional[Tuple[int, int]]:
"""Port of ChainedFixupPointerOnDisk:... | the_stack_v2_python_sparse | cle/backends/macho/structs.py | angr/cle | train | 389 |
8a1caa2578549f47287771d4c4c0585eb1df4541 | [
"self.np_random = np_random\nself.discard_pile = []\nself.shuffled_deck = utils.get_deck()\nself.np_random.shuffle(self.shuffled_deck)\nself.stock_pile = self.shuffled_deck.copy()",
"for _ in range(num):\n player.hand.append(self.stock_pile.pop())\nplayer.did_populate_hand()"
] | <|body_start_0|>
self.np_random = np_random
self.discard_pile = []
self.shuffled_deck = utils.get_deck()
self.np_random.shuffle(self.shuffled_deck)
self.stock_pile = self.shuffled_deck.copy()
<|end_body_0|>
<|body_start_1|>
for _ in range(num):
player.hand.ap... | Initialize a GinRummy dealer class | GinRummyDealer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GinRummyDealer:
"""Initialize a GinRummy dealer class"""
def __init__(self, np_random):
"""Empty discard_pile, set shuffled_deck, set stock_pile"""
<|body_0|>
def deal_cards(self, player: GinRummyPlayer, num: int):
"""Deal some cards from stock_pile to one player... | stack_v2_sparse_classes_36k_train_005921 | 1,049 | permissive | [
{
"docstring": "Empty discard_pile, set shuffled_deck, set stock_pile",
"name": "__init__",
"signature": "def __init__(self, np_random)"
},
{
"docstring": "Deal some cards from stock_pile to one player Args: player (GinRummyPlayer): The GinRummyPlayer object num (int): The number of cards to be ... | 2 | null | Implement the Python class `GinRummyDealer` described below.
Class description:
Initialize a GinRummy dealer class
Method signatures and docstrings:
- def __init__(self, np_random): Empty discard_pile, set shuffled_deck, set stock_pile
- def deal_cards(self, player: GinRummyPlayer, num: int): Deal some cards from sto... | Implement the Python class `GinRummyDealer` described below.
Class description:
Initialize a GinRummy dealer class
Method signatures and docstrings:
- def __init__(self, np_random): Empty discard_pile, set shuffled_deck, set stock_pile
- def deal_cards(self, player: GinRummyPlayer, num: int): Deal some cards from sto... | 7fc56edebe9a2e39c94f872edd8dbe325c61b806 | <|skeleton|>
class GinRummyDealer:
"""Initialize a GinRummy dealer class"""
def __init__(self, np_random):
"""Empty discard_pile, set shuffled_deck, set stock_pile"""
<|body_0|>
def deal_cards(self, player: GinRummyPlayer, num: int):
"""Deal some cards from stock_pile to one player... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GinRummyDealer:
"""Initialize a GinRummy dealer class"""
def __init__(self, np_random):
"""Empty discard_pile, set shuffled_deck, set stock_pile"""
self.np_random = np_random
self.discard_pile = []
self.shuffled_deck = utils.get_deck()
self.np_random.shuffle(self.s... | the_stack_v2_python_sparse | rlcard/games/gin_rummy/dealer.py | datamllab/rlcard | train | 2,447 |
51077a74235d1870e9b7694a818811f6271a74db | [
"id = request.args['id']\nstudent = StudentModel.objects(id=id).first()\nif not student:\n return Response('', 204)\nresponse = [mongo_to_dict(history) for history in student.point_histories]\nreturn self.unicode_safe_json_response(response)",
"id = request.form['id']\nstudent = StudentModel.objects(id=id).fir... | <|body_start_0|>
id = request.args['id']
student = StudentModel.objects(id=id).first()
if not student:
return Response('', 204)
response = [mongo_to_dict(history) for history in student.point_histories]
return self.unicode_safe_json_response(response)
<|end_body_0|>
... | PointManaging | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointManaging:
def get(self):
"""특정 학생의 상벌점 내역 조회"""
<|body_0|>
def post(self):
"""특정 학생에 대한 상벌점 부여"""
<|body_1|>
def delete(self):
"""상벌점 내역 삭제"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
id = request.args['id']
stu... | stack_v2_sparse_classes_36k_train_005922 | 2,872 | permissive | [
{
"docstring": "특정 학생의 상벌점 내역 조회",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "특정 학생에 대한 상벌점 부여",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "상벌점 내역 삭제",
"name": "delete",
"signature": "def delete(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_005989 | Implement the Python class `PointManaging` described below.
Class description:
Implement the PointManaging class.
Method signatures and docstrings:
- def get(self): 특정 학생의 상벌점 내역 조회
- def post(self): 특정 학생에 대한 상벌점 부여
- def delete(self): 상벌점 내역 삭제 | Implement the Python class `PointManaging` described below.
Class description:
Implement the PointManaging class.
Method signatures and docstrings:
- def get(self): 특정 학생의 상벌점 내역 조회
- def post(self): 특정 학생에 대한 상벌점 부여
- def delete(self): 상벌점 내역 삭제
<|skeleton|>
class PointManaging:
def get(self):
"""특정 학생... | de585fe904a2bf15f9fc74219eae176151a0f8ca | <|skeleton|>
class PointManaging:
def get(self):
"""특정 학생의 상벌점 내역 조회"""
<|body_0|>
def post(self):
"""특정 학생에 대한 상벌점 부여"""
<|body_1|>
def delete(self):
"""상벌점 내역 삭제"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PointManaging:
def get(self):
"""특정 학생의 상벌점 내역 조회"""
id = request.args['id']
student = StudentModel.objects(id=id).first()
if not student:
return Response('', 204)
response = [mongo_to_dict(history) for history in student.point_histories]
return self... | the_stack_v2_python_sparse | Server/app/views/v1/admin/point/point.py | miraedbswo/DMS-Backend | train | 2 | |
f3709f440b36519f27649c9acc14aed37d2999d3 | [
"self.msg_id = error_info['msg_id']\nself.level = error_info['loglevel']\nself.msg = error_info['msg']\nself.suffix = error_info['suffix']",
"msg = self.msg % kwargs\nLOG.log(self.level, 'MSGID%(msg_id)04d-%(msg_suffix)s: %(msg)s', {'msg_id': self.msg_id, 'msg_suffix': self.suffix, 'msg': msg})\nreturn msg"
] | <|body_start_0|>
self.msg_id = error_info['msg_id']
self.level = error_info['loglevel']
self.msg = error_info['msg']
self.suffix = error_info['suffix']
<|end_body_0|>
<|body_start_1|>
msg = self.msg % kwargs
LOG.log(self.level, 'MSGID%(msg_id)04d-%(msg_suffix)s: %(msg)s'... | messages for Hitachi VSP Driver. | VSPMsg | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VSPMsg:
"""messages for Hitachi VSP Driver."""
def __init__(self, error_info):
"""Initialize Enum attributes."""
<|body_0|>
def output_log(self, **kwargs):
"""Output the message to the log file and return the message."""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_005923 | 22,494 | permissive | [
{
"docstring": "Initialize Enum attributes.",
"name": "__init__",
"signature": "def __init__(self, error_info)"
},
{
"docstring": "Output the message to the log file and return the message.",
"name": "output_log",
"signature": "def output_log(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018893 | Implement the Python class `VSPMsg` described below.
Class description:
messages for Hitachi VSP Driver.
Method signatures and docstrings:
- def __init__(self, error_info): Initialize Enum attributes.
- def output_log(self, **kwargs): Output the message to the log file and return the message. | Implement the Python class `VSPMsg` described below.
Class description:
messages for Hitachi VSP Driver.
Method signatures and docstrings:
- def __init__(self, error_info): Initialize Enum attributes.
- def output_log(self, **kwargs): Output the message to the log file and return the message.
<|skeleton|>
class VSPM... | 0ccc5dd5eb73278bbfc277f8cabc7e757adc6cef | <|skeleton|>
class VSPMsg:
"""messages for Hitachi VSP Driver."""
def __init__(self, error_info):
"""Initialize Enum attributes."""
<|body_0|>
def output_log(self, **kwargs):
"""Output the message to the log file and return the message."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VSPMsg:
"""messages for Hitachi VSP Driver."""
def __init__(self, error_info):
"""Initialize Enum attributes."""
self.msg_id = error_info['msg_id']
self.level = error_info['loglevel']
self.msg = error_info['msg']
self.suffix = error_info['suffix']
def output_l... | the_stack_v2_python_sparse | cinder/volume/drivers/hitachi/vsp_utils.py | starlingx-staging/stx-cinder | train | 1 |
d07b1a016d0730c11a5298bd67dd0c71f739ec8c | [
"ctx.save_for_backward(input, indices)\nop, ip, o, h, w = input.size()\no, h, w, r = indices.size()\noutput = input.new_zeros((op * r, ip * o, h, w))\next_module.active_rotated_filter_forward(input, indices, output)\nreturn output",
"input, indices = ctx.saved_tensors\ngrad_in = torch.zeros_like(input)\next_modul... | <|body_start_0|>
ctx.save_for_backward(input, indices)
op, ip, o, h, w = input.size()
o, h, w, r = indices.size()
output = input.new_zeros((op * r, ip * o, h, w))
ext_module.active_rotated_filter_forward(input, indices, output)
return output
<|end_body_0|>
<|body_start_1... | Encoding the orientation information and generating orientation- sensitive features. The details are described in the paper `Align Deep Features for Oriented Object Detection <https://arxiv.org/abs/2008.09397>_`. | ActiveRotatedFilterFunction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActiveRotatedFilterFunction:
"""Encoding the orientation information and generating orientation- sensitive features. The details are described in the paper `Align Deep Features for Oriented Object Detection <https://arxiv.org/abs/2008.09397>_`."""
def forward(ctx, input: torch.Tensor, indice... | stack_v2_sparse_classes_36k_train_005924 | 2,230 | permissive | [
{
"docstring": "Args: input (torch.Tensor): Input features with shape [num_output_planes, num_input_planes, num_orientations, H, W]. indices (torch.Tensor): Indices with shape [num_orientations, H, W, num_rotations]. Returns: torch.Tensor: Refined features with shape [num_output_planes * num_rotations, num_inpu... | 2 | null | Implement the Python class `ActiveRotatedFilterFunction` described below.
Class description:
Encoding the orientation information and generating orientation- sensitive features. The details are described in the paper `Align Deep Features for Oriented Object Detection <https://arxiv.org/abs/2008.09397>_`.
Method signa... | Implement the Python class `ActiveRotatedFilterFunction` described below.
Class description:
Encoding the orientation information and generating orientation- sensitive features. The details are described in the paper `Align Deep Features for Oriented Object Detection <https://arxiv.org/abs/2008.09397>_`.
Method signa... | 6e9ee26718b22961d5c34caca4108413b1b7b3af | <|skeleton|>
class ActiveRotatedFilterFunction:
"""Encoding the orientation information and generating orientation- sensitive features. The details are described in the paper `Align Deep Features for Oriented Object Detection <https://arxiv.org/abs/2008.09397>_`."""
def forward(ctx, input: torch.Tensor, indice... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActiveRotatedFilterFunction:
"""Encoding the orientation information and generating orientation- sensitive features. The details are described in the paper `Align Deep Features for Oriented Object Detection <https://arxiv.org/abs/2008.09397>_`."""
def forward(ctx, input: torch.Tensor, indices: torch.Tens... | the_stack_v2_python_sparse | mmcv/ops/active_rotated_filter.py | open-mmlab/mmcv | train | 5,319 |
8bb8ed27b436ddf15f3a55a111cb4ed81ba57559 | [
"self.end_time_usecs = end_time_usecs\nself.is_incremental = is_incremental\nself.logical_bytes_transferred = logical_bytes_transferred\nself.logical_size_bytes = logical_size_bytes\nself.logical_transfer_rate_bps = logical_transfer_rate_bps\nself.physical_bytes_transferred = physical_bytes_transferred\nself.start_... | <|body_start_0|>
self.end_time_usecs = end_time_usecs
self.is_incremental = is_incremental
self.logical_bytes_transferred = logical_bytes_transferred
self.logical_size_bytes = logical_size_bytes
self.logical_transfer_rate_bps = logical_transfer_rate_bps
self.physical_byte... | Implementation of the 'CopyRunStats' model. Stats for one copy task or aggregated stats of a Copy Run in a Protection Job Run. Attributes: end_time_usecs (long|int): Specifies the time when this replication ended. If not set, then the replication has not ended yet. is_incremental (bool): Specifies whether this archival... | CopyRunStats | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CopyRunStats:
"""Implementation of the 'CopyRunStats' model. Stats for one copy task or aggregated stats of a Copy Run in a Protection Job Run. Attributes: end_time_usecs (long|int): Specifies the time when this replication ended. If not set, then the replication has not ended yet. is_incremental... | stack_v2_sparse_classes_36k_train_005925 | 3,966 | permissive | [
{
"docstring": "Constructor for the CopyRunStats class",
"name": "__init__",
"signature": "def __init__(self, end_time_usecs=None, is_incremental=None, logical_bytes_transferred=None, logical_size_bytes=None, logical_transfer_rate_bps=None, physical_bytes_transferred=None, start_time_usecs=None)"
},
... | 2 | stack_v2_sparse_classes_30k_train_012414 | Implement the Python class `CopyRunStats` described below.
Class description:
Implementation of the 'CopyRunStats' model. Stats for one copy task or aggregated stats of a Copy Run in a Protection Job Run. Attributes: end_time_usecs (long|int): Specifies the time when this replication ended. If not set, then the replic... | Implement the Python class `CopyRunStats` described below.
Class description:
Implementation of the 'CopyRunStats' model. Stats for one copy task or aggregated stats of a Copy Run in a Protection Job Run. Attributes: end_time_usecs (long|int): Specifies the time when this replication ended. If not set, then the replic... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CopyRunStats:
"""Implementation of the 'CopyRunStats' model. Stats for one copy task or aggregated stats of a Copy Run in a Protection Job Run. Attributes: end_time_usecs (long|int): Specifies the time when this replication ended. If not set, then the replication has not ended yet. is_incremental... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CopyRunStats:
"""Implementation of the 'CopyRunStats' model. Stats for one copy task or aggregated stats of a Copy Run in a Protection Job Run. Attributes: end_time_usecs (long|int): Specifies the time when this replication ended. If not set, then the replication has not ended yet. is_incremental (bool): Spec... | the_stack_v2_python_sparse | cohesity_management_sdk/models/copy_run_stats.py | cohesity/management-sdk-python | train | 24 |
32823a1bc17d31398adf4dd83dd0f50127a45e62 | [
"self.connected = False\nself.loaded = True\nself.connection_str = ''",
"del kwargs\nself.connected = True\nself.connection_str = connection_str\nprint('Connected.')"
] | <|body_start_0|>
self.connected = False
self.loaded = True
self.connection_str = ''
<|end_body_0|>
<|body_start_1|>
del kwargs
self.connected = True
self.connection_str = connection_str
print('Connected.')
<|end_body_1|>
| Demo data provider. | _DataDriver | [
"LicenseRef-scancode-generic-cla",
"LGPL-3.0-only",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"ISC",
"LGPL-2.0-or-later",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"LGPL-2.1-only",
"Unlicense",
"Python-2.0",
"LicenseRef-scancode-python-cwi",
"MIT",
"LGPL-2.1-or-later",
"GPL-2.... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _DataDriver:
"""Demo data provider."""
def __init__(self):
"""Initialize demo_provider."""
<|body_0|>
def connect(self, connection_str='default', **kwargs):
"""Connect to data source."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.connecte... | stack_v2_sparse_classes_36k_train_005926 | 7,922 | permissive | [
{
"docstring": "Initialize demo_provider.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Connect to data source.",
"name": "connect",
"signature": "def connect(self, connection_str='default', **kwargs)"
}
] | 2 | null | Implement the Python class `_DataDriver` described below.
Class description:
Demo data provider.
Method signatures and docstrings:
- def __init__(self): Initialize demo_provider.
- def connect(self, connection_str='default', **kwargs): Connect to data source. | Implement the Python class `_DataDriver` described below.
Class description:
Demo data provider.
Method signatures and docstrings:
- def __init__(self): Initialize demo_provider.
- def connect(self, connection_str='default', **kwargs): Connect to data source.
<|skeleton|>
class _DataDriver:
"""Demo data provider... | 44b1a390510f9be2772ec62cb95d0fc67dfc234b | <|skeleton|>
class _DataDriver:
"""Demo data provider."""
def __init__(self):
"""Initialize demo_provider."""
<|body_0|>
def connect(self, connection_str='default', **kwargs):
"""Connect to data source."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _DataDriver:
"""Demo data provider."""
def __init__(self):
"""Initialize demo_provider."""
self.connected = False
self.loaded = True
self.connection_str = ''
def connect(self, connection_str='default', **kwargs):
"""Connect to data source."""
del kwarg... | the_stack_v2_python_sparse | tools/mp_demo_data.py | RiskIQ/msticpy | train | 1 |
15d7221f6db892a141a8a9e9fc77a0ffd52c7b87 | [
"if not n or n <= 2:\n return 0\nprimes = [2]\nfor i in range(3, n):\n primeCheck = True\n limit = int(i ** 0.5)\n for prime in primes:\n if prime > limit:\n break\n if i % prime == 0:\n primeCheck = False\n break\n if primeCheck == True:\n primes... | <|body_start_0|>
if not n or n <= 2:
return 0
primes = [2]
for i in range(3, n):
primeCheck = True
limit = int(i ** 0.5)
for prime in primes:
if prime > limit:
break
if i % prime == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countPrimesINITIAL(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not n or n <= 2:
return 0
primes = [2]
... | stack_v2_sparse_classes_36k_train_005927 | 1,796 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "countPrimesINITIAL",
"signature": "def countPrimesINITIAL(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "countPrimes",
"signature": "def countPrimes(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimesINITIAL(self, n): :type n: int :rtype: int
- def countPrimes(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimesINITIAL(self, n): :type n: int :rtype: int
- def countPrimes(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def countPrimesINITIAL(self, n):... | 61bcc10a7ae701bc84773e519d84a20158e268a2 | <|skeleton|>
class Solution:
def countPrimesINITIAL(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countPrimesINITIAL(self, n):
""":type n: int :rtype: int"""
if not n or n <= 2:
return 0
primes = [2]
for i in range(3, n):
primeCheck = True
limit = int(i ** 0.5)
for prime in primes:
if prime > limi... | the_stack_v2_python_sparse | LeetCode/Python3/Problem 204.py | GH-Edifire/GH-JK-practice-problems | train | 0 | |
6bcc797ab3904867b96140962a88f38e5ee3c632 | [
"if not isinstance(data, np.ndarray) or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nn = data.shape[1]\nd = data.shape[0]\nself.mean = np.mean(data, axis=1).reshape(d, 1)\ndeviation = np.tile(sel... | <|body_start_0|>
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data points')
n = data.shape[1]
d = data.shape[0]
self.mean ... | represents a Multivariate Normal distribution | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""represents a Multivariate Normal distribution"""
def __init__(self, data):
"""- data is a numpy.ndarray of shape (d, n) containing the data set: - n is the number of data points - d is the number of dimensions in each data point If data is not a 2D numpy.ndarray, rais... | stack_v2_sparse_classes_36k_train_005928 | 2,578 | no_license | [
{
"docstring": "- data is a numpy.ndarray of shape (d, n) containing the data set: - n is the number of data points - d is the number of dimensions in each data point If data is not a 2D numpy.ndarray, raise a TypeError with the message: \"data must be a 2D numpy.ndarray\" If n is less than 2, raise a ValueErro... | 2 | null | Implement the Python class `MultiNormal` described below.
Class description:
represents a Multivariate Normal distribution
Method signatures and docstrings:
- def __init__(self, data): - data is a numpy.ndarray of shape (d, n) containing the data set: - n is the number of data points - d is the number of dimensions i... | Implement the Python class `MultiNormal` described below.
Class description:
represents a Multivariate Normal distribution
Method signatures and docstrings:
- def __init__(self, data): - data is a numpy.ndarray of shape (d, n) containing the data set: - n is the number of data points - d is the number of dimensions i... | e10b4e9b6f3fa00639e6e9e5b35f0cdb43a339a3 | <|skeleton|>
class MultiNormal:
"""represents a Multivariate Normal distribution"""
def __init__(self, data):
"""- data is a numpy.ndarray of shape (d, n) containing the data set: - n is the number of data points - d is the number of dimensions in each data point If data is not a 2D numpy.ndarray, rais... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiNormal:
"""represents a Multivariate Normal distribution"""
def __init__(self, data):
"""- data is a numpy.ndarray of shape (d, n) containing the data set: - n is the number of data points - d is the number of dimensions in each data point If data is not a 2D numpy.ndarray, raise a TypeError... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | HeimerR/holbertonschool-machine_learning | train | 0 |
5ef5945412e965502c46996f9d8489fbdc62663b | [
"if head is None:\n return head\nodd_pointer = head\neven_pointer = even_head = head.next\nwhile even_pointer is not None:\n third_pointer = even_pointer.next\n if third_pointer is None:\n even_pointer.next = None\n else:\n even_pointer.next = third_pointer.next\n odd_pointer.next = thi... | <|body_start_0|>
if head is None:
return head
odd_pointer = head
even_pointer = even_head = head.next
while even_pointer is not None:
third_pointer = even_pointer.next
if third_pointer is None:
even_pointer.next = None
else:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
"""https://leetcode-cn.com/problems/odd-even-linked-list/solution/qi-ou-lian-biao-by-leetcode-solution/"""
<|body_0|>
def oddEvenList2(self, head: ListNode) -> ListNode:
"""https://leetcode-cn.com/problems/... | stack_v2_sparse_classes_36k_train_005929 | 2,773 | no_license | [
{
"docstring": "https://leetcode-cn.com/problems/odd-even-linked-list/solution/qi-ou-lian-biao-by-leetcode-solution/",
"name": "oddEvenList",
"signature": "def oddEvenList(self, head: ListNode) -> ListNode"
},
{
"docstring": "https://leetcode-cn.com/problems/odd-even-linked-list/solution/kuai-la... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def oddEvenList(self, head: ListNode) -> ListNode: https://leetcode-cn.com/problems/odd-even-linked-list/solution/qi-ou-lian-biao-by-leetcode-solution/
- def oddEvenList2(self, h... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def oddEvenList(self, head: ListNode) -> ListNode: https://leetcode-cn.com/problems/odd-even-linked-list/solution/qi-ou-lian-biao-by-leetcode-solution/
- def oddEvenList2(self, h... | 3ea03cd8b1fa507553ebee4fd765c4cc4b5814b6 | <|skeleton|>
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
"""https://leetcode-cn.com/problems/odd-even-linked-list/solution/qi-ou-lian-biao-by-leetcode-solution/"""
<|body_0|>
def oddEvenList2(self, head: ListNode) -> ListNode:
"""https://leetcode-cn.com/problems/... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
"""https://leetcode-cn.com/problems/odd-even-linked-list/solution/qi-ou-lian-biao-by-leetcode-solution/"""
if head is None:
return head
odd_pointer = head
even_pointer = even_head = head.next
while... | the_stack_v2_python_sparse | Odd_Even_Linked_List_328.py | jay6413682/Leetcode | train | 0 | |
df0f838aee510bcdb73f4f24a2a8245e898a68da | [
"ans = []\ndic1 = collections.Counter(nums1)\nprint(f'dic1: {dic1}')\ndic2 = collections.Counter(nums2)\nprint(f'dic2: {dic2}')\nnum = dic1 & dic2\nfor i in num.elements():\n ans.append(i)\nreturn ans",
"ans = list()\nnums1.sort()\nnums2.sort()\nn = len(nums1)\nm = len(nums2)\nindex1 = index2 = 0\nwhile index1... | <|body_start_0|>
ans = []
dic1 = collections.Counter(nums1)
print(f'dic1: {dic1}')
dic2 = collections.Counter(nums2)
print(f'dic2: {dic2}')
num = dic1 & dic2
for i in num.elements():
ans.append(i)
return ans
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""使用collections计数,取交集 时间复杂度:O(m+n) 空间复杂度:O(min(m, n)) :param nums1: :param nums2: :return:"""
<|body_0|>
def intersect2(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""使用两个指针,... | stack_v2_sparse_classes_36k_train_005930 | 1,848 | no_license | [
{
"docstring": "使用collections计数,取交集 时间复杂度:O(m+n) 空间复杂度:O(min(m, n)) :param nums1: :param nums2: :return:",
"name": "intersect",
"signature": "def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]"
},
{
"docstring": "使用两个指针,判断两个集合里的元素是否相等 元素小的那个集合指针后移 时间复杂度:O(m+n) 空间复杂度:O(min(m, n)... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: 使用collections计数,取交集 时间复杂度:O(m+n) 空间复杂度:O(min(m, n)) :param nums1: :param nums2: :return:
- def intersect2(se... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: 使用collections计数,取交集 时间复杂度:O(m+n) 空间复杂度:O(min(m, n)) :param nums1: :param nums2: :return:
- def intersect2(se... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""使用collections计数,取交集 时间复杂度:O(m+n) 空间复杂度:O(min(m, n)) :param nums1: :param nums2: :return:"""
<|body_0|>
def intersect2(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""使用两个指针,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""使用collections计数,取交集 时间复杂度:O(m+n) 空间复杂度:O(min(m, n)) :param nums1: :param nums2: :return:"""
ans = []
dic1 = collections.Counter(nums1)
print(f'dic1: {dic1}')
dic2 = collections.Counter(nu... | the_stack_v2_python_sparse | 两个数组的交集2.py | cjrzs/MyLeetCode | train | 8 | |
e6c83c663fafdfaa0c3d8f3cb43f84f4ae1e97f3 | [
"factors = []\nfor factor in self:\n if isinstance(factor, Product):\n factors += list(factor)\n else:\n factors.append(factor)\nresult = Product([1])\nfor factor in factors:\n result = multiply(result, simplify_if_possible(factor))\nreturn result.flatten()",
"factors = []\nfor factor in se... | <|body_start_0|>
factors = []
for factor in self:
if isinstance(factor, Product):
factors += list(factor)
else:
factors.append(factor)
result = Product([1])
for factor in factors:
result = multiply(result, simplify_if_po... | See the documentation above for Sum. A Product acts almost exactly like a list, and can be converted to and from a list when necessary. | Product | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Product:
"""See the documentation above for Sum. A Product acts almost exactly like a list, and can be converted to and from a list when necessary."""
def simplify(self):
"""To simplify a product, we need to multiply all its factors together while taking things like the distributive ... | stack_v2_sparse_classes_36k_train_005931 | 9,240 | permissive | [
{
"docstring": "To simplify a product, we need to multiply all its factors together while taking things like the distributive law into account. This method calls multiply() repeatedly, leading to the code you will need to write.",
"name": "simplify",
"signature": "def simplify(self)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_004775 | Implement the Python class `Product` described below.
Class description:
See the documentation above for Sum. A Product acts almost exactly like a list, and can be converted to and from a list when necessary.
Method signatures and docstrings:
- def simplify(self): To simplify a product, we need to multiply all its fa... | Implement the Python class `Product` described below.
Class description:
See the documentation above for Sum. A Product acts almost exactly like a list, and can be converted to and from a list when necessary.
Method signatures and docstrings:
- def simplify(self): To simplify a product, we need to multiply all its fa... | 4fbac9f751a990b567c5ceb67384440ee528dbd0 | <|skeleton|>
class Product:
"""See the documentation above for Sum. A Product acts almost exactly like a list, and can be converted to and from a list when necessary."""
def simplify(self):
"""To simplify a product, we need to multiply all its factors together while taking things like the distributive ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Product:
"""See the documentation above for Sum. A Product acts almost exactly like a list, and can be converted to and from a list when necessary."""
def simplify(self):
"""To simplify a product, we need to multiply all its factors together while taking things like the distributive law into acco... | the_stack_v2_python_sparse | labs/lab0/algebra.py | AdamSpannbauer/mit6034 | train | 1 |
c6342a13335a05f97988c7653720eb0c3b5aedfb | [
"self.maxiter = maxiter\nself.ftol = ftol\nself.minimize = minimize\nself.prev_fvals = None\nself.iter = 0",
"self.iter += 1\nif self.iter == self.maxiter:\n return True\nelif self.prev_fvals is not None:\n fmax = torch.stack([self.prev_fvals.abs(), fvals.abs(), torch.ones_like(fvals)], dim=0).max(dim=0)[0]... | <|body_start_0|>
self.maxiter = maxiter
self.ftol = ftol
self.minimize = minimize
self.prev_fvals = None
self.iter = 0
<|end_body_0|>
<|body_start_1|>
self.iter += 1
if self.iter == self.maxiter:
return True
elif self.prev_fvals is not None:
... | Basic class for evaluating optimization convergence. | ConvergenceCriterion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvergenceCriterion:
"""Basic class for evaluating optimization convergence."""
def __init__(self, maxiter: int=15000, ftol: float=2.220446049250313e-09, minimize: bool=True) -> None:
"""Constructor for ConvergenceCriterion. Args: maxiter: maximum number of iterations. ftol: Functio... | stack_v2_sparse_classes_36k_train_005932 | 10,267 | permissive | [
{
"docstring": "Constructor for ConvergenceCriterion. Args: maxiter: maximum number of iterations. ftol: Function value relative tolerance for termination. minimize: boolean indicating the optimization direction.",
"name": "__init__",
"signature": "def __init__(self, maxiter: int=15000, ftol: float=2.22... | 2 | stack_v2_sparse_classes_30k_train_020392 | Implement the Python class `ConvergenceCriterion` described below.
Class description:
Basic class for evaluating optimization convergence.
Method signatures and docstrings:
- def __init__(self, maxiter: int=15000, ftol: float=2.220446049250313e-09, minimize: bool=True) -> None: Constructor for ConvergenceCriterion. A... | Implement the Python class `ConvergenceCriterion` described below.
Class description:
Basic class for evaluating optimization convergence.
Method signatures and docstrings:
- def __init__(self, maxiter: int=15000, ftol: float=2.220446049250313e-09, minimize: bool=True) -> None: Constructor for ConvergenceCriterion. A... | af13f0a38b579ab504f49a01f1ced13532a3ad49 | <|skeleton|>
class ConvergenceCriterion:
"""Basic class for evaluating optimization convergence."""
def __init__(self, maxiter: int=15000, ftol: float=2.220446049250313e-09, minimize: bool=True) -> None:
"""Constructor for ConvergenceCriterion. Args: maxiter: maximum number of iterations. ftol: Functio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvergenceCriterion:
"""Basic class for evaluating optimization convergence."""
def __init__(self, maxiter: int=15000, ftol: float=2.220446049250313e-09, minimize: bool=True) -> None:
"""Constructor for ConvergenceCriterion. Args: maxiter: maximum number of iterations. ftol: Function value relat... | the_stack_v2_python_sparse | botorch/optim/utils.py | shalijiang/bo | train | 1 |
77a05df04ddd22f5c609b32ceda10e6d7b02046a | [
"user = User.objects.create(username='testuser', password='qwerty12345Q!')\nrecruiter = User.objects.create(username='recruiter3', first_name='first_recruiter', last_name='last_recruiter', email='recruiter@mail.com')\ncandidate = User.objects.create(username='candidate3', first_name='first_candidate', last_name='la... | <|body_start_0|>
user = User.objects.create(username='testuser', password='qwerty12345Q!')
recruiter = User.objects.create(username='recruiter3', first_name='first_recruiter', last_name='last_recruiter', email='recruiter@mail.com')
candidate = User.objects.create(username='candidate3', first_nam... | Test POST request Comments app | CommentsPostTestCases | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentsPostTestCases:
"""Test POST request Comments app"""
def setUp(self):
"""Create new data in in linked tables"""
<|body_0|>
def test_post_create_comments(self):
"""Test for POST Comments"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user... | stack_v2_sparse_classes_36k_train_005933 | 13,494 | no_license | [
{
"docstring": "Create new data in in linked tables",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test for POST Comments",
"name": "test_post_create_comments",
"signature": "def test_post_create_comments(self)"
}
] | 2 | null | Implement the Python class `CommentsPostTestCases` described below.
Class description:
Test POST request Comments app
Method signatures and docstrings:
- def setUp(self): Create new data in in linked tables
- def test_post_create_comments(self): Test for POST Comments | Implement the Python class `CommentsPostTestCases` described below.
Class description:
Test POST request Comments app
Method signatures and docstrings:
- def setUp(self): Create new data in in linked tables
- def test_post_create_comments(self): Test for POST Comments
<|skeleton|>
class CommentsPostTestCases:
""... | f448ec0453818d55c5c9d30aaa4f19e1d7ca5867 | <|skeleton|>
class CommentsPostTestCases:
"""Test POST request Comments app"""
def setUp(self):
"""Create new data in in linked tables"""
<|body_0|>
def test_post_create_comments(self):
"""Test for POST Comments"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentsPostTestCases:
"""Test POST request Comments app"""
def setUp(self):
"""Create new data in in linked tables"""
user = User.objects.create(username='testuser', password='qwerty12345Q!')
recruiter = User.objects.create(username='recruiter3', first_name='first_recruiter', las... | the_stack_v2_python_sparse | Portfolio/tech-interview/techinterview/feedback/test_feedback.py | HeCToR74/Python | train | 1 |
4d9da072d5cdc9ac025c9182541a595cf2f22d4d | [
"self.parent: MenuNode = parent\nself.is_valid = True\nfeature_settings: FeatureSettings = MenuNode.get_settings(dir_path)\nif feature_settings is None:\n self.is_valid = False\n BotItLogger.error(f'No feature settings in: {dir_path}')\n return\nself.display_name = feature_settings.display_name\nself.show_... | <|body_start_0|>
self.parent: MenuNode = parent
self.is_valid = True
feature_settings: FeatureSettings = MenuNode.get_settings(dir_path)
if feature_settings is None:
self.is_valid = False
BotItLogger.error(f'No feature settings in: {dir_path}')
return
... | Represents a node in the menu (A feature that is in the menu) | MenuNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuNode:
"""Represents a node in the menu (A feature that is in the menu)"""
def __init__(self, dir_path: str, parent: Optional[MenuNode], ui: UI):
"""Creates a new MenuNode. :param dir_path: The directory path the node exists in :param parent: The parent MenuNode (Where to go back?... | stack_v2_sparse_classes_36k_train_005934 | 4,303 | no_license | [
{
"docstring": "Creates a new MenuNode. :param dir_path: The directory path the node exists in :param parent: The parent MenuNode (Where to go back?) :param ui: The UI to use (What UI to give the features?)",
"name": "__init__",
"signature": "def __init__(self, dir_path: str, parent: Optional[MenuNode],... | 3 | null | Implement the Python class `MenuNode` described below.
Class description:
Represents a node in the menu (A feature that is in the menu)
Method signatures and docstrings:
- def __init__(self, dir_path: str, parent: Optional[MenuNode], ui: UI): Creates a new MenuNode. :param dir_path: The directory path the node exists... | Implement the Python class `MenuNode` described below.
Class description:
Represents a node in the menu (A feature that is in the menu)
Method signatures and docstrings:
- def __init__(self, dir_path: str, parent: Optional[MenuNode], ui: UI): Creates a new MenuNode. :param dir_path: The directory path the node exists... | 8d3eb943de9611abf2b7d534ece4e8126dbd7a44 | <|skeleton|>
class MenuNode:
"""Represents a node in the menu (A feature that is in the menu)"""
def __init__(self, dir_path: str, parent: Optional[MenuNode], ui: UI):
"""Creates a new MenuNode. :param dir_path: The directory path the node exists in :param parent: The parent MenuNode (Where to go back?... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MenuNode:
"""Represents a node in the menu (A feature that is in the menu)"""
def __init__(self, dir_path: str, parent: Optional[MenuNode], ui: UI):
"""Creates a new MenuNode. :param dir_path: The directory path the node exists in :param parent: The parent MenuNode (Where to go back?) :param ui: ... | the_stack_v2_python_sparse | Features/SystemFeatures/HierarchicalMenu/Code/menu_node.py | dvirby/BotIt | train | 0 |
ddeaae5ba4b7866f0d55ec02cfcbe0fa62cec113 | [
"result = {'error': False, 'message': ''}\nurls = request.values.get('urls', '')\npage_type = request.values.get('type', '')\nurls = [u.strip().lower() for u in urls.split(',') if u]\nif not urls:\n result['error'] = True\n result['message'] = 'Urls is empty'\n return result\nif not page_type:\n result[... | <|body_start_0|>
result = {'error': False, 'message': ''}
urls = request.values.get('urls', '')
page_type = request.values.get('type', '')
urls = [u.strip().lower() for u in urls.split(',') if u]
if not urls:
result['error'] = True
result['message'] = 'Url... | Label training data | PageTypeStorageResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PageTypeStorageResource:
"""Label training data"""
def post(self):
"""Post labeled data to update"""
<|body_0|>
def get(self):
"""Get list labeled data"""
<|body_1|>
def delete(self):
"""Get list labeled data"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k_train_005935 | 23,616 | no_license | [
{
"docstring": "Post labeled data to update",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Get list labeled data",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Get list labeled data",
"name": "delete",
"signature": "def delete(self)"
... | 3 | stack_v2_sparse_classes_30k_train_013574 | Implement the Python class `PageTypeStorageResource` described below.
Class description:
Label training data
Method signatures and docstrings:
- def post(self): Post labeled data to update
- def get(self): Get list labeled data
- def delete(self): Get list labeled data | Implement the Python class `PageTypeStorageResource` described below.
Class description:
Label training data
Method signatures and docstrings:
- def post(self): Post labeled data to update
- def get(self): Get list labeled data
- def delete(self): Get list labeled data
<|skeleton|>
class PageTypeStorageResource:
... | 9ea084d56a263a935456afe51bcdc92aa2210083 | <|skeleton|>
class PageTypeStorageResource:
"""Label training data"""
def post(self):
"""Post labeled data to update"""
<|body_0|>
def get(self):
"""Get list labeled data"""
<|body_1|>
def delete(self):
"""Get list labeled data"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PageTypeStorageResource:
"""Label training data"""
def post(self):
"""Post labeled data to update"""
result = {'error': False, 'message': ''}
urls = request.values.get('urls', '')
page_type = request.values.get('type', '')
urls = [u.strip().lower() for u in urls.sp... | the_stack_v2_python_sparse | api/api.py | diepdaocs/web-page-classifier | train | 1 |
fb63b9593d4999ef940727f9f35396ebe7209495 | [
"result = []\nmax_val = len(S)\nindex = len(S) - 1\nmin_val = 0\nwhile index >= 0:\n if S[index] == 'I':\n result.insert(0, max_val)\n max_val -= 1\n else:\n result.insert(0, min_val)\n min_val += 1\n index -= 1\nresult.insert(0, (max_val + min_val) / 2)\nreturn result",
"resu... | <|body_start_0|>
result = []
max_val = len(S)
index = len(S) - 1
min_val = 0
while index >= 0:
if S[index] == 'I':
result.insert(0, max_val)
max_val -= 1
else:
result.insert(0, min_val)
min_va... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _diStringMatch(self, S):
""":type S: str :rtype: List[int]"""
<|body_0|>
def diStringMatch(self, S):
""":type S: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
max_val = len(S)
index =... | stack_v2_sparse_classes_36k_train_005936 | 2,287 | permissive | [
{
"docstring": ":type S: str :rtype: List[int]",
"name": "_diStringMatch",
"signature": "def _diStringMatch(self, S)"
},
{
"docstring": ":type S: str :rtype: List[int]",
"name": "diStringMatch",
"signature": "def diStringMatch(self, S)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _diStringMatch(self, S): :type S: str :rtype: List[int]
- def diStringMatch(self, S): :type S: str :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _diStringMatch(self, S): :type S: str :rtype: List[int]
- def diStringMatch(self, S): :type S: str :rtype: List[int]
<|skeleton|>
class Solution:
def _diStringMatch(sel... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _diStringMatch(self, S):
""":type S: str :rtype: List[int]"""
<|body_0|>
def diStringMatch(self, S):
""":type S: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _diStringMatch(self, S):
""":type S: str :rtype: List[int]"""
result = []
max_val = len(S)
index = len(S) - 1
min_val = 0
while index >= 0:
if S[index] == 'I':
result.insert(0, max_val)
max_val -= 1
... | the_stack_v2_python_sparse | 942.di-string-match.py | windard/leeeeee | train | 0 | |
40814c796e0ccffa976ed6474946ca42a0b00e20 | [
"super(SelfAttention, self).__init__()\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)",
"query = s_prev\nvalues = hidden_states\nquery_with_time_axis = tf.expand_dims(query, 1)\nscore = self.V(tf.nn.tanh(self.W(query_with_time_axis) + self.U(values... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
<|end_body_0|>
<|body_start_1|>
query = s_prev
values = hidden_states
query_with_time_axis = tf.ex... | This class calculates the attention for machine translation based on https://arxiv.org/pdf/1409.0473.pdf | SelfAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""This class calculates the attention for machine translation based on https://arxiv.org/pdf/1409.0473.pdf"""
def __init__(self, units):
"""All begins here"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""This method call SelfAttention"""
... | stack_v2_sparse_classes_36k_train_005937 | 1,730 | permissive | [
{
"docstring": "All begins here",
"name": "__init__",
"signature": "def __init__(self, units)"
},
{
"docstring": "This method call SelfAttention",
"name": "call",
"signature": "def call(self, s_prev, hidden_states)"
}
] | 2 | null | Implement the Python class `SelfAttention` described below.
Class description:
This class calculates the attention for machine translation based on https://arxiv.org/pdf/1409.0473.pdf
Method signatures and docstrings:
- def __init__(self, units): All begins here
- def call(self, s_prev, hidden_states): This method ca... | Implement the Python class `SelfAttention` described below.
Class description:
This class calculates the attention for machine translation based on https://arxiv.org/pdf/1409.0473.pdf
Method signatures and docstrings:
- def __init__(self, units): All begins here
- def call(self, s_prev, hidden_states): This method ca... | 58c367f3014919f95157426121093b9fe14d4035 | <|skeleton|>
class SelfAttention:
"""This class calculates the attention for machine translation based on https://arxiv.org/pdf/1409.0473.pdf"""
def __init__(self, units):
"""All begins here"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""This method call SelfAttention"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""This class calculates the attention for machine translation based on https://arxiv.org/pdf/1409.0473.pdf"""
def __init__(self, units):
"""All begins here"""
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.laye... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | linkem97/holbertonschool-machine_learning | train | 0 |
d113ebbfe7c02fb786ba4624e88cd009a9ba2598 | [
"with open(img_path, 'rb') as f:\n base64_data = base64.b64encode(f.read())\n base64_data = base64_data.decode('utf8')\n return base64_data",
"base64_encoding = base64_encoding.encode('utf8')\nimg_data = base64.b64decode(base64_encoding)\nwith open(des_img_path, 'wb') as file:\n file.write(img_data)"
... | <|body_start_0|>
with open(img_path, 'rb') as f:
base64_data = base64.b64encode(f.read())
base64_data = base64_data.decode('utf8')
return base64_data
<|end_body_0|>
<|body_start_1|>
base64_encoding = base64_encoding.encode('utf8')
img_data = base64.b64decode(... | ImageTransform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageTransform:
def img_to_base64(img_path):
""":param img_path: :return:"""
<|body_0|>
def base64_to_img(base64_encoding, des_img_path):
""":param des_img_path: :param base64_encoding: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
with o... | stack_v2_sparse_classes_36k_train_005938 | 1,206 | no_license | [
{
"docstring": ":param img_path: :return:",
"name": "img_to_base64",
"signature": "def img_to_base64(img_path)"
},
{
"docstring": ":param des_img_path: :param base64_encoding: :return:",
"name": "base64_to_img",
"signature": "def base64_to_img(base64_encoding, des_img_path)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000707 | Implement the Python class `ImageTransform` described below.
Class description:
Implement the ImageTransform class.
Method signatures and docstrings:
- def img_to_base64(img_path): :param img_path: :return:
- def base64_to_img(base64_encoding, des_img_path): :param des_img_path: :param base64_encoding: :return: | Implement the Python class `ImageTransform` described below.
Class description:
Implement the ImageTransform class.
Method signatures and docstrings:
- def img_to_base64(img_path): :param img_path: :return:
- def base64_to_img(base64_encoding, des_img_path): :param des_img_path: :param base64_encoding: :return:
<|sk... | ee41eb80d6b8823cfd764920ed8aa4c682d9a013 | <|skeleton|>
class ImageTransform:
def img_to_base64(img_path):
""":param img_path: :return:"""
<|body_0|>
def base64_to_img(base64_encoding, des_img_path):
""":param des_img_path: :param base64_encoding: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageTransform:
def img_to_base64(img_path):
""":param img_path: :return:"""
with open(img_path, 'rb') as f:
base64_data = base64.b64encode(f.read())
base64_data = base64_data.decode('utf8')
return base64_data
def base64_to_img(base64_encoding, des_img_... | the_stack_v2_python_sparse | data_custom_backend/llib/cv_utility/image_transform.py | marjeylee/cmdb | train | 0 | |
8b4213dea336ae50976739dc12250647a0d55cc7 | [
"if not self.referenced_user:\n return self.name\nreturn u'de %s (utilise notre site)' % self.referenced_user.get_pseudo()",
"if not self.date_from or not (self.current or self.date_to):\n return ''\ndate_from = self.date_from.strftime('%d/%m/%Y')\ndate_to = u\"à aujourd'hui\" if self.current else 'au %s' %... | <|body_start_0|>
if not self.referenced_user:
return self.name
return u'de %s (utilise notre site)' % self.referenced_user.get_pseudo()
<|end_body_0|>
<|body_start_1|>
if not self.date_from or not (self.current or self.date_to):
return ''
date_from = self.date_fr... | A model representing a reference for a prestataire. | Reference | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reference:
"""A model representing a reference for a prestataire."""
def get_famille_display(self):
"""Retrieve the famille, depending on reference type"""
<|body_0|>
def get_dates_display(self):
"""Retrieve the dates of the reference for display."""
<|bo... | stack_v2_sparse_classes_36k_train_005939 | 24,210 | permissive | [
{
"docstring": "Retrieve the famille, depending on reference type",
"name": "get_famille_display",
"signature": "def get_famille_display(self)"
},
{
"docstring": "Retrieve the dates of the reference for display.",
"name": "get_dates_display",
"signature": "def get_dates_display(self)"
... | 2 | stack_v2_sparse_classes_30k_train_005749 | Implement the Python class `Reference` described below.
Class description:
A model representing a reference for a prestataire.
Method signatures and docstrings:
- def get_famille_display(self): Retrieve the famille, depending on reference type
- def get_dates_display(self): Retrieve the dates of the reference for dis... | Implement the Python class `Reference` described below.
Class description:
A model representing a reference for a prestataire.
Method signatures and docstrings:
- def get_famille_display(self): Retrieve the famille, depending on reference type
- def get_dates_display(self): Retrieve the dates of the reference for dis... | c7b3399e88a6922cadc0c7c9f2ff7447e7c95377 | <|skeleton|>
class Reference:
"""A model representing a reference for a prestataire."""
def get_famille_display(self):
"""Retrieve the famille, depending on reference type"""
<|body_0|>
def get_dates_display(self):
"""Retrieve the dates of the reference for display."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reference:
"""A model representing a reference for a prestataire."""
def get_famille_display(self):
"""Retrieve the famille, depending on reference type"""
if not self.referenced_user:
return self.name
return u'de %s (utilise notre site)' % self.referenced_user.get_pse... | the_stack_v2_python_sparse | famille/models/users.py | huguesmayolle/famille | train | 0 |
669f9baf3166970218b96d8bdc08cb6c5798d9b9 | [
"timestamp = None\ntry:\n timestamp = json.dumps({'commit_hash': commit_hash, 'time': time, 'branch_name': branch_name}).encode('UTF-8')\n producer = KafkaProducer(bootstrap_servers=KAFKA_SERVER, client_id='ioc_puller', api_version=(2, 7, 0))\n producer.send(KAFKA_TIMESTAMP_TOPIC, timestamp)\nexcept Except... | <|body_start_0|>
timestamp = None
try:
timestamp = json.dumps({'commit_hash': commit_hash, 'time': time, 'branch_name': branch_name}).encode('UTF-8')
producer = KafkaProducer(bootstrap_servers=KAFKA_SERVER, client_id='ioc_puller', api_version=(2, 7, 0))
producer.send(... | Class for the Puller-Server. | Puller | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Puller:
"""Class for the Puller-Server."""
def commit_timestamp(commit_hash, time, branch_name):
"""commit_timestamp will send a timestamp to KAFKA so it can be accessed at any time. @param commit_hash will be the hash value of the commit. @param time will be a datetime object with t... | stack_v2_sparse_classes_36k_train_005940 | 6,516 | permissive | [
{
"docstring": "commit_timestamp will send a timestamp to KAFKA so it can be accessed at any time. @param commit_hash will be the hash value of the commit. @param time will be a datetime object with the timestamp @param branch_name will be the branch_name of the last timestamp. @return will return a timestamp-o... | 5 | stack_v2_sparse_classes_30k_train_010367 | Implement the Python class `Puller` described below.
Class description:
Class for the Puller-Server.
Method signatures and docstrings:
- def commit_timestamp(commit_hash, time, branch_name): commit_timestamp will send a timestamp to KAFKA so it can be accessed at any time. @param commit_hash will be the hash value of... | Implement the Python class `Puller` described below.
Class description:
Class for the Puller-Server.
Method signatures and docstrings:
- def commit_timestamp(commit_hash, time, branch_name): commit_timestamp will send a timestamp to KAFKA so it can be accessed at any time. @param commit_hash will be the hash value of... | cdad9966ab2aef495d0dca51a06cf567dd38a315 | <|skeleton|>
class Puller:
"""Class for the Puller-Server."""
def commit_timestamp(commit_hash, time, branch_name):
"""commit_timestamp will send a timestamp to KAFKA so it can be accessed at any time. @param commit_hash will be the hash value of the commit. @param time will be a datetime object with t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Puller:
"""Class for the Puller-Server."""
def commit_timestamp(commit_hash, time, branch_name):
"""commit_timestamp will send a timestamp to KAFKA so it can be accessed at any time. @param commit_hash will be the hash value of the commit. @param time will be a datetime object with the timestamp ... | the_stack_v2_python_sparse | iocpuller/core/server.py | hm-seclab/YAFRA | train | 32 |
28682de5ca0d4a856b222640950801c7a81be634 | [
"super(Edge2Node, self).__init__()\nself.channel = channel\nself.dim = dim\nself.filters = filters\nself.row_conv = nn.Conv2d(channel, filters, (1, dim))\nself.col_conv = nn.Conv2d(channel, filters, (dim, 1))",
"row = self.row_conv(x)\ncol = self.col_conv(x)\nreturn row + col.permute(0, 1, 3, 2)"
] | <|body_start_0|>
super(Edge2Node, self).__init__()
self.channel = channel
self.dim = dim
self.filters = filters
self.row_conv = nn.Conv2d(channel, filters, (1, dim))
self.col_conv = nn.Conv2d(channel, filters, (dim, 1))
<|end_body_0|>
<|body_start_1|>
row = self.... | BrainNetCNN edge to node (e2n) layer Attributes: channel (int): number of input channel col_conv (nn.Conv2d): column convolution dim (int): number of ROI for functional connectivity filters (int): number of output channel row_conv ((nn.Conv2d): row convolution | Edge2Node | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Edge2Node:
"""BrainNetCNN edge to node (e2n) layer Attributes: channel (int): number of input channel col_conv (nn.Conv2d): column convolution dim (int): number of ROI for functional connectivity filters (int): number of output channel row_conv ((nn.Conv2d): row convolution"""
def __init__(s... | stack_v2_sparse_classes_36k_train_005941 | 12,068 | permissive | [
{
"docstring": "initialization function of e2n layer Args: channel (int): number of input channel dim (int): number of ROI for functional connectivity filters (int): number of output channel",
"name": "__init__",
"signature": "def __init__(self, channel, dim, filters)"
},
{
"docstring": "e2n by ... | 2 | stack_v2_sparse_classes_30k_train_007262 | Implement the Python class `Edge2Node` described below.
Class description:
BrainNetCNN edge to node (e2n) layer Attributes: channel (int): number of input channel col_conv (nn.Conv2d): column convolution dim (int): number of ROI for functional connectivity filters (int): number of output channel row_conv ((nn.Conv2d):... | Implement the Python class `Edge2Node` described below.
Class description:
BrainNetCNN edge to node (e2n) layer Attributes: channel (int): number of input channel col_conv (nn.Conv2d): column convolution dim (int): number of ROI for functional connectivity filters (int): number of output channel row_conv ((nn.Conv2d):... | c773720ad340dcb1d566b0b8de68b6acdf2ca505 | <|skeleton|>
class Edge2Node:
"""BrainNetCNN edge to node (e2n) layer Attributes: channel (int): number of input channel col_conv (nn.Conv2d): column convolution dim (int): number of ROI for functional connectivity filters (int): number of output channel row_conv ((nn.Conv2d): row convolution"""
def __init__(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Edge2Node:
"""BrainNetCNN edge to node (e2n) layer Attributes: channel (int): number of input channel col_conv (nn.Conv2d): column convolution dim (int): number of ROI for functional connectivity filters (int): number of output channel row_conv ((nn.Conv2d): row convolution"""
def __init__(self, channel,... | the_stack_v2_python_sparse | stable_projects/predict_phenotypes/He2019_KRDNN/cbig/He2019/CBIG_model_pytorch.py | ThomasYeoLab/CBIG | train | 508 |
a73cda9db45de5a687378be465f6ff8bd68c757d | [
"self.d = dict()\nself.stk = []\nself.length = capacity",
"if key in self.d:\n ans = self.d[key]\n self.stk.remove(key)\n self.stk.append(key)\n return ans\nelse:\n return -1",
"if key not in self.d:\n if len(self.d) == self.length:\n temp = self.stk.pop(0)\n del self.d[temp]\n ... | <|body_start_0|>
self.d = dict()
self.stk = []
self.length = capacity
<|end_body_0|>
<|body_start_1|>
if key in self.d:
ans = self.d[key]
self.stk.remove(key)
self.stk.append(key)
return ans
else:
return -1
<|end_body_1... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_005942 | 1,062 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | d8c3be5937c54b740ebccd0b373a67ece46773f3 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.d = dict()
self.stk = []
self.length = capacity
def get(self, key):
""":type key: int :rtype: int"""
if key in self.d:
ans = self.d[key]
self.stk.remove(key)
... | the_stack_v2_python_sparse | LRU Cache.py | shank54/Leetcode | train | 0 | |
912c90c58095803598c17d621284f4b6ac6e2ab3 | [
"chapterMapping = super()._get_chapterMapping(chId, chapterNumber)\nif self.novel.chapters[chId].suppressChapterTitle:\n chapterMapping['Title'] = ''\nreturn chapterMapping",
"sceneMapping = super()._get_sceneMapping(scId, sceneNumber, wordsTotal, lettersTotal)\nsceneMapping['Summary'] = _('Summary')\nreturn s... | <|body_start_0|>
chapterMapping = super()._get_chapterMapping(chId, chapterNumber)
if self.novel.chapters[chId].suppressChapterTitle:
chapterMapping['Title'] = ''
return chapterMapping
<|end_body_0|>
<|body_start_1|>
sceneMapping = super()._get_sceneMapping(scId, sceneNumber... | ODT manuscript file writer. Export a manuscript with invisibly tagged chapters and scenes. | OdtWManuscript | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OdtWManuscript:
"""ODT manuscript file writer. Export a manuscript with invisibly tagged chapters and scenes."""
def _get_chapterMapping(self, chId, chapterNumber):
"""Return a mapping dictionary for a chapter section. Positional arguments: chId: str -- chapter ID. chapterNumber: int... | stack_v2_sparse_classes_36k_train_005943 | 3,448 | permissive | [
{
"docstring": "Return a mapping dictionary for a chapter section. Positional arguments: chId: str -- chapter ID. chapterNumber: int -- chapter number. Suppress the chapter title if necessary. Extends the superclass method.",
"name": "_get_chapterMapping",
"signature": "def _get_chapterMapping(self, chI... | 2 | stack_v2_sparse_classes_30k_train_010437 | Implement the Python class `OdtWManuscript` described below.
Class description:
ODT manuscript file writer. Export a manuscript with invisibly tagged chapters and scenes.
Method signatures and docstrings:
- def _get_chapterMapping(self, chId, chapterNumber): Return a mapping dictionary for a chapter section. Position... | Implement the Python class `OdtWManuscript` described below.
Class description:
ODT manuscript file writer. Export a manuscript with invisibly tagged chapters and scenes.
Method signatures and docstrings:
- def _get_chapterMapping(self, chId, chapterNumber): Return a mapping dictionary for a chapter section. Position... | 33a868daed653c3371f5991d243a034668a80884 | <|skeleton|>
class OdtWManuscript:
"""ODT manuscript file writer. Export a manuscript with invisibly tagged chapters and scenes."""
def _get_chapterMapping(self, chId, chapterNumber):
"""Return a mapping dictionary for a chapter section. Positional arguments: chId: str -- chapter ID. chapterNumber: int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OdtWManuscript:
"""ODT manuscript file writer. Export a manuscript with invisibly tagged chapters and scenes."""
def _get_chapterMapping(self, chId, chapterNumber):
"""Return a mapping dictionary for a chapter section. Positional arguments: chId: str -- chapter ID. chapterNumber: int -- chapter n... | the_stack_v2_python_sparse | src/pywriter/odt_w/odt_w_manuscript.py | peter88213/PyWriter | train | 3 |
4d5be2f9031339bfd610484fc9c82cb3bbf73440 | [
"kwargs = super().get_form_kwargs()\ntry:\n kwargs.update({'totp_secret': self.request.session['totp_secret']})\nexcept KeyError:\n raise Http404\nreturn kwargs",
"user = models.User.objects.get(pk=self.request.session.pop('user_pk'))\nself.request.session.pop('totp_secret')\ntoken = default_token_generator... | <|body_start_0|>
kwargs = super().get_form_kwargs()
try:
kwargs.update({'totp_secret': self.request.session['totp_secret']})
except KeyError:
raise Http404
return kwargs
<|end_body_0|>
<|body_start_1|>
user = models.User.objects.get(pk=self.request.sessio... | View to verify a code received by SMS. | VerifySMSCodeView | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerifySMSCodeView:
"""View to verify a code received by SMS."""
def get_form_kwargs(self):
"""Include totp secret in kwargs."""
<|body_0|>
def form_valid(self, form):
"""Redirect to reset password form."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_005944 | 9,442 | permissive | [
{
"docstring": "Include totp secret in kwargs.",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self)"
},
{
"docstring": "Redirect to reset password form.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | null | Implement the Python class `VerifySMSCodeView` described below.
Class description:
View to verify a code received by SMS.
Method signatures and docstrings:
- def get_form_kwargs(self): Include totp secret in kwargs.
- def form_valid(self, form): Redirect to reset password form. | Implement the Python class `VerifySMSCodeView` described below.
Class description:
View to verify a code received by SMS.
Method signatures and docstrings:
- def get_form_kwargs(self): Include totp secret in kwargs.
- def form_valid(self, form): Redirect to reset password form.
<|skeleton|>
class VerifySMSCodeView:
... | df699aab0799ec1725b6b89be38e56285821c889 | <|skeleton|>
class VerifySMSCodeView:
"""View to verify a code received by SMS."""
def get_form_kwargs(self):
"""Include totp secret in kwargs."""
<|body_0|>
def form_valid(self, form):
"""Redirect to reset password form."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VerifySMSCodeView:
"""View to verify a code received by SMS."""
def get_form_kwargs(self):
"""Include totp secret in kwargs."""
kwargs = super().get_form_kwargs()
try:
kwargs.update({'totp_secret': self.request.session['totp_secret']})
except KeyError:
... | the_stack_v2_python_sparse | modoboa/core/views/auth.py | modoboa/modoboa | train | 2,201 |
723b88ebb01c603955e1ebc4df95994caad0585f | [
"assert schema is not None, 'The `schema` argument must be provided.'\nif not schema.coerce:\n return check_obj\nerror_handler = SchemaErrorHandler(lazy=True)\ncoerced_multi_index = {}\nfor i, index in enumerate(schema.indexes):\n if all((x is None for x in schema.names)):\n index_levels = [i]\n els... | <|body_start_0|>
assert schema is not None, 'The `schema` argument must be provided.'
if not schema.coerce:
return check_obj
error_handler = SchemaErrorHandler(lazy=True)
coerced_multi_index = {}
for i, index in enumerate(schema.indexes):
if all((x is None... | Backend implementation for pandas multiindex. | MultiIndexBackend | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiIndexBackend:
"""Backend implementation for pandas multiindex."""
def coerce_dtype(self, check_obj: pd.MultiIndex, schema=None) -> pd.MultiIndex:
"""Coerce type of a pd.Series by type specified in dtype. :param obj: multi-index to coerce. :returns: ``MultiIndex`` with coerced da... | stack_v2_sparse_classes_36k_train_005945 | 19,001 | permissive | [
{
"docstring": "Coerce type of a pd.Series by type specified in dtype. :param obj: multi-index to coerce. :returns: ``MultiIndex`` with coerced data type",
"name": "coerce_dtype",
"signature": "def coerce_dtype(self, check_obj: pd.MultiIndex, schema=None) -> pd.MultiIndex"
},
{
"docstring": "Val... | 4 | stack_v2_sparse_classes_30k_train_017106 | Implement the Python class `MultiIndexBackend` described below.
Class description:
Backend implementation for pandas multiindex.
Method signatures and docstrings:
- def coerce_dtype(self, check_obj: pd.MultiIndex, schema=None) -> pd.MultiIndex: Coerce type of a pd.Series by type specified in dtype. :param obj: multi-... | Implement the Python class `MultiIndexBackend` described below.
Class description:
Backend implementation for pandas multiindex.
Method signatures and docstrings:
- def coerce_dtype(self, check_obj: pd.MultiIndex, schema=None) -> pd.MultiIndex: Coerce type of a pd.Series by type specified in dtype. :param obj: multi-... | 850dcf8e59632d54bc9a6df47b9ca08afa089a27 | <|skeleton|>
class MultiIndexBackend:
"""Backend implementation for pandas multiindex."""
def coerce_dtype(self, check_obj: pd.MultiIndex, schema=None) -> pd.MultiIndex:
"""Coerce type of a pd.Series by type specified in dtype. :param obj: multi-index to coerce. :returns: ``MultiIndex`` with coerced da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiIndexBackend:
"""Backend implementation for pandas multiindex."""
def coerce_dtype(self, check_obj: pd.MultiIndex, schema=None) -> pd.MultiIndex:
"""Coerce type of a pd.Series by type specified in dtype. :param obj: multi-index to coerce. :returns: ``MultiIndex`` with coerced data type"""
... | the_stack_v2_python_sparse | pandera/backends/pandas/components.py | unionai-oss/pandera | train | 997 |
5849554cbf30be7e9d6edc82e992bf4f8eb0f73a | [
"tab = request.GET['tab']\nif tab == 'fund':\n urls = AwsService.get_default_list_icons('standard_fund/')[1:]\nelif tab == 'income':\n urls = AwsService.get_default_list_icons('standard_income/')[1:]\nelif tab == 'spending':\n urls = AwsService.get_default_list_icons('standard/')[1:]\nelif tab == 'group':\... | <|body_start_0|>
tab = request.GET['tab']
if tab == 'fund':
urls = AwsService.get_default_list_icons('standard_fund/')[1:]
elif tab == 'income':
urls = AwsService.get_default_list_icons('standard_income/')[1:]
elif tab == 'spending':
urls = AwsService.... | View for handling CRUD methods for images in the AmazonS3 bucket | FileHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileHandler:
"""View for handling CRUD methods for images in the AmazonS3 bucket"""
def get(self, request):
"""the method retrieves default icons from AWS S3 :param - request object"""
<|body_0|>
def post(self, request):
"""The name property of the file which is ... | stack_v2_sparse_classes_36k_train_005946 | 3,252 | no_license | [
{
"docstring": "the method retrieves default icons from AWS S3 :param - request object",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "The name property of the file which is passed is 'icon', so in HTML form it must be set: <input type='file' name = 'icon'>",
"name"... | 4 | stack_v2_sparse_classes_30k_train_004452 | Implement the Python class `FileHandler` described below.
Class description:
View for handling CRUD methods for images in the AmazonS3 bucket
Method signatures and docstrings:
- def get(self, request): the method retrieves default icons from AWS S3 :param - request object
- def post(self, request): The name property ... | Implement the Python class `FileHandler` described below.
Class description:
View for handling CRUD methods for images in the AmazonS3 bucket
Method signatures and docstrings:
- def get(self, request): the method retrieves default icons from AWS S3 :param - request object
- def post(self, request): The name property ... | b5589f40581e567512c0a4e0f4c5f9c5c507a1d7 | <|skeleton|>
class FileHandler:
"""View for handling CRUD methods for images in the AmazonS3 bucket"""
def get(self, request):
"""the method retrieves default icons from AWS S3 :param - request object"""
<|body_0|>
def post(self, request):
"""The name property of the file which is ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileHandler:
"""View for handling CRUD methods for images in the AmazonS3 bucket"""
def get(self, request):
"""the method retrieves default icons from AWS S3 :param - request object"""
tab = request.GET['tab']
if tab == 'fund':
urls = AwsService.get_default_list_icons(... | the_stack_v2_python_sparse | iBudget/ibudget/views.py | antooa/familyFinanceTracker | train | 0 |
7de65201b624df9a7e3b04c0a1eb4173089f87fd | [
"self.files_selector = files_selector\nself.on_nfs_files = on_nfs_files\nself.vm_selector = vm_selector",
"if dictionary is None:\n return None\nfiles_selector = cohesity_management_sdk.models.input_spec_input_files_selector.InputSpec_InputFilesSelector.from_dictionary(dictionary.get('filesSelector')) if dicti... | <|body_start_0|>
self.files_selector = files_selector
self.on_nfs_files = on_nfs_files
self.vm_selector = vm_selector
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
files_selector = cohesity_management_sdk.models.input_spec_input_files_selector.In... | Implementation of the 'InputSpec' model. TODO: type description here. Attributes: files_selector (InputSpec_InputFilesSelector): TODO: Type description here. on_nfs_files (bool): Selects whether input is files inside vmdks or files on NFS. One of vm_selector or files_selector will be chosen based on this flag. vm_selec... | InputSpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputSpec:
"""Implementation of the 'InputSpec' model. TODO: type description here. Attributes: files_selector (InputSpec_InputFilesSelector): TODO: Type description here. on_nfs_files (bool): Selects whether input is files inside vmdks or files on NFS. One of vm_selector or files_selector will b... | stack_v2_sparse_classes_36k_train_005947 | 2,448 | permissive | [
{
"docstring": "Constructor for the InputSpec class",
"name": "__init__",
"signature": "def __init__(self, files_selector=None, on_nfs_files=None, vm_selector=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation ... | 2 | null | Implement the Python class `InputSpec` described below.
Class description:
Implementation of the 'InputSpec' model. TODO: type description here. Attributes: files_selector (InputSpec_InputFilesSelector): TODO: Type description here. on_nfs_files (bool): Selects whether input is files inside vmdks or files on NFS. One ... | Implement the Python class `InputSpec` described below.
Class description:
Implementation of the 'InputSpec' model. TODO: type description here. Attributes: files_selector (InputSpec_InputFilesSelector): TODO: Type description here. on_nfs_files (bool): Selects whether input is files inside vmdks or files on NFS. One ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class InputSpec:
"""Implementation of the 'InputSpec' model. TODO: type description here. Attributes: files_selector (InputSpec_InputFilesSelector): TODO: Type description here. on_nfs_files (bool): Selects whether input is files inside vmdks or files on NFS. One of vm_selector or files_selector will b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputSpec:
"""Implementation of the 'InputSpec' model. TODO: type description here. Attributes: files_selector (InputSpec_InputFilesSelector): TODO: Type description here. on_nfs_files (bool): Selects whether input is files inside vmdks or files on NFS. One of vm_selector or files_selector will be chosen base... | the_stack_v2_python_sparse | cohesity_management_sdk/models/input_spec.py | cohesity/management-sdk-python | train | 24 |
6d00027bc2ce07503efbf6d0a034558688368a13 | [
"key = tokey(source.key, geometry_string, serialize(options))\nfilename, _ext = os.path.splitext(os.path.basename(source.name))\npath = '%s/%s' % (key, filename)\nreturn '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])",
"source_image = source_image.convert('RGB')\nlogger.debug('Creati... | <|body_start_0|>
key = tokey(source.key, geometry_string, serialize(options))
filename, _ext = os.path.splitext(os.path.basename(source.name))
path = '%s/%s' % (key, filename)
return '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])
<|end_body_0|>
<|body_start... | SEOThumbnailBackend | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEOThumbnailBackend:
def _get_thumbnail_filename(self, source, geometry_string, options):
"""Computes the destination filename."""
<|body_0|>
def _create_thumbnail(self, source_image, geometry_string, options, thumbnail):
"""Creates the thumbnail by using default.eng... | stack_v2_sparse_classes_36k_train_005948 | 1,602 | permissive | [
{
"docstring": "Computes the destination filename.",
"name": "_get_thumbnail_filename",
"signature": "def _get_thumbnail_filename(self, source, geometry_string, options)"
},
{
"docstring": "Creates the thumbnail by using default.engine",
"name": "_create_thumbnail",
"signature": "def _cr... | 2 | stack_v2_sparse_classes_30k_train_009766 | Implement the Python class `SEOThumbnailBackend` described below.
Class description:
Implement the SEOThumbnailBackend class.
Method signatures and docstrings:
- def _get_thumbnail_filename(self, source, geometry_string, options): Computes the destination filename.
- def _create_thumbnail(self, source_image, geometry... | Implement the Python class `SEOThumbnailBackend` described below.
Class description:
Implement the SEOThumbnailBackend class.
Method signatures and docstrings:
- def _get_thumbnail_filename(self, source, geometry_string, options): Computes the destination filename.
- def _create_thumbnail(self, source_image, geometry... | e21aa8fa62df96f41ddbea913f386ee7c6780ed0 | <|skeleton|>
class SEOThumbnailBackend:
def _get_thumbnail_filename(self, source, geometry_string, options):
"""Computes the destination filename."""
<|body_0|>
def _create_thumbnail(self, source_image, geometry_string, options, thumbnail):
"""Creates the thumbnail by using default.eng... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SEOThumbnailBackend:
def _get_thumbnail_filename(self, source, geometry_string, options):
"""Computes the destination filename."""
key = tokey(source.key, geometry_string, serialize(options))
filename, _ext = os.path.splitext(os.path.basename(source.name))
path = '%s/%s' % (key... | the_stack_v2_python_sparse | jobsp/thumbnailname.py | MicroPyramid/opensource-job-portal | train | 360 | |
8cdc70f87477f8a7c738c6191d83312fc5580e7b | [
"s = []\nqueue = deque()\nqueue.append(root)\nwhile queue:\n cur = queue.pop()\n if cur:\n s.append(str(cur.val))\n queue.appendleft(cur.left)\n queue.appendleft(cur.right)\n else:\n s.append('null')\n s.append(',')\nres = ''.join(s)\nreturn res",
"tree = data.split(',')\ni... | <|body_start_0|>
s = []
queue = deque()
queue.append(root)
while queue:
cur = queue.pop()
if cur:
s.append(str(cur.val))
queue.appendleft(cur.left)
queue.appendleft(cur.right)
else:
s.appe... | 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_005949 | 1,842 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_017453 | 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:... | 7ebe6f3a373403125549346c49a08f9c554dafac | <|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"""
s = []
queue = deque()
queue.append(root)
while queue:
cur = queue.pop()
if cur:
s.append(str(cur.val))
qu... | the_stack_v2_python_sparse | 二叉树/serialize.py | takenmore/Leetcode_record | train | 0 | |
20f41804efeea6051c28563026ff39cde925cc82 | [
"res_head = ListNode(0)\nres_cur = res_head\nwhile len(lists) > 0:\n min_pos = -1\n remove_pos = []\n for i in range(len(lists)):\n if lists[i]:\n if min_pos < 0 or lists[min_pos].val > lists[i].val:\n min_pos = i\n else:\n remove_pos.append(i)\n res_cu... | <|body_start_0|>
res_head = ListNode(0)
res_cur = res_head
while len(lists) > 0:
min_pos = -1
remove_pos = []
for i in range(len(lists)):
if lists[i]:
if min_pos < 0 or lists[min_pos].val > lists[i].val:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists1(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res_head = ListNode(... | stack_v2_sparse_classes_36k_train_005950 | 2,603 | no_license | [
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists1",
"signature": "def mergeKLists1(self, lists)"
},
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists1(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists1(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
<|skeleton|>
class Solut... | 85ddffc5c835e36dcb12b2457abef6aa98b44a78 | <|skeleton|>
class Solution:
def mergeKLists1(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists1(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
res_head = ListNode(0)
res_cur = res_head
while len(lists) > 0:
min_pos = -1
remove_pos = []
for i in range(len(lists)):
if lists[i]:
... | the_stack_v2_python_sparse | q23_merge_k_sorted_lists.py | ddizhang/code-like-a-geek | train | 0 | |
57d7c6e3d3fce553f2a7c46a93511e196f9136a9 | [
"super().__init__()\nlogger.debug('Create PaddleCLSConnectionHandler to process the cls request')\nself._inputs = OrderedDict()\nself._outputs = OrderedDict()\nself.cls_engine = cls_engine\nself.executor = self.cls_engine.executor\nself._conf = self.executor._conf\nself._label_list = self.executor._label_list\nself... | <|body_start_0|>
super().__init__()
logger.debug('Create PaddleCLSConnectionHandler to process the cls request')
self._inputs = OrderedDict()
self._outputs = OrderedDict()
self.cls_engine = cls_engine
self.executor = self.cls_engine.executor
self._conf = self.exec... | PaddleCLSConnectionHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaddleCLSConnectionHandler:
def __init__(self, cls_engine):
"""The PaddleSpeech CLS Server Connection Handler This connection process every cls server request Args: cls_engine (CLSEngine): The CLS engine"""
<|body_0|>
def run(self, audio_data):
"""engine run Args: au... | stack_v2_sparse_classes_36k_train_005951 | 4,065 | permissive | [
{
"docstring": "The PaddleSpeech CLS Server Connection Handler This connection process every cls server request Args: cls_engine (CLSEngine): The CLS engine",
"name": "__init__",
"signature": "def __init__(self, cls_engine)"
},
{
"docstring": "engine run Args: audio_data (bytes): base64.b64decod... | 3 | stack_v2_sparse_classes_30k_train_010283 | Implement the Python class `PaddleCLSConnectionHandler` described below.
Class description:
Implement the PaddleCLSConnectionHandler class.
Method signatures and docstrings:
- def __init__(self, cls_engine): The PaddleSpeech CLS Server Connection Handler This connection process every cls server request Args: cls_engi... | Implement the Python class `PaddleCLSConnectionHandler` described below.
Class description:
Implement the PaddleCLSConnectionHandler class.
Method signatures and docstrings:
- def __init__(self, cls_engine): The PaddleSpeech CLS Server Connection Handler This connection process every cls server request Args: cls_engi... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class PaddleCLSConnectionHandler:
def __init__(self, cls_engine):
"""The PaddleSpeech CLS Server Connection Handler This connection process every cls server request Args: cls_engine (CLSEngine): The CLS engine"""
<|body_0|>
def run(self, audio_data):
"""engine run Args: au... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaddleCLSConnectionHandler:
def __init__(self, cls_engine):
"""The PaddleSpeech CLS Server Connection Handler This connection process every cls server request Args: cls_engine (CLSEngine): The CLS engine"""
super().__init__()
logger.debug('Create PaddleCLSConnectionHandler to process t... | the_stack_v2_python_sparse | paddlespeech/server/engine/cls/python/cls_engine.py | anniyanvr/DeepSpeech-1 | train | 0 | |
40b45895e73a7a46bee620bf24660a417421340e | [
"Thread.__init__(self)\nself.IP = IP\nself.scan_type = scan_type\nself.file = file\nself.connstr = ''\nself.scanresult = ''",
"try:\n cd = pyclamd.ClamdNetworkSocket(self.IP, 1050)\n if cd.ping():\n self.connstr = self.IP + ' connection [OK]'\n cd.reload()\n if self.scan_type == 'contsc... | <|body_start_0|>
Thread.__init__(self)
self.IP = IP
self.scan_type = scan_type
self.file = file
self.connstr = ''
self.scanresult = ''
<|end_body_0|>
<|body_start_1|>
try:
cd = pyclamd.ClamdNetworkSocket(self.IP, 1050)
if cd.ping():
... | Scan | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scan:
def __init__(self, IP, scan_type, file):
"""构造方法"""
<|body_0|>
def run(self):
"""多进程run方法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Thread.__init__(self)
self.IP = IP
self.scan_type = scan_type
self.file = file
... | stack_v2_sparse_classes_36k_train_005952 | 1,648 | permissive | [
{
"docstring": "构造方法",
"name": "__init__",
"signature": "def __init__(self, IP, scan_type, file)"
},
{
"docstring": "多进程run方法",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005499 | Implement the Python class `Scan` described below.
Class description:
Implement the Scan class.
Method signatures and docstrings:
- def __init__(self, IP, scan_type, file): 构造方法
- def run(self): 多进程run方法 | Implement the Python class `Scan` described below.
Class description:
Implement the Scan class.
Method signatures and docstrings:
- def __init__(self, IP, scan_type, file): 构造方法
- def run(self): 多进程run方法
<|skeleton|>
class Scan:
def __init__(self, IP, scan_type, file):
"""构造方法"""
<|body_0|>
... | 4f6bb04081d7e04383fdf2fb9b7baef4e768db4c | <|skeleton|>
class Scan:
def __init__(self, IP, scan_type, file):
"""构造方法"""
<|body_0|>
def run(self):
"""多进程run方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scan:
def __init__(self, IP, scan_type, file):
"""构造方法"""
Thread.__init__(self)
self.IP = IP
self.scan_type = scan_type
self.file = file
self.connstr = ''
self.scanresult = ''
def run(self):
"""多进程run方法"""
try:
cd = pycla... | the_stack_v2_python_sparse | 第四章/pyClamad/simple1.py | tools2018/python-devops | train | 0 | |
93af8c078317e6b09543fc8a7d0c230abd2667aa | [
"output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'Payload'], [request.data['AvailabilityDetails'], request.data['AuthenticationDetails'], None]))\njson_params = request.data['APIParams']\noutput_json['Payload'] = self.pre_login_raise_ticket_json(json_params)\nreturn Response(output_json)",
... | <|body_start_0|>
output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'Payload'], [request.data['AvailabilityDetails'], request.data['AuthenticationDetails'], None]))
json_params = request.data['APIParams']
output_json['Payload'] = self.pre_login_raise_ticket_json(json_params)... | This covers the API for get all ticket types. | PreLoginRaiseTicketAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreLoginRaiseTicketAPI:
"""This covers the API for get all ticket types."""
def post(self, request):
"""Post Function for getting ticket types."""
<|body_0|>
def pre_login_raise_ticket_json(self, request):
"""This function checks if the email address already has ... | stack_v2_sparse_classes_36k_train_005953 | 5,694 | no_license | [
{
"docstring": "Post Function for getting ticket types.",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "This function checks if the email address already has an account with us. If yes then it raises a post login ticket else raises a pre-login ticket. Pre-login ticket... | 2 | null | Implement the Python class `PreLoginRaiseTicketAPI` described below.
Class description:
This covers the API for get all ticket types.
Method signatures and docstrings:
- def post(self, request): Post Function for getting ticket types.
- def pre_login_raise_ticket_json(self, request): This function checks if the email... | Implement the Python class `PreLoginRaiseTicketAPI` described below.
Class description:
This covers the API for get all ticket types.
Method signatures and docstrings:
- def post(self, request): Post Function for getting ticket types.
- def pre_login_raise_ticket_json(self, request): This function checks if the email... | 36eb9931f330e64902354c6fc471be2adf4b7049 | <|skeleton|>
class PreLoginRaiseTicketAPI:
"""This covers the API for get all ticket types."""
def post(self, request):
"""Post Function for getting ticket types."""
<|body_0|>
def pre_login_raise_ticket_json(self, request):
"""This function checks if the email address already has ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreLoginRaiseTicketAPI:
"""This covers the API for get all ticket types."""
def post(self, request):
"""Post Function for getting ticket types."""
output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'Payload'], [request.data['AvailabilityDetails'], request.data['Authen... | the_stack_v2_python_sparse | Generic/common/supportcentre/api/pre_login_raise_ticket/views_pre_login_raise_ticket.py | archiemb303/common_backend_django | train | 0 |
c432ffa83c618f412d51c7116e955b9a9636e076 | [
"clf = self._clf.steps[-1][1].regressor_\nif not hasattr(clf, 'evals_result_'):\n raise AttributeError(\"Plotting training progress for XGBRegressor model is not possible, necessary attribute 'evals_result_' is missing. This is usually cause by calling MLRModel.rfecv()\")\nevals_result = clf.evals_result()\ntrai... | <|body_start_0|>
clf = self._clf.steps[-1][1].regressor_
if not hasattr(clf, 'evals_result_'):
raise AttributeError("Plotting training progress for XGBRegressor model is not possible, necessary attribute 'evals_result_' is missing. This is usually cause by calling MLRModel.rfecv()")
... | Gradient Boosting Regression model (:mod:`xgboost` implementation). | XGBoostGBRModel | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XGBoostGBRModel:
"""Gradient Boosting Regression model (:mod:`xgboost` implementation)."""
def plot_training_progress(self, filename=None):
"""Plot training progress for training and (if possible) test data. Parameters ---------- filename : str, optional (default: 'training_progress'... | stack_v2_sparse_classes_36k_train_005954 | 3,174 | permissive | [
{
"docstring": "Plot training progress for training and (if possible) test data. Parameters ---------- filename : str, optional (default: 'training_progress') Name of the plot file.",
"name": "plot_training_progress",
"signature": "def plot_training_progress(self, filename=None)"
},
{
"docstring... | 2 | null | Implement the Python class `XGBoostGBRModel` described below.
Class description:
Gradient Boosting Regression model (:mod:`xgboost` implementation).
Method signatures and docstrings:
- def plot_training_progress(self, filename=None): Plot training progress for training and (if possible) test data. Parameters --------... | Implement the Python class `XGBoostGBRModel` described below.
Class description:
Gradient Boosting Regression model (:mod:`xgboost` implementation).
Method signatures and docstrings:
- def plot_training_progress(self, filename=None): Plot training progress for training and (if possible) test data. Parameters --------... | 0d2b68d6614c667141207affd7834cc49d34b203 | <|skeleton|>
class XGBoostGBRModel:
"""Gradient Boosting Regression model (:mod:`xgboost` implementation)."""
def plot_training_progress(self, filename=None):
"""Plot training progress for training and (if possible) test data. Parameters ---------- filename : str, optional (default: 'training_progress'... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XGBoostGBRModel:
"""Gradient Boosting Regression model (:mod:`xgboost` implementation)."""
def plot_training_progress(self, filename=None):
"""Plot training progress for training and (if possible) test data. Parameters ---------- filename : str, optional (default: 'training_progress') Name of the... | the_stack_v2_python_sparse | esmvaltool/diag_scripts/mlr/models/gbr_xgboost.py | ESMValGroup/ESMValTool | train | 196 |
c886e273972ecb4f7d0f52ed30b61359eaaba35b | [
"self.l = len(nums)\nif self.l == 1:\n return 0\nelif self.l == 2:\n return nums.index(max(nums))\nelse:\n return self.findPeakHelper(nums, 0, self.l)",
"if end - start <= 1 or start == self.l - 1:\n return start\nmid = (start + end) // 2\nif mid == 0 and nums[mid + 1] < nums[mid]:\n return mid\nel... | <|body_start_0|>
self.l = len(nums)
if self.l == 1:
return 0
elif self.l == 2:
return nums.index(max(nums))
else:
return self.findPeakHelper(nums, 0, self.l)
<|end_body_0|>
<|body_start_1|>
if end - start <= 1 or start == self.l - 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findPeakHelper(self, nums, start, end):
""":type nums: List[int] :type start: int :type end: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_005955 | 1,689 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findPeakElement",
"signature": "def findPeakElement(self, nums)"
},
{
"docstring": ":type nums: List[int] :type start: int :type end: int :rtype: int",
"name": "findPeakHelper",
"signature": "def findPeakHelper(self, nums, star... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPeakElement(self, nums): :type nums: List[int] :rtype: int
- def findPeakHelper(self, nums, start, end): :type nums: List[int] :type start: int :type end: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPeakElement(self, nums): :type nums: List[int] :rtype: int
- def findPeakHelper(self, nums, start, end): :type nums: List[int] :type start: int :type end: int :rtype: int... | 8cda0518440488992d7e2c70cb8555ec7b34083f | <|skeleton|>
class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findPeakHelper(self, nums, start, end):
""":type nums: List[int] :type start: int :type end: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
self.l = len(nums)
if self.l == 1:
return 0
elif self.l == 2:
return nums.index(max(nums))
else:
return self.findPeakHelper(nums, 0, self.l)
def f... | the_stack_v2_python_sparse | 162/main.py | szhongren/leetcode | train | 0 | |
7f0dfc1110133736ac69a0a4cc59792d09dec424 | [
"self.id = id\nself.url = url\nself.links = links\nself.external_signer_id = external_signer_id\nself.redirect_settings = redirect_settings\nself.signature_type = signature_type\nself.ui = ui\nself.tags = tags\nself.order = order\nself.required = required\nself.additional_properties = additional_properties",
"if ... | <|body_start_0|>
self.id = id
self.url = url
self.links = links
self.external_signer_id = external_signer_id
self.redirect_settings = redirect_settings
self.signature_type = signature_type
self.ui = ui
self.tags = tags
self.order = order
se... | Implementation of the 'Signer' model. TODO: type model description here. Attributes: id (string): TODO: type description here. url (string): TODO: type description here. links (list of string): TODO: type description here. external_signer_id (string): TODO: type description here. redirect_settings (RedirectSettings): T... | Signer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Signer:
"""Implementation of the 'Signer' model. TODO: type model description here. Attributes: id (string): TODO: type description here. url (string): TODO: type description here. links (list of string): TODO: type description here. external_signer_id (string): TODO: type description here. redir... | stack_v2_sparse_classes_36k_train_005956 | 4,100 | permissive | [
{
"docstring": "Constructor for the Signer class",
"name": "__init__",
"signature": "def __init__(self, external_signer_id=None, id=None, links=None, order=None, redirect_settings=None, required=None, signature_type=None, tags=None, ui=None, url=None, additional_properties={})"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_000502 | Implement the Python class `Signer` described below.
Class description:
Implementation of the 'Signer' model. TODO: type model description here. Attributes: id (string): TODO: type description here. url (string): TODO: type description here. links (list of string): TODO: type description here. external_signer_id (stri... | Implement the Python class `Signer` described below.
Class description:
Implementation of the 'Signer' model. TODO: type model description here. Attributes: id (string): TODO: type description here. url (string): TODO: type description here. links (list of string): TODO: type description here. external_signer_id (stri... | 49acc3d416a1dde7ea43b178d070484baf1b7f2b | <|skeleton|>
class Signer:
"""Implementation of the 'Signer' model. TODO: type model description here. Attributes: id (string): TODO: type description here. url (string): TODO: type description here. links (list of string): TODO: type description here. external_signer_id (string): TODO: type description here. redir... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Signer:
"""Implementation of the 'Signer' model. TODO: type model description here. Attributes: id (string): TODO: type description here. url (string): TODO: type description here. links (list of string): TODO: type description here. external_signer_id (string): TODO: type description here. redirect_settings ... | the_stack_v2_python_sparse | PYTHON_GENERIC_LIB/tester/models/signer.py | MaryamAdnan3/Tester1 | train | 0 |
a873c31f705f7238e5aa8ea8aaeb61e7323a4fd6 | [
"from .function_field import is_RationalFunctionField\nif not is_RationalFunctionField(K):\n raise ValueError('K must be a rational function field')\nif u.parent() is not K:\n raise ValueError('u must be an element in K')\nFunctionFieldDerivation.__init__(self, K)\nself._u = u",
"f, g = (x.numerator(), x.de... | <|body_start_0|>
from .function_field import is_RationalFunctionField
if not is_RationalFunctionField(K):
raise ValueError('K must be a rational function field')
if u.parent() is not K:
raise ValueError('u must be an element in K')
FunctionFieldDerivation.__init__... | A derivation on a rational function field. INPUT: - ``K`` -- a rational function field - ``u`` -- an element of ``K``, the image of the generator of ``K`` under the derivation. EXAMPLES:: sage: K.<x> = FunctionField(QQ) sage: d = K.derivation() sage: isinstance(d, sage.rings.function_field.maps.FunctionFieldDerivation_... | FunctionFieldDerivation_rational | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionFieldDerivation_rational:
"""A derivation on a rational function field. INPUT: - ``K`` -- a rational function field - ``u`` -- an element of ``K``, the image of the generator of ``K`` under the derivation. EXAMPLES:: sage: K.<x> = FunctionField(QQ) sage: d = K.derivation() sage: isinstanc... | stack_v2_sparse_classes_36k_train_005957 | 18,835 | no_license | [
{
"docstring": "Initialize a derivation of ``K`` which sends the generator of ``K`` to ``u``. EXAMPLES:: sage: K.<x> = FunctionField(QQ) sage: d = K.derivation() # indirect doctest",
"name": "__init__",
"signature": "def __init__(self, K, u)"
},
{
"docstring": "Compute the derivation of ``x``. I... | 2 | null | Implement the Python class `FunctionFieldDerivation_rational` described below.
Class description:
A derivation on a rational function field. INPUT: - ``K`` -- a rational function field - ``u`` -- an element of ``K``, the image of the generator of ``K`` under the derivation. EXAMPLES:: sage: K.<x> = FunctionField(QQ) s... | Implement the Python class `FunctionFieldDerivation_rational` described below.
Class description:
A derivation on a rational function field. INPUT: - ``K`` -- a rational function field - ``u`` -- an element of ``K``, the image of the generator of ``K`` under the derivation. EXAMPLES:: sage: K.<x> = FunctionField(QQ) s... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class FunctionFieldDerivation_rational:
"""A derivation on a rational function field. INPUT: - ``K`` -- a rational function field - ``u`` -- an element of ``K``, the image of the generator of ``K`` under the derivation. EXAMPLES:: sage: K.<x> = FunctionField(QQ) sage: d = K.derivation() sage: isinstanc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FunctionFieldDerivation_rational:
"""A derivation on a rational function field. INPUT: - ``K`` -- a rational function field - ``u`` -- an element of ``K``, the image of the generator of ``K`` under the derivation. EXAMPLES:: sage: K.<x> = FunctionField(QQ) sage: d = K.derivation() sage: isinstance(d, sage.rin... | the_stack_v2_python_sparse | sage/src/sage/rings/function_field/maps.py | bopopescu/geosci | train | 0 |
d6dae09b0fd339f6e9055fcb9005ce68cb0f2921 | [
"self.mean = mean\nself.icdf_array = np.asarray(icdf_array)\nself.CDF_RES = len(icdf_array) - 1\nself.time_steps_per_day = pe.Parameters.instance().time_steps_per_day",
"rand_num = random.random()\nq = rand_num * self.CDF_RES\ni = math.floor(q)\nq -= float(i)\nti = self.mean * (q * self.icdf_array[i + 1] + (1.0 -... | <|body_start_0|>
self.mean = mean
self.icdf_array = np.asarray(icdf_array)
self.CDF_RES = len(icdf_array) - 1
self.time_steps_per_day = pe.Parameters.instance().time_steps_per_day
<|end_body_0|>
<|body_start_1|>
rand_num = random.random()
q = rand_num * self.CDF_RES
... | Class of inverse cumulative distribution functions (icdf) and their associated methods, in a style similar to CovidSim. | InverseCdf | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InverseCdf:
"""Class of inverse cumulative distribution functions (icdf) and their associated methods, in a style similar to CovidSim."""
def __init__(self, mean, icdf_array):
"""Constructor Method Parameters ---------- mean : float Mean of the icdf icdf_array : np.ndarray Array of q... | stack_v2_sparse_classes_36k_train_005958 | 2,643 | permissive | [
{
"docstring": "Constructor Method Parameters ---------- mean : float Mean of the icdf icdf_array : np.ndarray Array of quantiles of the icdf_array, values in array must be evenly spaced with the final value being as close to one as possible",
"name": "__init__",
"signature": "def __init__(self, mean, i... | 3 | stack_v2_sparse_classes_30k_train_015206 | Implement the Python class `InverseCdf` described below.
Class description:
Class of inverse cumulative distribution functions (icdf) and their associated methods, in a style similar to CovidSim.
Method signatures and docstrings:
- def __init__(self, mean, icdf_array): Constructor Method Parameters ---------- mean : ... | Implement the Python class `InverseCdf` described below.
Class description:
Class of inverse cumulative distribution functions (icdf) and their associated methods, in a style similar to CovidSim.
Method signatures and docstrings:
- def __init__(self, mean, icdf_array): Constructor Method Parameters ---------- mean : ... | c11de122c6bfdf9103162e4045758808da5df322 | <|skeleton|>
class InverseCdf:
"""Class of inverse cumulative distribution functions (icdf) and their associated methods, in a style similar to CovidSim."""
def __init__(self, mean, icdf_array):
"""Constructor Method Parameters ---------- mean : float Mean of the icdf icdf_array : np.ndarray Array of q... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InverseCdf:
"""Class of inverse cumulative distribution functions (icdf) and their associated methods, in a style similar to CovidSim."""
def __init__(self, mean, icdf_array):
"""Constructor Method Parameters ---------- mean : float Mean of the icdf icdf_array : np.ndarray Array of quantiles of t... | the_stack_v2_python_sparse | pyEpiabm/pyEpiabm/utility/inverse_cdf.py | SABS-R3-Epidemiology/epiabm | train | 21 |
f2d4f0df53102104b9e5a16cfe4d581144061d4a | [
"Gremlin().gremlin_post('graph.truncateBackend();', auth=auth)\nbody = {'group_name': 'gremlin', 'group_description': 'group can execute gremlin'}\ncode, res = Auth().post_groups(body, auth=auth)\nprint(code, res)\nbody = {'target_url': '%s:%d' % (_cfg.graph_host, _cfg.server_port), 'target_name': 'gremlin', 'targe... | <|body_start_0|>
Gremlin().gremlin_post('graph.truncateBackend();', auth=auth)
body = {'group_name': 'gremlin', 'group_description': 'group can execute gremlin'}
code, res = Auth().post_groups(body, auth=auth)
print(code, res)
body = {'target_url': '%s:%d' % (_cfg.graph_host, _cf... | 绑定资源和用户组 | Access | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Access:
"""绑定资源和用户组"""
def setUp(self):
"""测试case开始 :resurn:"""
<|body_0|>
def test_access_create(self):
"""创建 access"""
<|body_1|>
def test_access_delete(self):
"""删除 access"""
<|body_2|>
def test_access_list(self):
"""获... | stack_v2_sparse_classes_36k_train_005959 | 17,517 | no_license | [
{
"docstring": "测试case开始 :resurn:",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "创建 access",
"name": "test_access_create",
"signature": "def test_access_create(self)"
},
{
"docstring": "删除 access",
"name": "test_access_delete",
"signature": "def test... | 6 | stack_v2_sparse_classes_30k_train_001617 | Implement the Python class `Access` described below.
Class description:
绑定资源和用户组
Method signatures and docstrings:
- def setUp(self): 测试case开始 :resurn:
- def test_access_create(self): 创建 access
- def test_access_delete(self): 删除 access
- def test_access_list(self): 获取 access
- def test_access_one(self): 获取 access
- d... | Implement the Python class `Access` described below.
Class description:
绑定资源和用户组
Method signatures and docstrings:
- def setUp(self): 测试case开始 :resurn:
- def test_access_create(self): 创建 access
- def test_access_delete(self): 删除 access
- def test_access_list(self): 获取 access
- def test_access_one(self): 获取 access
- d... | 89e5b34ab925bcc0bbc4ad63302e96c62a420399 | <|skeleton|>
class Access:
"""绑定资源和用户组"""
def setUp(self):
"""测试case开始 :resurn:"""
<|body_0|>
def test_access_create(self):
"""创建 access"""
<|body_1|>
def test_access_delete(self):
"""删除 access"""
<|body_2|>
def test_access_list(self):
"""获... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Access:
"""绑定资源和用户组"""
def setUp(self):
"""测试case开始 :resurn:"""
Gremlin().gremlin_post('graph.truncateBackend();', auth=auth)
body = {'group_name': 'gremlin', 'group_description': 'group can execute gremlin'}
code, res = Auth().post_groups(body, auth=auth)
print(co... | the_stack_v2_python_sparse | src/graph_function_test/server/auth/test_auth_api.py | hugegraph/hugegraph-test | train | 1 |
de5cc6767c3f9066a3bc76aa323be54addad780c | [
"try:\n firewallController = FirewallController()\n json_data = json.dumps(firewallController.get_interface_ipv4Configuration_address(id))\n resp = Response(json_data, status=200, mimetype='application/json')\n return resp\nexcept ValueError as ve:\n return Response(json.dumps(str(ve)), status=404, m... | <|body_start_0|>
try:
firewallController = FirewallController()
json_data = json.dumps(firewallController.get_interface_ipv4Configuration_address(id))
resp = Response(json_data, status=200, mimetype='application/json')
return resp
except ValueError as ve:
... | Interface_ifEntry_Ipv4Configuration_Address | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interface_ifEntry_Ipv4Configuration_Address:
def get(self, id):
"""Get the ip address of an interface"""
<|body_0|>
def put(self, id):
"""Update the ip address of an interface"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
firewall... | stack_v2_sparse_classes_36k_train_005960 | 12,460 | no_license | [
{
"docstring": "Get the ip address of an interface",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Update the ip address of an interface",
"name": "put",
"signature": "def put(self, id)"
}
] | 2 | null | Implement the Python class `Interface_ifEntry_Ipv4Configuration_Address` described below.
Class description:
Implement the Interface_ifEntry_Ipv4Configuration_Address class.
Method signatures and docstrings:
- def get(self, id): Get the ip address of an interface
- def put(self, id): Update the ip address of an inter... | Implement the Python class `Interface_ifEntry_Ipv4Configuration_Address` described below.
Class description:
Implement the Interface_ifEntry_Ipv4Configuration_Address class.
Method signatures and docstrings:
- def get(self, id): Get the ip address of an interface
- def put(self, id): Update the ip address of an inter... | 6070e3cb6bf957e04f5d8267db11f3296410e18e | <|skeleton|>
class Interface_ifEntry_Ipv4Configuration_Address:
def get(self, id):
"""Get the ip address of an interface"""
<|body_0|>
def put(self, id):
"""Update the ip address of an interface"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Interface_ifEntry_Ipv4Configuration_Address:
def get(self, id):
"""Get the ip address of an interface"""
try:
firewallController = FirewallController()
json_data = json.dumps(firewallController.get_interface_ipv4Configuration_address(id))
resp = Response(jso... | the_stack_v2_python_sparse | configuration-agent/firewall/rest_api/resources/interface.py | ReliableLion/frog4-configurable-vnf | train | 0 | |
b04a47c229c06775263aed689456c8269a417746 | [
"self.policy_model = policy_model\nself.expert_visual_in = self.policy_model.visual_in\nself.obs_in_expert = self.policy_model.vector_in\nself.make_inputs()\nself.create_loss(learning_rate, anneal_steps)",
"self.done_expert = tf.placeholder(shape=[None, 1], dtype=tf.float32)\nself.done_policy = tf.placeholder(sha... | <|body_start_0|>
self.policy_model = policy_model
self.expert_visual_in = self.policy_model.visual_in
self.obs_in_expert = self.policy_model.vector_in
self.make_inputs()
self.create_loss(learning_rate, anneal_steps)
<|end_body_0|>
<|body_start_1|>
self.done_expert = tf.p... | BCModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BCModel:
def __init__(self, policy_model: LearningModel, learning_rate: float=0.0003, anneal_steps: int=0):
"""Tensorflow operations to perform Behavioral Cloning on a Policy model :param policy_model: The policy of the learning algorithm :param lr: The initial learning Rate for behavior... | stack_v2_sparse_classes_36k_train_005961 | 3,118 | permissive | [
{
"docstring": "Tensorflow operations to perform Behavioral Cloning on a Policy model :param policy_model: The policy of the learning algorithm :param lr: The initial learning Rate for behavioral cloning :param anneal_steps: Number of steps over which to anneal BC training",
"name": "__init__",
"signatu... | 3 | null | Implement the Python class `BCModel` described below.
Class description:
Implement the BCModel class.
Method signatures and docstrings:
- def __init__(self, policy_model: LearningModel, learning_rate: float=0.0003, anneal_steps: int=0): Tensorflow operations to perform Behavioral Cloning on a Policy model :param poli... | Implement the Python class `BCModel` described below.
Class description:
Implement the BCModel class.
Method signatures and docstrings:
- def __init__(self, policy_model: LearningModel, learning_rate: float=0.0003, anneal_steps: int=0): Tensorflow operations to perform Behavioral Cloning on a Policy model :param poli... | 334df1e8afbfff3544413ade46fb12f03556014b | <|skeleton|>
class BCModel:
def __init__(self, policy_model: LearningModel, learning_rate: float=0.0003, anneal_steps: int=0):
"""Tensorflow operations to perform Behavioral Cloning on a Policy model :param policy_model: The policy of the learning algorithm :param lr: The initial learning Rate for behavior... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BCModel:
def __init__(self, policy_model: LearningModel, learning_rate: float=0.0003, anneal_steps: int=0):
"""Tensorflow operations to perform Behavioral Cloning on a Policy model :param policy_model: The policy of the learning algorithm :param lr: The initial learning Rate for behavioral cloning :pa... | the_stack_v2_python_sparse | mlagents/trainers/components/bc/model.py | Abluceli/HRG-SAC | train | 7 | |
b6d751bee3e871bce59453d32b8c4bb19b1aa645 | [
"self.parser = reqparse.RequestParser()\nself.parser.add_argument('name')\nself.parser.add_argument('token')\nsuper(CtaStrategyParam, self).__init__()",
"args = self.parser.parse_args()\nname = 'strategyHedge_syt'\nengine = me.getApp('CtaStrategy')\nl = engine.getStrategyParam(name)\nfrom collections import Order... | <|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_argument('token')
super(CtaStrategyParam, self).__init__()
<|end_body_0|>
<|body_start_1|>
args = self.parser.parse_args()
name = 'strategyHedge_syt'
engine =... | 查询策略参数 | CtaStrategyParam | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CtaStrategyParam:
"""查询策略参数"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""订阅"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_... | stack_v2_sparse_classes_36k_train_005962 | 24,002 | permissive | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "订阅",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000490 | Implement the Python class `CtaStrategyParam` described below.
Class description:
查询策略参数
Method signatures and docstrings:
- def __init__(self): 初始化
- def get(self): 订阅 | Implement the Python class `CtaStrategyParam` described below.
Class description:
查询策略参数
Method signatures and docstrings:
- def __init__(self): 初始化
- def get(self): 订阅
<|skeleton|>
class CtaStrategyParam:
"""查询策略参数"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""订... | c316649161086da2543d39bf0455d0f793cdd08f | <|skeleton|>
class CtaStrategyParam:
"""查询策略参数"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""订阅"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CtaStrategyParam:
"""查询策略参数"""
def __init__(self):
"""初始化"""
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_argument('token')
super(CtaStrategyParam, self).__init__()
def get(self):
"""订阅"""
args = self.... | the_stack_v2_python_sparse | WebTrader/webServer.py | webclinic017/riskBacktestingPlatform | train | 0 |
c8a92e3be05aaa1f4307a4ba750ad86a4a5b8dd5 | [
"self.val2nodes = dict()\nself.nodes = list()\nself.node2index = dict()",
"is_new = val not in self.val2nodes\nnode = LinkedListNode(val)\nself.nodes.append(node)\nself.node2index[node] = len(self.nodes) - 1\nif is_new:\n self.val2nodes[val] = node\n return True\nelse:\n existed_nodes = self.val2nodes[va... | <|body_start_0|>
self.val2nodes = dict()
self.nodes = list()
self.node2index = dict()
<|end_body_0|>
<|body_start_1|>
is_new = val not in self.val2nodes
node = LinkedListNode(val)
self.nodes.append(node)
self.node2index[node] = len(self.nodes) - 1
if is_n... | RandomizedCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedCollection:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool"""
... | stack_v2_sparse_classes_36k_train_005963 | 2,129 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool",
"name": "insert",
... | 4 | stack_v2_sparse_classes_30k_train_020811 | Implement the Python class `RandomizedCollection` described below.
Class description:
Implement the RandomizedCollection class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the collection. Returns true if the collection did no... | Implement the Python class `RandomizedCollection` described below.
Class description:
Implement the RandomizedCollection class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the collection. Returns true if the collection did no... | 44f422b75aa296cbb42d968ff843969af7bfa18a | <|skeleton|>
class RandomizedCollection:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomizedCollection:
def __init__(self):
"""Initialize your data structure here."""
self.val2nodes = dict()
self.nodes = list()
self.node2index = dict()
def insert(self, val):
"""Inserts a value to the collection. Returns true if the collection did not already con... | the_stack_v2_python_sparse | Data Structure/Hash Map/954/954_Jiuzhang_Su.py | liuhz0926/algorithm_practicing_progress | train | 0 | |
00e446368e3fc28af9c3cc14c670c47d0f932ca8 | [
"for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]",
"for i, n in enumerate(nums):\n remain = target - n\n if remain in nums[i + 1:]:\n return (nums.index(n), nums[i + 1:].index(remain) + (i + 1))",
"dic = {}\nfor i... | <|body_start_0|>
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
<|end_body_0|>
<|body_start_1|>
for i, n in enumerate(nums):
remain = target - n
if remain in nums[i + 1:]:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twoSum3(self, nums, targ... | stack_v2_sparse_classes_36k_train_005964 | 2,311 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum1",
"signature": "def twoSum1(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum2",
"signature": "def twoSum2(self, nums, target)"
... | 4 | stack_v2_sparse_classes_30k_train_013570 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List... | bea9d655338af9ce35c70927888930507bb6aae8 | <|skeleton|>
class Solution:
def twoSum1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twoSum3(self, nums, targ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
def twoSum2(self, nums, tar... | the_stack_v2_python_sparse | twoSum.py | lilly9117/Algorithm_study | train | 0 | |
9110bedc176564f7addd91e554ea7f9de00eae54 | [
"if config['lang'] != 'en':\n raise Exception('spaCy tokenizer is currently only allowed in English pipeline.')\ntry:\n import spacy\n from spacy.lang.en import English\nexcept ImportError:\n raise ImportError('spaCy 2.0+ is used but not installed on your machine. Go to https://spacy.io/usage for instal... | <|body_start_0|>
if config['lang'] != 'en':
raise Exception('spaCy tokenizer is currently only allowed in English pipeline.')
try:
import spacy
from spacy.lang.en import English
except ImportError:
raise ImportError('spaCy 2.0+ is used but not inst... | SpacyTokenizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpacyTokenizer:
def __init__(self, config):
"""Construct a spaCy-based tokenizer by loading the spaCy pipeline."""
<|body_0|>
def process(self, document):
"""Tokenize a document with the spaCy tokenizer and wrap the results into a Doc object."""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_005965 | 2,724 | permissive | [
{
"docstring": "Construct a spaCy-based tokenizer by loading the spaCy pipeline.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Tokenize a document with the spaCy tokenizer and wrap the results into a Doc object.",
"name": "process",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_004534 | Implement the Python class `SpacyTokenizer` described below.
Class description:
Implement the SpacyTokenizer class.
Method signatures and docstrings:
- def __init__(self, config): Construct a spaCy-based tokenizer by loading the spaCy pipeline.
- def process(self, document): Tokenize a document with the spaCy tokeniz... | Implement the Python class `SpacyTokenizer` described below.
Class description:
Implement the SpacyTokenizer class.
Method signatures and docstrings:
- def __init__(self, config): Construct a spaCy-based tokenizer by loading the spaCy pipeline.
- def process(self, document): Tokenize a document with the spaCy tokeniz... | c530c9af647d521262b56b717bcc38b0cfc5f1b8 | <|skeleton|>
class SpacyTokenizer:
def __init__(self, config):
"""Construct a spaCy-based tokenizer by loading the spaCy pipeline."""
<|body_0|>
def process(self, document):
"""Tokenize a document with the spaCy tokenizer and wrap the results into a Doc object."""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpacyTokenizer:
def __init__(self, config):
"""Construct a spaCy-based tokenizer by loading the spaCy pipeline."""
if config['lang'] != 'en':
raise Exception('spaCy tokenizer is currently only allowed in English pipeline.')
try:
import spacy
from spa... | the_stack_v2_python_sparse | stanza/pipeline/external/spacy.py | stanfordnlp/stanza | train | 4,281 | |
c7f1364164acc9325bd61009618116db5cda564a | [
"filters = self._block_args.input_filters * self._block_args.expand_ratio\ncid = itertools.count(0)\nget_conv_name = lambda: 'conv2d' + ('' if not next(cid) else '_' + str(next(cid) // 2))\nkernel_size = self._block_args.kernel_size\nif self._block_args.expand_ratio != 1:\n self._expand_conv = tf.keras.layers.Co... | <|body_start_0|>
filters = self._block_args.input_filters * self._block_args.expand_ratio
cid = itertools.count(0)
get_conv_name = lambda: 'conv2d' + ('' if not next(cid) else '_' + str(next(cid) // 2))
kernel_size = self._block_args.kernel_size
if self._block_args.expand_ratio !... | MBConv-like block without depthwise convolution and squeeze-and-excite. | MBConvBlockWithoutDepthwise | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MBConvBlockWithoutDepthwise:
"""MBConv-like block without depthwise convolution and squeeze-and-excite."""
def _build(self):
"""Builds block according to the arguments."""
<|body_0|>
def call(self, inputs, training, survival_prob=None):
"""Implementation of call(... | stack_v2_sparse_classes_36k_train_005966 | 28,094 | permissive | [
{
"docstring": "Builds block according to the arguments.",
"name": "_build",
"signature": "def _build(self)"
},
{
"docstring": "Implementation of call(). Args: inputs: the inputs tensor. training: boolean, whether the model is constructed for training. survival_prob: float, between 0 to 1, drop ... | 2 | stack_v2_sparse_classes_30k_train_013802 | Implement the Python class `MBConvBlockWithoutDepthwise` described below.
Class description:
MBConv-like block without depthwise convolution and squeeze-and-excite.
Method signatures and docstrings:
- def _build(self): Builds block according to the arguments.
- def call(self, inputs, training, survival_prob=None): Im... | Implement the Python class `MBConvBlockWithoutDepthwise` described below.
Class description:
MBConv-like block without depthwise convolution and squeeze-and-excite.
Method signatures and docstrings:
- def _build(self): Builds block according to the arguments.
- def call(self, inputs, training, survival_prob=None): Im... | c7392f2bab3165244d1c565b66409fa11fa82367 | <|skeleton|>
class MBConvBlockWithoutDepthwise:
"""MBConv-like block without depthwise convolution and squeeze-and-excite."""
def _build(self):
"""Builds block according to the arguments."""
<|body_0|>
def call(self, inputs, training, survival_prob=None):
"""Implementation of call(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MBConvBlockWithoutDepthwise:
"""MBConv-like block without depthwise convolution and squeeze-and-excite."""
def _build(self):
"""Builds block according to the arguments."""
filters = self._block_args.input_filters * self._block_args.expand_ratio
cid = itertools.count(0)
get... | the_stack_v2_python_sparse | efficientdet/backbone/efficientnet_model.py | google/automl | train | 6,415 |
e5aa7f3f364e0ae576c7d2d8980f7ea1c4881863 | [
"self.data_set_reader = data_set_reader\nself.param = param\nself.model_class = model_class\nself.predictor = None\nself.input_keys = []\nself.init_data_params()\nself.init_env()",
"model_path = self.param['inference_model_path']\nconfig = AnalysisConfig(model_path + '/' + 'model', model_path + '/' + 'params')\ni... | <|body_start_0|>
self.data_set_reader = data_set_reader
self.param = param
self.model_class = model_class
self.predictor = None
self.input_keys = []
self.init_data_params()
self.init_env()
<|end_body_0|>
<|body_start_1|>
model_path = self.param['inference... | Predictor: 模型预测 | Predictor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predictor:
"""Predictor: 模型预测"""
def __init__(self, param, data_set_reader, model_class):
"""1.解析input_data的结构 2.解析参数,构造predictor 3. 启动data_generator,开始预测 4.回掉预测结果到model中进行解析 :param param: 运行的基本参数设置 :param data_set_reader: 运行的基本参数设置 :param model_class: 使用的是哪个model"""
<|body_0... | stack_v2_sparse_classes_36k_train_005967 | 3,405 | permissive | [
{
"docstring": "1.解析input_data的结构 2.解析参数,构造predictor 3. 启动data_generator,开始预测 4.回掉预测结果到model中进行解析 :param param: 运行的基本参数设置 :param data_set_reader: 运行的基本参数设置 :param model_class: 使用的是哪个model",
"name": "__init__",
"signature": "def __init__(self, param, data_set_reader, model_class)"
},
{
"docstring... | 4 | stack_v2_sparse_classes_30k_train_002696 | Implement the Python class `Predictor` described below.
Class description:
Predictor: 模型预测
Method signatures and docstrings:
- def __init__(self, param, data_set_reader, model_class): 1.解析input_data的结构 2.解析参数,构造predictor 3. 启动data_generator,开始预测 4.回掉预测结果到model中进行解析 :param param: 运行的基本参数设置 :param data_set_reader: 运行的基... | Implement the Python class `Predictor` described below.
Class description:
Predictor: 模型预测
Method signatures and docstrings:
- def __init__(self, param, data_set_reader, model_class): 1.解析input_data的结构 2.解析参数,构造predictor 3. 启动data_generator,开始预测 4.回掉预测结果到model中进行解析 :param param: 运行的基本参数设置 :param data_set_reader: 运行的基... | e08f3cb7b9db4c837000316c791542580ba02624 | <|skeleton|>
class Predictor:
"""Predictor: 模型预测"""
def __init__(self, param, data_set_reader, model_class):
"""1.解析input_data的结构 2.解析参数,构造predictor 3. 启动data_generator,开始预测 4.回掉预测结果到model中进行解析 :param param: 运行的基本参数设置 :param data_set_reader: 运行的基本参数设置 :param model_class: 使用的是哪个model"""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Predictor:
"""Predictor: 模型预测"""
def __init__(self, param, data_set_reader, model_class):
"""1.解析input_data的结构 2.解析参数,构造predictor 3. 启动data_generator,开始预测 4.回掉预测结果到model中进行解析 :param param: 运行的基本参数设置 :param data_set_reader: 运行的基本参数设置 :param model_class: 使用的是哪个model"""
self.data_set_reader ... | the_stack_v2_python_sparse | NLP/DuSQL-Baseline/text2sql/framework/predictor.py | ajayvbabu/Research | train | 0 |
474494ce13b5e3f8aa507558a741d146df6d4982 | [
"urls = super().get_urls()\nnew_urls = [path('upload-csv/', self.upload_csv), path('update_elastic/', ElasticActions.update_elastic), path('export-elastic/', ElasticActions.export_to_elastic)]\nreturn new_urls + urls",
"if request.method == 'POST':\n csv_file = request.FILES['importer_un_fichier']\n if not ... | <|body_start_0|>
urls = super().get_urls()
new_urls = [path('upload-csv/', self.upload_csv), path('update_elastic/', ElasticActions.update_elastic), path('export-elastic/', ElasticActions.export_to_elastic)]
return new_urls + urls
<|end_body_0|>
<|body_start_1|>
if request.method == 'PO... | Modèle de l'administration des laboratoires | LaboratoryAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LaboratoryAdmin:
"""Modèle de l'administration des laboratoires"""
def get_urls(self):
"""Initialise les urls du modèle LaboratoryAdmin"""
<|body_0|>
def upload_csv(request):
"""Permet de charger un fichier CSV dans la base de données du modèle Laboratory"""
... | stack_v2_sparse_classes_36k_train_005968 | 12,279 | no_license | [
{
"docstring": "Initialise les urls du modèle LaboratoryAdmin",
"name": "get_urls",
"signature": "def get_urls(self)"
},
{
"docstring": "Permet de charger un fichier CSV dans la base de données du modèle Laboratory",
"name": "upload_csv",
"signature": "def upload_csv(request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004111 | Implement the Python class `LaboratoryAdmin` described below.
Class description:
Modèle de l'administration des laboratoires
Method signatures and docstrings:
- def get_urls(self): Initialise les urls du modèle LaboratoryAdmin
- def upload_csv(request): Permet de charger un fichier CSV dans la base de données du modè... | Implement the Python class `LaboratoryAdmin` described below.
Class description:
Modèle de l'administration des laboratoires
Method signatures and docstrings:
- def get_urls(self): Initialise les urls du modèle LaboratoryAdmin
- def upload_csv(request): Permet de charger un fichier CSV dans la base de données du modè... | 0471d2de17597d97f3209099aff3edc72d615fa2 | <|skeleton|>
class LaboratoryAdmin:
"""Modèle de l'administration des laboratoires"""
def get_urls(self):
"""Initialise les urls du modèle LaboratoryAdmin"""
<|body_0|>
def upload_csv(request):
"""Permet de charger un fichier CSV dans la base de données du modèle Laboratory"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LaboratoryAdmin:
"""Modèle de l'administration des laboratoires"""
def get_urls(self):
"""Initialise les urls du modèle LaboratoryAdmin"""
urls = super().get_urls()
new_urls = [path('upload-csv/', self.upload_csv), path('update_elastic/', ElasticActions.update_elastic), path('expo... | the_stack_v2_python_sparse | elasticHal/admin.py | Patent2net/SoVisu | train | 1 |
bb4ff44961b1f4f7f8c0acd86a4c99f12f4b84c9 | [
"if isinstance(exc, NotImplementedError):\n return self._make_error_response(400, str(exc))\nreturn super().handle_exception(exc)",
"course_key = CourseKey.from_string(course_id)\nif not has_studio_write_access(request.user, course_key):\n self.permission_denied(request)\ncourse_module = modulestore().get_c... | <|body_start_0|>
if isinstance(exc, NotImplementedError):
return self._make_error_response(400, str(exc))
return super().handle_exception(exc)
<|end_body_0|>
<|body_start_1|>
course_key = CourseKey.from_string(course_id)
if not has_studio_write_access(request.user, course_ke... | API view for reordering course tabs. | CourseTabReorderView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseTabReorderView:
"""API view for reordering course tabs."""
def handle_exception(self, exc: Exception) -> Response:
"""Handle NotImplementedError and return a proper response for it."""
<|body_0|>
def post(self, request: Request, course_id: str) -> Response:
... | stack_v2_sparse_classes_36k_train_005969 | 8,341 | permissive | [
{
"docstring": "Handle NotImplementedError and return a proper response for it.",
"name": "handle_exception",
"signature": "def handle_exception(self, exc: Exception) -> Response"
},
{
"docstring": "Reorder tabs in a course. **Example Requests** Move course tabs: POST /api/contentstore/v0/tabs/{... | 2 | null | Implement the Python class `CourseTabReorderView` described below.
Class description:
API view for reordering course tabs.
Method signatures and docstrings:
- def handle_exception(self, exc: Exception) -> Response: Handle NotImplementedError and return a proper response for it.
- def post(self, request: Request, cour... | Implement the Python class `CourseTabReorderView` described below.
Class description:
API view for reordering course tabs.
Method signatures and docstrings:
- def handle_exception(self, exc: Exception) -> Response: Handle NotImplementedError and return a proper response for it.
- def post(self, request: Request, cour... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class CourseTabReorderView:
"""API view for reordering course tabs."""
def handle_exception(self, exc: Exception) -> Response:
"""Handle NotImplementedError and return a proper response for it."""
<|body_0|>
def post(self, request: Request, course_id: str) -> Response:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CourseTabReorderView:
"""API view for reordering course tabs."""
def handle_exception(self, exc: Exception) -> Response:
"""Handle NotImplementedError and return a proper response for it."""
if isinstance(exc, NotImplementedError):
return self._make_error_response(400, str(exc... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/cms/djangoapps/contentstore/rest_api/v0/views/tabs.py | luque/better-ways-of-thinking-about-software | train | 3 |
ac9e075472a9b366f6ed142ec592302e1f0ac1ec | [
"logging.info('Creating ContinuousTrainRunner ...')\nsuper().__init__(base_dir, create_agent_fn, create_environment_fn)\nself._agent.eval_mode = False",
"statistics = iteration_statistics.IterationStatistics()\nnum_episodes_train, average_reward_train, average_steps_per_second = self._run_train_phase(statistics)\... | <|body_start_0|>
logging.info('Creating ContinuousTrainRunner ...')
super().__init__(base_dir, create_agent_fn, create_environment_fn)
self._agent.eval_mode = False
<|end_body_0|>
<|body_start_1|>
statistics = iteration_statistics.IterationStatistics()
num_episodes_train, averag... | Object that handles running experiments. This is mostly the same as discrete_domains.TrainRunner, but is written solely for JAX/Flax agents. | ContinuousTrainRunner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContinuousTrainRunner:
"""Object that handles running experiments. This is mostly the same as discrete_domains.TrainRunner, but is written solely for JAX/Flax agents."""
def __init__(self, base_dir, create_agent_fn, create_environment_fn=gym_lib.create_gym_environment):
"""Initialize... | stack_v2_sparse_classes_36k_train_005970 | 11,511 | permissive | [
{
"docstring": "Initialize the TrainRunner object in charge of running a full experiment. Args: base_dir: str, the base directory to host all required sub-directories. create_agent_fn: A function that takes as args a Tensorflow session and an environment, and returns an agent. create_environment_fn: A function ... | 3 | stack_v2_sparse_classes_30k_train_001643 | Implement the Python class `ContinuousTrainRunner` described below.
Class description:
Object that handles running experiments. This is mostly the same as discrete_domains.TrainRunner, but is written solely for JAX/Flax agents.
Method signatures and docstrings:
- def __init__(self, base_dir, create_agent_fn, create_e... | Implement the Python class `ContinuousTrainRunner` described below.
Class description:
Object that handles running experiments. This is mostly the same as discrete_domains.TrainRunner, but is written solely for JAX/Flax agents.
Method signatures and docstrings:
- def __init__(self, base_dir, create_agent_fn, create_e... | ed92c57bd547db68d63aabee383d4c55756a6a0f | <|skeleton|>
class ContinuousTrainRunner:
"""Object that handles running experiments. This is mostly the same as discrete_domains.TrainRunner, but is written solely for JAX/Flax agents."""
def __init__(self, base_dir, create_agent_fn, create_environment_fn=gym_lib.create_gym_environment):
"""Initialize... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContinuousTrainRunner:
"""Object that handles running experiments. This is mostly the same as discrete_domains.TrainRunner, but is written solely for JAX/Flax agents."""
def __init__(self, base_dir, create_agent_fn, create_environment_fn=gym_lib.create_gym_environment):
"""Initialize the TrainRun... | the_stack_v2_python_sparse | dopamine/continuous_domains/run_experiment.py | HOZHENWAI/dopamine | train | 1 |
1b77fe056340d4361686e9ad1a45bf576492f71f | [
"self.c2s = {1: 'Thousand', 2: 'Million', 3: 'Billion'}\nself.n2s = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'}\nself.t2s = {10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 1... | <|body_start_0|>
self.c2s = {1: 'Thousand', 2: 'Million', 3: 'Billion'}
self.n2s = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'}
self.t2s = {10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', ... | 总体思路是,按英文数字表示习惯,每3位,变换一次表示后缀,Billion,Million,Thousand 3位以内,可以共用一个规则表示,用 lower 函数来单独处理 本题是Hard的主要原因是 英文数字表达的细节容易出错, 此外 1,000,000 - > one million, 程序容易输出 one million thousand 这就需要在每隔3位 添加 billion million 的时候,判断 高位部分时候如果为空, 则不添加多余的 thousand | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""总体思路是,按英文数字表示习惯,每3位,变换一次表示后缀,Billion,Million,Thousand 3位以内,可以共用一个规则表示,用 lower 函数来单独处理 本题是Hard的主要原因是 英文数字表达的细节容易出错, 此外 1,000,000 - > one million, 程序容易输出 one million thousand 这就需要在每隔3位 添加 billion million 的时候,判断 高位部分时候如果为空, 则不添加多余的 thousand"""
def __init__(self) -> None:
""... | stack_v2_sparse_classes_36k_train_005971 | 3,864 | permissive | [
{
"docstring": "初始化不同位数的数字英文单词映射关系",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "每隔3位,分区而治, 1,3位以内转换英文, 2,3位之间添加后缀 最后把结果合并即可",
"name": "numberToWords",
"signature": "def numberToWords(self, num: int) -> str"
},
{
"docstring": "3位以内的数字 -> 英文 转换... | 3 | null | Implement the Python class `Solution` described below.
Class description:
总体思路是,按英文数字表示习惯,每3位,变换一次表示后缀,Billion,Million,Thousand 3位以内,可以共用一个规则表示,用 lower 函数来单独处理 本题是Hard的主要原因是 英文数字表达的细节容易出错, 此外 1,000,000 - > one million, 程序容易输出 one million thousand 这就需要在每隔3位 添加 billion million 的时候,判断 高位部分时候如果为空, 则不添加多余的 thousand
Method... | Implement the Python class `Solution` described below.
Class description:
总体思路是,按英文数字表示习惯,每3位,变换一次表示后缀,Billion,Million,Thousand 3位以内,可以共用一个规则表示,用 lower 函数来单独处理 本题是Hard的主要原因是 英文数字表达的细节容易出错, 此外 1,000,000 - > one million, 程序容易输出 one million thousand 这就需要在每隔3位 添加 billion million 的时候,判断 高位部分时候如果为空, 则不添加多余的 thousand
Method... | 65549f72c565d9f11641c86d6cef9c7988805817 | <|skeleton|>
class Solution:
"""总体思路是,按英文数字表示习惯,每3位,变换一次表示后缀,Billion,Million,Thousand 3位以内,可以共用一个规则表示,用 lower 函数来单独处理 本题是Hard的主要原因是 英文数字表达的细节容易出错, 此外 1,000,000 - > one million, 程序容易输出 one million thousand 这就需要在每隔3位 添加 billion million 的时候,判断 高位部分时候如果为空, 则不添加多余的 thousand"""
def __init__(self) -> None:
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""总体思路是,按英文数字表示习惯,每3位,变换一次表示后缀,Billion,Million,Thousand 3位以内,可以共用一个规则表示,用 lower 函数来单独处理 本题是Hard的主要原因是 英文数字表达的细节容易出错, 此外 1,000,000 - > one million, 程序容易输出 one million thousand 这就需要在每隔3位 添加 billion million 的时候,判断 高位部分时候如果为空, 则不添加多余的 thousand"""
def __init__(self) -> None:
"""初始化不同位数的数字英文... | the_stack_v2_python_sparse | src/273.integer-to-english-words.py | wisesky/LeetCode-Practice | train | 0 |
64aa211716d1ff8aa7a7f77a0930a1b04c1f87e2 | [
"if not root:\n return ''\nif root.left:\n if root.right:\n return '{}({})({})'.format(root.val, self.serialize(root.left), self.serialize(root.right))\n else:\n return '{}({})'.format(root.val, self.serialize(root.left))\nelif root.right:\n return '{}()({})'.format(root.val, self.serializ... | <|body_start_0|>
if not root:
return ''
if root.left:
if root.right:
return '{}({})({})'.format(root.val, self.serialize(root.left), self.serialize(root.right))
else:
return '{}({})'.format(root.val, self.serialize(root.left))
e... | 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_005972 | 2,097 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 34a78e06d493e61b21d4442747e9102abf9b319b | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
if root.left:
if root.right:
return '{}({})({})'.format(root.val, self.serialize(root.left), self.serialize(root.ri... | the_stack_v2_python_sparse | 449_Serialize_and_Deserialize_BST.py | sunnyyeti/Leetcode-solutions | train | 0 | |
79b5d3b7c3c78b84b2f5a224d186146150820a9d | [
"super().__init__()\nself.every_n_steps = every_n_steps\nself.nrow = nrow\nself.padding = padding\nself.normalize = normalize\nself.norm_range = norm_range\nself.scale_each = scale_each\nself.pad_value = pad_value\nself.multi_optim = multi_optim\nself.use_wandb = use_wandb",
"if batch_idx % self.every_n_steps == ... | <|body_start_0|>
super().__init__()
self.every_n_steps = every_n_steps
self.nrow = nrow
self.padding = padding
self.normalize = normalize
self.norm_range = norm_range
self.scale_each = scale_each
self.pad_value = pad_value
self.multi_optim = multi_... | ReconstructedImageLogger | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReconstructedImageLogger:
def __init__(self, every_n_steps: int=1000, nrow: int=8, padding: int=2, normalize: bool=True, norm_range: Optional[Tuple[int, int]]=None, scale_each: bool=False, pad_value: int=0, use_wandb: bool=False, multi_optim=False) -> None:
"""Args: num_samples: Number o... | stack_v2_sparse_classes_36k_train_005973 | 6,454 | permissive | [
{
"docstring": "Args: num_samples: Number of images displayed in the grid. Default: ``3``. nrow: Number of images displayed in each row of the grid. The final grid size is ``(B / nrow, nrow)``. Default: ``8``. padding: Amount of padding. Default: ``2``. normalize: If ``True``, shift the image to the range (0, 1... | 4 | null | Implement the Python class `ReconstructedImageLogger` described below.
Class description:
Implement the ReconstructedImageLogger class.
Method signatures and docstrings:
- def __init__(self, every_n_steps: int=1000, nrow: int=8, padding: int=2, normalize: bool=True, norm_range: Optional[Tuple[int, int]]=None, scale_e... | Implement the Python class `ReconstructedImageLogger` described below.
Class description:
Implement the ReconstructedImageLogger class.
Method signatures and docstrings:
- def __init__(self, every_n_steps: int=1000, nrow: int=8, padding: int=2, normalize: bool=True, norm_range: Optional[Tuple[int, int]]=None, scale_e... | 9d643e88946fc4a24f2d4d073c08b05ea693f4c5 | <|skeleton|>
class ReconstructedImageLogger:
def __init__(self, every_n_steps: int=1000, nrow: int=8, padding: int=2, normalize: bool=True, norm_range: Optional[Tuple[int, int]]=None, scale_each: bool=False, pad_value: int=0, use_wandb: bool=False, multi_optim=False) -> None:
"""Args: num_samples: Number o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReconstructedImageLogger:
def __init__(self, every_n_steps: int=1000, nrow: int=8, padding: int=2, normalize: bool=True, norm_range: Optional[Tuple[int, int]]=None, scale_each: bool=False, pad_value: int=0, use_wandb: bool=False, multi_optim=False) -> None:
"""Args: num_samples: Number of images displ... | the_stack_v2_python_sparse | multimodal/Language-Image_Pre-Training/L-Verse/pytorch/latent_verse/callbacks.py | Deep-Spark/DeepSparkHub | train | 7 | |
12f60eeb4605a202b9daa2bbe3dcda18e554a9ad | [
"next = self.partial_match_table(p)\ni, j = (0, 0)\ntL = len(t)\npL = len(p)\nwhile i < tL and j < pL:\n if j == -1 or t[i] == p[j]:\n i += 1\n j += 1\n else:\n j = next[j]\nif j == pL:\n return i - j\nelse:\n return -1",
"m = len(pattern)\nnext = [-1] * m\nk = -1\nj = 0\nwhile j ... | <|body_start_0|>
next = self.partial_match_table(p)
i, j = (0, 0)
tL = len(t)
pL = len(p)
while i < tL and j < pL:
if j == -1 or t[i] == p[j]:
i += 1
j += 1
else:
j = next[j]
if j == pL:
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def strStr(self, t, p):
""":type haystack: str :type needle: str :rtype: int"""
<|body_0|>
def partial_match_table(self, pattern):
"""Compute the "next" table corresponding to pattern, for use in the Knuth-Morris-Pratt string search algorithm."""
<|... | stack_v2_sparse_classes_36k_train_005974 | 1,257 | no_license | [
{
"docstring": ":type haystack: str :type needle: str :rtype: int",
"name": "strStr",
"signature": "def strStr(self, t, p)"
},
{
"docstring": "Compute the \"next\" table corresponding to pattern, for use in the Knuth-Morris-Pratt string search algorithm.",
"name": "partial_match_table",
... | 2 | stack_v2_sparse_classes_30k_train_014509 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def strStr(self, t, p): :type haystack: str :type needle: str :rtype: int
- def partial_match_table(self, pattern): Compute the "next" table corresponding to pattern, for use in ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def strStr(self, t, p): :type haystack: str :type needle: str :rtype: int
- def partial_match_table(self, pattern): Compute the "next" table corresponding to pattern, for use in ... | 4aa3a3a0da8b911e140446352debb9b567b6d78b | <|skeleton|>
class Solution:
def strStr(self, t, p):
""":type haystack: str :type needle: str :rtype: int"""
<|body_0|>
def partial_match_table(self, pattern):
"""Compute the "next" table corresponding to pattern, for use in the Knuth-Morris-Pratt string search algorithm."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def strStr(self, t, p):
""":type haystack: str :type needle: str :rtype: int"""
next = self.partial_match_table(p)
i, j = (0, 0)
tL = len(t)
pL = len(p)
while i < tL and j < pL:
if j == -1 or t[i] == p[j]:
i += 1
... | the_stack_v2_python_sparse | implement_strStr_28.py | adiggo/leetcode_py | train | 0 | |
35cc0513731c42f2089428caa367fd7ad55bb112 | [
"assert 0 <= x <= 268435455\nbuffer = b''\nwhile 1:\n digit = x % 128\n x //= 128\n if x > 0:\n digit |= 128\n if sys.version_info[0] >= 3:\n buffer += bytes([digit])\n else:\n buffer += bytes(chr(digit))\n if x == 0:\n break\nreturn buffer",
"multiplier = 1\nvalue = ... | <|body_start_0|>
assert 0 <= x <= 268435455
buffer = b''
while 1:
digit = x % 128
x //= 128
if x > 0:
digit |= 128
if sys.version_info[0] >= 3:
buffer += bytes([digit])
else:
buffer += byt... | MQTT variable byte integer helper class. Used in several places in MQTT v5.0 properties. | VariableByteIntegers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VariableByteIntegers:
"""MQTT variable byte integer helper class. Used in several places in MQTT v5.0 properties."""
def encode(x):
"""Convert an integer 0 <= x <= 268435455 into multi-byte format. Returns the buffer convered from the integer."""
<|body_0|>
def decode(bu... | stack_v2_sparse_classes_36k_train_005975 | 16,499 | permissive | [
{
"docstring": "Convert an integer 0 <= x <= 268435455 into multi-byte format. Returns the buffer convered from the integer.",
"name": "encode",
"signature": "def encode(x)"
},
{
"docstring": "Get the value of a multi-byte integer from a buffer Return the value, and the number of bytes used. [MQ... | 2 | stack_v2_sparse_classes_30k_train_015299 | Implement the Python class `VariableByteIntegers` described below.
Class description:
MQTT variable byte integer helper class. Used in several places in MQTT v5.0 properties.
Method signatures and docstrings:
- def encode(x): Convert an integer 0 <= x <= 268435455 into multi-byte format. Returns the buffer convered f... | Implement the Python class `VariableByteIntegers` described below.
Class description:
MQTT variable byte integer helper class. Used in several places in MQTT v5.0 properties.
Method signatures and docstrings:
- def encode(x): Convert an integer 0 <= x <= 268435455 into multi-byte format. Returns the buffer convered f... | d031aab82e3fa5ce7cf57b257fef8c9a4c63d71e | <|skeleton|>
class VariableByteIntegers:
"""MQTT variable byte integer helper class. Used in several places in MQTT v5.0 properties."""
def encode(x):
"""Convert an integer 0 <= x <= 268435455 into multi-byte format. Returns the buffer convered from the integer."""
<|body_0|>
def decode(bu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VariableByteIntegers:
"""MQTT variable byte integer helper class. Used in several places in MQTT v5.0 properties."""
def encode(x):
"""Convert an integer 0 <= x <= 268435455 into multi-byte format. Returns the buffer convered from the integer."""
assert 0 <= x <= 268435455
buffer ... | the_stack_v2_python_sparse | venv/lib/python3.9/site-packages/paho/mqtt/properties.py | CiscoDevNet/meraki-code | train | 67 |
d2fb199ca9b7a3023a6745bb13613567a408c2f6 | [
"self.thresholds = np.array([276, 277], dtype=np.float32)\nself.rain_name = 'probability_of_falling_rain_level_above_surface'\nself.snow_name = 'probability_of_falling_snow_level_below_surface'\nrain_prob = np.array([[[0.5, 0.1, 1.0], [0.0, 0.2, 0.5], [0.1, 0.1, 0.3]], [[0.5, 0.1, 1.0], [0.0, 0.2, 0.5], [0.1, 0.1, ... | <|body_start_0|>
self.thresholds = np.array([276, 277], dtype=np.float32)
self.rain_name = 'probability_of_falling_rain_level_above_surface'
self.snow_name = 'probability_of_falling_snow_level_below_surface'
rain_prob = np.array([[[0.5, 0.1, 1.0], [0.0, 0.2, 0.5], [0.1, 0.1, 0.3]], [[0.5... | Tests the calculate sleet probability function. | Test_calculate_sleet_probability | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_calculate_sleet_probability:
"""Tests the calculate sleet probability function."""
def setUp(self):
"""Create cubes to input into the function."""
<|body_0|>
def test_basic_calculation(self):
"""Test the basic sleet calculation works."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_005976 | 5,635 | permissive | [
{
"docstring": "Create cubes to input into the function.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the basic sleet calculation works.",
"name": "test_basic_calculation",
"signature": "def test_basic_calculation(self)"
},
{
"docstring": "Test the ba... | 5 | stack_v2_sparse_classes_30k_train_020341 | Implement the Python class `Test_calculate_sleet_probability` described below.
Class description:
Tests the calculate sleet probability function.
Method signatures and docstrings:
- def setUp(self): Create cubes to input into the function.
- def test_basic_calculation(self): Test the basic sleet calculation works.
- ... | Implement the Python class `Test_calculate_sleet_probability` described below.
Class description:
Tests the calculate sleet probability function.
Method signatures and docstrings:
- def setUp(self): Create cubes to input into the function.
- def test_basic_calculation(self): Test the basic sleet calculation works.
- ... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_calculate_sleet_probability:
"""Tests the calculate sleet probability function."""
def setUp(self):
"""Create cubes to input into the function."""
<|body_0|>
def test_basic_calculation(self):
"""Test the basic sleet calculation works."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_calculate_sleet_probability:
"""Tests the calculate sleet probability function."""
def setUp(self):
"""Create cubes to input into the function."""
self.thresholds = np.array([276, 277], dtype=np.float32)
self.rain_name = 'probability_of_falling_rain_level_above_surface'
... | the_stack_v2_python_sparse | improver_tests/precipitation_type/calculate_sleet_prob/test_calculate_sleet_probability.py | metoppv/improver | train | 101 |
631ef4f637a0375fe349a43dd9eeb7d54966e239 | [
"super().__init__()\nself.cost_class = cost_class\nself.cost_bbox = cost_bbox\nself.cost_giou = cost_giou\nself.focal_loss_alpha = focal_loss_alpha\nself.focal_loss_gamma = focal_loss_gamma\nassert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, 'all costs cant be 0'",
"bs, num_queries = outputs['pred_logits... | <|body_start_0|>
super().__init__()
self.cost_class = cost_class
self.cost_bbox = cost_bbox
self.cost_giou = cost_giou
self.focal_loss_alpha = focal_loss_alpha
self.focal_loss_gamma = focal_loss_gamma
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, 'al... | This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are un-matched (... | HungarianMatcher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HungarianMatcher:
"""This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best pr... | stack_v2_sparse_classes_36k_train_005977 | 17,112 | permissive | [
{
"docstring": "Creates the matcher Params: cost_class: This is the relative weight of the classification error in the matching cost cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost cost_giou: This is the relative weight of the giou loss of the bounding... | 2 | null | Implement the Python class `HungarianMatcher` described below.
Class description:
This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case,... | Implement the Python class `HungarianMatcher` described below.
Class description:
This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case,... | bd83b98342b0a6bc8d8dcd5936233aeda1e32167 | <|skeleton|>
class HungarianMatcher:
"""This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HungarianMatcher:
"""This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, wh... | the_stack_v2_python_sparse | ppdet/modeling/losses/sparsercnn_loss.py | PaddlePaddle/PaddleDetection | train | 12,523 |
86d70de6dac194bcb91ffd5bbbcd9a2ece6e1b29 | [
"super(CombinedCNNSpecialists, self).__init__()\nstride = 1\nmax_s = 2\nself.conv = nn.Sequential(nn.Conv2d(n_channels, 64, kernel_size=(3, 3), stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(kernel_size=(3, 3), stride=2, padding=1), nn.Conv2d(64, 128, kernel_size=(3, 3), stride=1, padding=1), nn.... | <|body_start_0|>
super(CombinedCNNSpecialists, self).__init__()
stride = 1
max_s = 2
self.conv = nn.Sequential(nn.Conv2d(n_channels, 64, kernel_size=(3, 3), stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(kernel_size=(3, 3), stride=2, padding=1), nn.Conv2d(64, 128, kern... | This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward. | CombinedCNNSpecialists | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CombinedCNNSpecialists:
"""This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward."""
def __init__(self, n_channels, n_inputs):
"""Initializes MLP object. Args: n_input... | stack_v2_sparse_classes_36k_train_005978 | 6,082 | no_license | [
{
"docstring": "Initializes MLP object. Args: n_inputs: number of inputs. n_hidden: list of ints, specifies the number of units in each linear layer. If the list is empty, the MLP will not have any linear layers, and the model will simply perform a multinomial logistic regression. n_classes: number of classes o... | 2 | stack_v2_sparse_classes_30k_train_016784 | Implement the Python class `CombinedCNNSpecialists` described below.
Class description:
This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward.
Method signatures and docstrings:
- def __init__(self, n_c... | Implement the Python class `CombinedCNNSpecialists` described below.
Class description:
This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward.
Method signatures and docstrings:
- def __init__(self, n_c... | b060caa315f0c066410da9580e64d6db0222f2a8 | <|skeleton|>
class CombinedCNNSpecialists:
"""This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward."""
def __init__(self, n_channels, n_inputs):
"""Initializes MLP object. Args: n_input... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CombinedCNNSpecialists:
"""This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward."""
def __init__(self, n_channels, n_inputs):
"""Initializes MLP object. Args: n_inputs: number of ... | the_stack_v2_python_sparse | STL-10/combined_shared_cnn_specialists/shared_cnn.py | VCharatsidis/Unsupervised-Clustering | train | 1 |
2f6452cdebc8f387d5b83d08d4498413ec0b4d44 | [
"self.reqparser = reqparse.RequestParser()\nself.reqparser.add_argument('name', required=False, store_missing=False, type=str, location=['form', 'json'])\nself.reqparser.add_argument('id', required=False, store_missing=False, type=str, location=['form', 'json'])\nself.reqparser.add_argument('theme_id', required=Fal... | <|body_start_0|>
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('name', required=False, store_missing=False, type=str, location=['form', 'json'])
self.reqparser.add_argument('id', required=False, store_missing=False, type=str, location=['form', 'json'])
self.reqpar... | Delete an existing SubTheme. | DeleteSubTheme | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteSubTheme:
"""Delete an existing SubTheme."""
def __init__(self) -> None:
"""Set required arguments for POST request."""
<|body_0|>
def post(self) -> ({str: str}, HTTPStatus):
"""Delete an existing SubTheme. :param name: the name of SubTheme. :param id: id o... | stack_v2_sparse_classes_36k_train_005979 | 2,268 | permissive | [
{
"docstring": "Set required arguments for POST request.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Delete an existing SubTheme. :param name: the name of SubTheme. :param id: id of SubTheme. :param theme_id: Parent theme id. :type name: str :type id: str :... | 2 | null | Implement the Python class `DeleteSubTheme` described below.
Class description:
Delete an existing SubTheme.
Method signatures and docstrings:
- def __init__(self) -> None: Set required arguments for POST request.
- def post(self) -> ({str: str}, HTTPStatus): Delete an existing SubTheme. :param name: the name of SubT... | Implement the Python class `DeleteSubTheme` described below.
Class description:
Delete an existing SubTheme.
Method signatures and docstrings:
- def __init__(self) -> None: Set required arguments for POST request.
- def post(self) -> ({str: str}, HTTPStatus): Delete an existing SubTheme. :param name: the name of SubT... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class DeleteSubTheme:
"""Delete an existing SubTheme."""
def __init__(self) -> None:
"""Set required arguments for POST request."""
<|body_0|>
def post(self) -> ({str: str}, HTTPStatus):
"""Delete an existing SubTheme. :param name: the name of SubTheme. :param id: id o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteSubTheme:
"""Delete an existing SubTheme."""
def __init__(self) -> None:
"""Set required arguments for POST request."""
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('name', required=False, store_missing=False, type=str, location=['form', 'json'])
... | the_stack_v2_python_sparse | Analytics/resources/themes/delete_subtheme.py | thanosbnt/SharingCitiesDashboard | train | 0 |
fad46b55b2ec382b86c2284df43e34036489e2af | [
"maxarea = 0\ndp = [[0] * len(matrix[0]) for _ in range(len(matrix))]\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == '0':\n continue\n width = dp[i][j] = dp[i][j - 1] + 1 if j else 1\n for k in range(i, -1, -1):\n width = min(width,... | <|body_start_0|>
maxarea = 0
dp = [[0] * len(matrix[0]) for _ in range(len(matrix))]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == '0':
continue
width = dp[i][j] = dp[i][j - 1] + 1 if j else 1
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalRectangle_dp(self, matrix: List[List[str]]) -> int:
"""方法二:动态规划 - 使用柱状图的优化暴力方法 时间复杂度 : O(N^2M) 空间复杂度 : O(NM) :param matrix: :return:"""
<|body_0|>
def maximalRectangle(self, matrix: List[List[str]]) -> int:
"""方法三:使用柱状图 - 栈 时间复杂度 : O(NM)。对每一行运行 力... | stack_v2_sparse_classes_36k_train_005980 | 3,366 | permissive | [
{
"docstring": "方法二:动态规划 - 使用柱状图的优化暴力方法 时间复杂度 : O(N^2M) 空间复杂度 : O(NM) :param matrix: :return:",
"name": "maximalRectangle_dp",
"signature": "def maximalRectangle_dp(self, matrix: List[List[str]]) -> int"
},
{
"docstring": "方法三:使用柱状图 - 栈 时间复杂度 : O(NM)。对每一行运行 力扣 84 需要 M (每行长度) 时间,运行了 N 次,共计 O(NM)。... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle_dp(self, matrix: List[List[str]]) -> int: 方法二:动态规划 - 使用柱状图的优化暴力方法 时间复杂度 : O(N^2M) 空间复杂度 : O(NM) :param matrix: :return:
- def maximalRectangle(self, matrix: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle_dp(self, matrix: List[List[str]]) -> int: 方法二:动态规划 - 使用柱状图的优化暴力方法 时间复杂度 : O(N^2M) 空间复杂度 : O(NM) :param matrix: :return:
- def maximalRectangle(self, matrix: ... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def maximalRectangle_dp(self, matrix: List[List[str]]) -> int:
"""方法二:动态规划 - 使用柱状图的优化暴力方法 时间复杂度 : O(N^2M) 空间复杂度 : O(NM) :param matrix: :return:"""
<|body_0|>
def maximalRectangle(self, matrix: List[List[str]]) -> int:
"""方法三:使用柱状图 - 栈 时间复杂度 : O(NM)。对每一行运行 力... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximalRectangle_dp(self, matrix: List[List[str]]) -> int:
"""方法二:动态规划 - 使用柱状图的优化暴力方法 时间复杂度 : O(N^2M) 空间复杂度 : O(NM) :param matrix: :return:"""
maxarea = 0
dp = [[0] * len(matrix[0]) for _ in range(len(matrix))]
for i in range(len(matrix)):
for j in ran... | the_stack_v2_python_sparse | LeetCode 热题 HOT 100/maximalRectangle.py | MaoningGuan/LeetCode | train | 3 | |
d4fb1597af1c32edc716f2cf41946f6041bd86d4 | [
"Parametre.__init__(self, 'retirer', 'down')\nself.aide_courte = 'amène le pavillon'\nself.aide_longue = 'Cette commande permet de baisser le pavillon actuel du navire. Elle ne prend aucun argument. Le pavillon sera amené par le personnage entrant la commande.'",
"salle = personnage.salle\nif not hasattr(salle, '... | <|body_start_0|>
Parametre.__init__(self, 'retirer', 'down')
self.aide_courte = 'amène le pavillon'
self.aide_longue = 'Cette commande permet de baisser le pavillon actuel du navire. Elle ne prend aucun argument. Le pavillon sera amené par le personnage entrant la commande.'
<|end_body_0|>
<|bo... | Commande 'pavillon retirer'. | PrmRetirer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmRetirer:
"""Commande 'pavillon retirer'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametr... | stack_v2_sparse_classes_36k_train_005981 | 3,070 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmRetirer` described below.
Class description:
Commande 'pavillon retirer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmRetirer` described below.
Class description:
Commande 'pavillon retirer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmRetirer:
"""Commande 'pavi... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmRetirer:
"""Commande 'pavillon retirer'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmRetirer:
"""Commande 'pavillon retirer'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'retirer', 'down')
self.aide_courte = 'amène le pavillon'
self.aide_longue = 'Cette commande permet de baisser le pavillon actuel du navire. Elle ne ... | the_stack_v2_python_sparse | src/secondaires/navigation/commandes/pavillon/retirer.py | vincent-lg/tsunami | train | 5 |
96c474b23cda98e5d031bf4795b97e86b050e0ee | [
"group_number = int(self.ui.lineEdit_group_number.text())\nself.protocol.create_sequence(group_number)\nself.ui.tableWidget_tasks.setRowCount(len(self.protocol.trial_list))\nfor i in range(len(self.protocol.trial_list)):\n self.ui.tableWidget_tasks.setItem(i, 0, QTableWidgetItem(self.protocol.trial_list[i].name)... | <|body_start_0|>
group_number = int(self.ui.lineEdit_group_number.text())
self.protocol.create_sequence(group_number)
self.ui.tableWidget_tasks.setRowCount(len(self.protocol.trial_list))
for i in range(len(self.protocol.trial_list)):
self.ui.tableWidget_tasks.setItem(i, 0, QT... | SequenceManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceManager:
def onClicked_button_create_sequence(self):
"""Event listener for create sequence button in Experimental Protocol tab. The listed tasks will be iterated 'group number' times in the Task table"""
<|body_0|>
def onClicked_button_randomize(self):
"""Eve... | stack_v2_sparse_classes_36k_train_005982 | 2,026 | no_license | [
{
"docstring": "Event listener for create sequence button in Experimental Protocol tab. The listed tasks will be iterated 'group number' times in the Task table",
"name": "onClicked_button_create_sequence",
"signature": "def onClicked_button_create_sequence(self)"
},
{
"docstring": "Event listen... | 2 | stack_v2_sparse_classes_30k_train_013646 | Implement the Python class `SequenceManager` described below.
Class description:
Implement the SequenceManager class.
Method signatures and docstrings:
- def onClicked_button_create_sequence(self): Event listener for create sequence button in Experimental Protocol tab. The listed tasks will be iterated 'group number'... | Implement the Python class `SequenceManager` described below.
Class description:
Implement the SequenceManager class.
Method signatures and docstrings:
- def onClicked_button_create_sequence(self): Event listener for create sequence button in Experimental Protocol tab. The listed tasks will be iterated 'group number'... | 3fc47027ef2fcb69d54a95d4dec369e2221559a0 | <|skeleton|>
class SequenceManager:
def onClicked_button_create_sequence(self):
"""Event listener for create sequence button in Experimental Protocol tab. The listed tasks will be iterated 'group number' times in the Task table"""
<|body_0|>
def onClicked_button_randomize(self):
"""Eve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceManager:
def onClicked_button_create_sequence(self):
"""Event listener for create sequence button in Experimental Protocol tab. The listed tasks will be iterated 'group number' times in the Task table"""
group_number = int(self.ui.lineEdit_group_number.text())
self.protocol.cre... | the_stack_v2_python_sparse | package/views/main_GUI/exp_protocol_design/sequence_manager.py | WILLSNIU186/EEG-Online-Experiment-GUI | train | 13 | |
055e0945666915c62de4dd740440837d972f1026 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('yjunchoi_yzhang71', 'yjunchoi_yzhang71')\nrepo.dropCollection('pollingLocation')\nrepo.createCollection('pollingLocation')\nurl = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/f7c6dc9eb6b144... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('yjunchoi_yzhang71', 'yjunchoi_yzhang71')
repo.dropCollection('pollingLocation')
repo.createCollection('pollingLocation')
url = 'http://bos... | pollingLocation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pollingLocation:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythi... | stack_v2_sparse_classes_36k_train_005983 | 3,601 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_013409 | Implement the Python class `pollingLocation` described below.
Class description:
Implement the pollingLocation class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=Non... | Implement the Python class `pollingLocation` described below.
Class description:
Implement the pollingLocation class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=Non... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class pollingLocation:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class pollingLocation:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('yjunchoi_yzhang71', 'yjunchoi_yzhan... | the_stack_v2_python_sparse | yjunchoi_yzhang71/pollingLocation.py | ROODAY/course-2017-fal-proj | train | 3 | |
96647a534284a3a0c57ba511cb75f8bb8cd45ddb | [
"session = db_apis.get_session()\nwith session.begin():\n db_amp = self.amphora_repo.get(session, id=amphora.get(constants.ID))\nself.amphora_driver.finalize_amphora(db_amp)\nLOG.debug('Finalized the amphora.')",
"if isinstance(result, failure.Failure):\n return\nLOG.warning('Reverting amphora finalize.')\n... | <|body_start_0|>
session = db_apis.get_session()
with session.begin():
db_amp = self.amphora_repo.get(session, id=amphora.get(constants.ID))
self.amphora_driver.finalize_amphora(db_amp)
LOG.debug('Finalized the amphora.')
<|end_body_0|>
<|body_start_1|>
if isinstance... | Task to finalize the amphora before any listeners are configured. | AmphoraFinalize | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmphoraFinalize:
"""Task to finalize the amphora before any listeners are configured."""
def execute(self, amphora):
"""Execute finalize_amphora routine."""
<|body_0|>
def revert(self, result, amphora, *args, **kwargs):
"""Handle a failed amphora finalize."""
... | stack_v2_sparse_classes_36k_train_005984 | 28,773 | permissive | [
{
"docstring": "Execute finalize_amphora routine.",
"name": "execute",
"signature": "def execute(self, amphora)"
},
{
"docstring": "Handle a failed amphora finalize.",
"name": "revert",
"signature": "def revert(self, result, amphora, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `AmphoraFinalize` described below.
Class description:
Task to finalize the amphora before any listeners are configured.
Method signatures and docstrings:
- def execute(self, amphora): Execute finalize_amphora routine.
- def revert(self, result, amphora, *args, **kwargs): Handle a failed amp... | Implement the Python class `AmphoraFinalize` described below.
Class description:
Task to finalize the amphora before any listeners are configured.
Method signatures and docstrings:
- def execute(self, amphora): Execute finalize_amphora routine.
- def revert(self, result, amphora, *args, **kwargs): Handle a failed amp... | 0426285a41464a5015494584f109eed35a0d44db | <|skeleton|>
class AmphoraFinalize:
"""Task to finalize the amphora before any listeners are configured."""
def execute(self, amphora):
"""Execute finalize_amphora routine."""
<|body_0|>
def revert(self, result, amphora, *args, **kwargs):
"""Handle a failed amphora finalize."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AmphoraFinalize:
"""Task to finalize the amphora before any listeners are configured."""
def execute(self, amphora):
"""Execute finalize_amphora routine."""
session = db_apis.get_session()
with session.begin():
db_amp = self.amphora_repo.get(session, id=amphora.get(con... | the_stack_v2_python_sparse | octavia/controller/worker/v2/tasks/amphora_driver_tasks.py | openstack/octavia | train | 147 |
698d9f67974508089d123eea8c4b0bc0fc14ccec | [
"self.logger = getMSLogger(getattr(msConfig, 'verbose', False), kwargs.get('logger'))\nself.msConfig = msConfig\nself.logger.info('Configuration including default values:\\n%s', self.msConfig)\nself.authzRules = readAuthzRules(msConfig.get('authz_rules', None))\nself.authzKey = msConfig['authz_key']\nif isinstance(... | <|body_start_0|>
self.logger = getMSLogger(getattr(msConfig, 'verbose', False), kwargs.get('logger'))
self.msConfig = msConfig
self.logger.info('Configuration including default values:\n%s', self.msConfig)
self.authzRules = readAuthzRules(msConfig.get('authz_rules', None))
self.a... | This class provides auth/authz functionality for micro-services | MSAuth | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MSAuth:
"""This class provides auth/authz functionality for micro-services"""
def __init__(self, msConfig, **kwargs):
"""Provides a basic setup for all the microservices :param msConfig: MS service configuration :param kwargs: optional parameters"""
<|body_0|>
def author... | stack_v2_sparse_classes_36k_train_005985 | 5,449 | permissive | [
{
"docstring": "Provides a basic setup for all the microservices :param msConfig: MS service configuration :param kwargs: optional parameters",
"name": "__init__",
"signature": "def __init__(self, msConfig, **kwargs)"
},
{
"docstring": "Check auth role. :return: boolean",
"name": "authorizeA... | 2 | null | Implement the Python class `MSAuth` described below.
Class description:
This class provides auth/authz functionality for micro-services
Method signatures and docstrings:
- def __init__(self, msConfig, **kwargs): Provides a basic setup for all the microservices :param msConfig: MS service configuration :param kwargs: ... | Implement the Python class `MSAuth` described below.
Class description:
This class provides auth/authz functionality for micro-services
Method signatures and docstrings:
- def __init__(self, msConfig, **kwargs): Provides a basic setup for all the microservices :param msConfig: MS service configuration :param kwargs: ... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class MSAuth:
"""This class provides auth/authz functionality for micro-services"""
def __init__(self, msConfig, **kwargs):
"""Provides a basic setup for all the microservices :param msConfig: MS service configuration :param kwargs: optional parameters"""
<|body_0|>
def author... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MSAuth:
"""This class provides auth/authz functionality for micro-services"""
def __init__(self, msConfig, **kwargs):
"""Provides a basic setup for all the microservices :param msConfig: MS service configuration :param kwargs: optional parameters"""
self.logger = getMSLogger(getattr(msCon... | the_stack_v2_python_sparse | src/python/WMCore/MicroService/MSCore/MSAuth.py | vkuznet/WMCore | train | 0 |
c12917949c5cb349cdd7d91554b4297b4bb23946 | [
"if not date == None:\n date = '%sT%sZ' % (date, time)\nreturn date",
"if not datetime == None and 'T' in datetime:\n datetime = datetime.split('T')[0]\nreturn datetime"
] | <|body_start_0|>
if not date == None:
date = '%sT%sZ' % (date, time)
return date
<|end_body_0|>
<|body_start_1|>
if not datetime == None and 'T' in datetime:
datetime = datetime.split('T')[0]
return datetime
<|end_body_1|>
| StringExtensions | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringExtensions:
def convertDateStrToDateTimeStr(date, time='00:00:00'):
"""Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ) Args: date: the date as a string to be converted time: the time as a string to be added to the date Returns... | stack_v2_sparse_classes_36k_train_005986 | 1,907 | permissive | [
{
"docstring": "Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ) Args: date: the date as a string to be converted time: the time as a string to be added to the date Returns: A string representation of a datetime in the following format YYYY-MM-DDTHH:mm:SSZ"... | 2 | stack_v2_sparse_classes_30k_train_007239 | Implement the Python class `StringExtensions` described below.
Class description:
Implement the StringExtensions class.
Method signatures and docstrings:
- def convertDateStrToDateTimeStr(date, time='00:00:00'): Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ) Ar... | Implement the Python class `StringExtensions` described below.
Class description:
Implement the StringExtensions class.
Method signatures and docstrings:
- def convertDateStrToDateTimeStr(date, time='00:00:00'): Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ) Ar... | b596df09c52511e2e0c0987f6245aa4607190dd0 | <|skeleton|>
class StringExtensions:
def convertDateStrToDateTimeStr(date, time='00:00:00'):
"""Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ) Args: date: the date as a string to be converted time: the time as a string to be added to the date Returns... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringExtensions:
def convertDateStrToDateTimeStr(date, time='00:00:00'):
"""Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ) Args: date: the date as a string to be converted time: the time as a string to be added to the date Returns: A string rep... | the_stack_v2_python_sparse | starthinker/task/traffic/class_extensions.py | google/starthinker | train | 167 | |
4d866359ebc5ac83258332ebea965fb946d93db7 | [
"self.func = func\nself.args = args or list()\nself.kwargs = kwargs or dict()\nself.name = name or 'Generic'\nself.is_complete = Event()\nself.output = None",
"if not self.is_complete.isSet():\n if self.name != 'Parsing':\n zdslog.debug('Performing %s Task' % self.name)\n try:\n self.output = ... | <|body_start_0|>
self.func = func
self.args = args or list()
self.kwargs = kwargs or dict()
self.name = name or 'Generic'
self.is_complete = Event()
self.output = None
<|end_body_0|>
<|body_start_1|>
if not self.is_complete.isSet():
if self.name != 'P... | Represents a Task to be performed. .. attribute:: func The function this Task will call when it is performed .. attribute:: args A list of positional arguments to pass to func .. attribute:: kwargs A list of keyword arguments to pass to func .. attribute:: name The (optional) name of this task, default 'Generic' .. att... | Task | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Task:
"""Represents a Task to be performed. .. attribute:: func The function this Task will call when it is performed .. attribute:: args A list of positional arguments to pass to func .. attribute:: kwargs A list of keyword arguments to pass to func .. attribute:: name The (optional) name of thi... | stack_v2_sparse_classes_36k_train_005987 | 2,478 | permissive | [
{
"docstring": "Initializes a Task. :param func: what this Task calls when it's performed :type func: function :param args: A list of positional arguments to pass to func, default None :param kwargs: A list of keyword arguments to pass to func, default None :param name: The (optional) name of this task, default... | 2 | stack_v2_sparse_classes_30k_train_011552 | Implement the Python class `Task` described below.
Class description:
Represents a Task to be performed. .. attribute:: func The function this Task will call when it is performed .. attribute:: args A list of positional arguments to pass to func .. attribute:: kwargs A list of keyword arguments to pass to func .. attr... | Implement the Python class `Task` described below.
Class description:
Represents a Task to be performed. .. attribute:: func The function this Task will call when it is performed .. attribute:: args A list of positional arguments to pass to func .. attribute:: kwargs A list of keyword arguments to pass to func .. attr... | 2d0c88778f1dd1f820a9685032fc68d3f91f3532 | <|skeleton|>
class Task:
"""Represents a Task to be performed. .. attribute:: func The function this Task will call when it is performed .. attribute:: args A list of positional arguments to pass to func .. attribute:: kwargs A list of keyword arguments to pass to func .. attribute:: name The (optional) name of thi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Task:
"""Represents a Task to be performed. .. attribute:: func The function this Task will call when it is performed .. attribute:: args A list of positional arguments to pass to func .. attribute:: kwargs A list of keyword arguments to pass to func .. attribute:: name The (optional) name of this task, defau... | the_stack_v2_python_sparse | trunk/ZDStack/ZDSTask.py | camgunz/zdstack | train | 2 |
d7f3c2f5dd1bf40787a2d35c53e502defd750991 | [
"super().__init__()\nself.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)\nself.gru = tf.keras.layers.GRU(units=units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')\nself.F = tf.keras.layers.Dense(units=vocab)",
"_, units = s_prev.shape\nattention =... | <|body_start_0|>
super().__init__()
self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)
self.gru = tf.keras.layers.GRU(units=units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')
self.F = tf.keras.layers.Dense(units=vocab)
... | Inherits from tensorflow.keras.layers.Layer to decode for machine translation | RNNDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""Inherits from tensorflow.keras.layers.Layer to decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor"""
<|body_0|>
def call(self, x, s_prev, hidden_states):
"""* x (batch, 1) contains the previou... | stack_v2_sparse_classes_36k_train_005988 | 2,316 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, vocab, embedding, units, batch)"
},
{
"docstring": "* x (batch, 1) contains the previous word in the target sequence as an index of the target vocabulary. * s_prev (batch, units) contains the previous decode... | 2 | null | Implement the Python class `RNNDecoder` described below.
Class description:
Inherits from tensorflow.keras.layers.Layer to decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor
- def call(self, x, s_prev, hidden_states): * x (batch, 1)... | Implement the Python class `RNNDecoder` described below.
Class description:
Inherits from tensorflow.keras.layers.Layer to decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor
- def call(self, x, s_prev, hidden_states): * x (batch, 1)... | 161e33b23d398d7d01ad0d7740b78dda3f27e787 | <|skeleton|>
class RNNDecoder:
"""Inherits from tensorflow.keras.layers.Layer to decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor"""
<|body_0|>
def call(self, x, s_prev, hidden_states):
"""* x (batch, 1) contains the previou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNDecoder:
"""Inherits from tensorflow.keras.layers.Layer to decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor"""
super().__init__()
self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)
... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | felipeserna/holbertonschool-machine_learning | train | 0 |
a7eb5ca5affb37a488272a1a2cd0bddbe20bebbe | [
"l_id = 0\nproduction_obj = self.pool.get('stock.production.lot')\nfor line in self.browse(cr, uid, ids, context=context):\n if line.production_lot_id:\n continue\n l_id += 1\n production_lot_dico = {'name': line.order_id and str(line.order_id.name) + '/%02d' % (l_id,) or False, 'product_id': line.p... | <|body_start_0|>
l_id = 0
production_obj = self.pool.get('stock.production.lot')
for line in self.browse(cr, uid, ids, context=context):
if line.production_lot_id:
continue
l_id += 1
production_lot_dico = {'name': line.order_id and str(line.ord... | sale_order_line | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sale_order_line:
def button_confirm(self, cr, uid, ids, context=None):
"""This method confirm order. @param self : Object Pointer @param cr : Database Cursor @param uid : Current Logged in User @param ids : Current Records @param context : standard Dictionary @return : True"""
<|... | stack_v2_sparse_classes_36k_train_005989 | 9,284 | no_license | [
{
"docstring": "This method confirm order. @param self : Object Pointer @param cr : Database Cursor @param uid : Current Logged in User @param ids : Current Records @param context : standard Dictionary @return : True",
"name": "button_confirm",
"signature": "def button_confirm(self, cr, uid, ids, contex... | 2 | null | Implement the Python class `sale_order_line` described below.
Class description:
Implement the sale_order_line class.
Method signatures and docstrings:
- def button_confirm(self, cr, uid, ids, context=None): This method confirm order. @param self : Object Pointer @param cr : Database Cursor @param uid : Current Logge... | Implement the Python class `sale_order_line` described below.
Class description:
Implement the sale_order_line class.
Method signatures and docstrings:
- def button_confirm(self, cr, uid, ids, context=None): This method confirm order. @param self : Object Pointer @param cr : Database Cursor @param uid : Current Logge... | c5a5678379649ccdf57a9d55b09b30436428b430 | <|skeleton|>
class sale_order_line:
def button_confirm(self, cr, uid, ids, context=None):
"""This method confirm order. @param self : Object Pointer @param cr : Database Cursor @param uid : Current Logged in User @param ids : Current Records @param context : standard Dictionary @return : True"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class sale_order_line:
def button_confirm(self, cr, uid, ids, context=None):
"""This method confirm order. @param self : Object Pointer @param cr : Database Cursor @param uid : Current Logged in User @param ids : Current Records @param context : standard Dictionary @return : True"""
l_id = 0
... | the_stack_v2_python_sparse | education/library/sale.py | adahra/addons | train | 1 | |
a7c46aedba6fdde82f4e12e17763a6e542483afb | [
"super(ConsumerComplaints, self).__init__(name, **kwargs)\nself.website_id = 'consumer_complaints'\nself.website_type = 'complaint'",
"base_url = 'https://www.consumercomplaints.in/bysubcategory/mobile-handsets/page/%d'\nfor page_index in range(1, 2):\n request_url = base_url % page_index\n request = Reques... | <|body_start_0|>
super(ConsumerComplaints, self).__init__(name, **kwargs)
self.website_id = 'consumer_complaints'
self.website_type = 'complaint'
<|end_body_0|>
<|body_start_1|>
base_url = 'https://www.consumercomplaints.in/bysubcategory/mobile-handsets/page/%d'
for page_index i... | 爬虫类 爬虫类名与 website_id 一致,不过遵循类名的首字母大写命名格式 | ConsumerComplaints | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsumerComplaints:
"""爬虫类 爬虫类名与 website_id 一致,不过遵循类名的首字母大写命名格式"""
def __init__(self, name=None, **kwargs):
"""完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None"""
<|body_0|>
def s... | stack_v2_sparse_classes_36k_train_005990 | 3,480 | no_license | [
{
"docstring": "完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None",
"name": "__init__",
"signature": "def __init__(self, name=None, **kwargs)"
},
{
"docstring": "爬虫任务的起点,由于网站数据量有限,这里 url 为不变的 :warning: 增量更... | 3 | null | Implement the Python class `ConsumerComplaints` described below.
Class description:
爬虫类 爬虫类名与 website_id 一致,不过遵循类名的首字母大写命名格式
Method signatures and docstrings:
- def __init__(self, name=None, **kwargs): 完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 se... | Implement the Python class `ConsumerComplaints` described below.
Class description:
爬虫类 爬虫类名与 website_id 一致,不过遵循类名的首字母大写命名格式
Method signatures and docstrings:
- def __init__(self, name=None, **kwargs): 完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 se... | 1b42878b694fabc65a02228662ffdf819e5dcc71 | <|skeleton|>
class ConsumerComplaints:
"""爬虫类 爬虫类名与 website_id 一致,不过遵循类名的首字母大写命名格式"""
def __init__(self, name=None, **kwargs):
"""完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None"""
<|body_0|>
def s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConsumerComplaints:
"""爬虫类 爬虫类名与 website_id 一致,不过遵循类名的首字母大写命名格式"""
def __init__(self, name=None, **kwargs):
"""完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None"""
super(ConsumerComplaints, self).__... | the_stack_v2_python_sparse | zhengkuo/consumer_complaints/consumer_complaints/spiders/consumer_complaints.py | wangsanshi123/spiders | train | 0 |
0440459c91257265d4e54862f8582033e6b0f453 | [
"self.number = number\nself.task = task\nself.key = key\nself.runs = runs\nself.trynext = trynext\nself.anytime = anytime\nself.json = json\nself.participants = participants\nself.task_debug = task_debug\nself.forced_debug = forced_debug",
"if self.task_debug or self.forced_debug:\n log_debug = log.debug_alway... | <|body_start_0|>
self.number = number
self.task = task
self.key = key
self.runs = runs
self.trynext = trynext
self.anytime = anytime
self.json = json
self.participants = participants
self.task_debug = task_debug
self.forced_debug = forced_d... | Handles scheduling for a single run. | SchedulerWorker | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedulerWorker:
"""Handles scheduling for a single run."""
def __init__(self, number, task, key, runs, trynext, anytime, json, participants, task_debug, forced_debug):
"""Initialize"""
<|body_0|>
def __call__(self):
"""Do the scheduling"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_005991 | 35,160 | permissive | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self, number, task, key, runs, trynext, anytime, json, participants, task_debug, forced_debug)"
},
{
"docstring": "Do the scheduling",
"name": "__call__",
"signature": "def __call__(self)"
}
] | 2 | null | Implement the Python class `SchedulerWorker` described below.
Class description:
Handles scheduling for a single run.
Method signatures and docstrings:
- def __init__(self, number, task, key, runs, trynext, anytime, json, participants, task_debug, forced_debug): Initialize
- def __call__(self): Do the scheduling | Implement the Python class `SchedulerWorker` described below.
Class description:
Handles scheduling for a single run.
Method signatures and docstrings:
- def __init__(self, number, task, key, runs, trynext, anytime, json, participants, task_debug, forced_debug): Initialize
- def __call__(self): Do the scheduling
<|s... | f6d04c0455e5be4d490df16ec1acb377f9025d9f | <|skeleton|>
class SchedulerWorker:
"""Handles scheduling for a single run."""
def __init__(self, number, task, key, runs, trynext, anytime, json, participants, task_debug, forced_debug):
"""Initialize"""
<|body_0|>
def __call__(self):
"""Do the scheduling"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchedulerWorker:
"""Handles scheduling for a single run."""
def __init__(self, number, task, key, runs, trynext, anytime, json, participants, task_debug, forced_debug):
"""Initialize"""
self.number = number
self.task = task
self.key = key
self.runs = runs
s... | the_stack_v2_python_sparse | pscheduler-server/pscheduler-server/daemons/scheduler | perfsonar/pscheduler | train | 53 |
b03d8e77889d78d07471cbc646ced16102682277 | [
"value = '<div>'\nclase = 'actions'\nurl_cont = './' + str(obj.id_tipo_item)\nid_tipo = UrlParser.parse_id(request.url, 'tipositems')\nif id_tipo:\n url_cont = '../' + str(obj.id_tipo_item)\nif UrlParser.parse_nombre(request.url, 'post_buscar'):\n url_cont = '../' + str(obj.id_tipo_item)\npp = PoseePermiso('r... | <|body_start_0|>
value = '<div>'
clase = 'actions'
url_cont = './' + str(obj.id_tipo_item)
id_tipo = UrlParser.parse_id(request.url, 'tipositems')
if id_tipo:
url_cont = '../' + str(obj.id_tipo_item)
if UrlParser.parse_nombre(request.url, 'post_buscar'):
... | TipoItemTableFiller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TipoItemTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, id_fase=None, id_tipo=None, **kw):
"""Se muestra la lista de tipos de item para la fase en cuestión"""
<|body_1... | stack_v2_sparse_classes_36k_train_005992 | 21,979 | no_license | [
{
"docstring": "Links de acciones para un registro dado",
"name": "__actions__",
"signature": "def __actions__(self, obj)"
},
{
"docstring": "Se muestra la lista de tipos de item para la fase en cuestión",
"name": "_do_get_provider_count_and_objs",
"signature": "def _do_get_provider_coun... | 2 | stack_v2_sparse_classes_30k_train_014038 | Implement the Python class `TipoItemTableFiller` described below.
Class description:
Implement the TipoItemTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, id_fase=None, id_tipo=None, **kw): Se muestr... | Implement the Python class `TipoItemTableFiller` described below.
Class description:
Implement the TipoItemTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, id_fase=None, id_tipo=None, **kw): Se muestr... | 997531e130d1951b483f4a6a67f2df7467cd9fd1 | <|skeleton|>
class TipoItemTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, id_fase=None, id_tipo=None, **kw):
"""Se muestra la lista de tipos de item para la fase en cuestión"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TipoItemTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
value = '<div>'
clase = 'actions'
url_cont = './' + str(obj.id_tipo_item)
id_tipo = UrlParser.parse_id(request.url, 'tipositems')
if id_tipo:
url_cont = '.... | the_stack_v2_python_sparse | lpm/controllers/tipoitem.py | jorgeramirez/LPM | train | 1 | |
0361320c7de07ad261f2fea08a05f3f5cb605d02 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | FederatedLearningServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FederatedLearningServicer:
"""Missing associated documentation comment in .proto file."""
def GetJob(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def GetTensorRecord(self, request, context):
"""Missing associa... | stack_v2_sparse_classes_36k_train_005993 | 7,291 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetJob",
"signature": "def GetJob(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetTensorRecord",
"signature": "def GetTensorRecord(self, ... | 4 | stack_v2_sparse_classes_30k_train_010810 | Implement the Python class `FederatedLearningServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetJob(self, request, context): Missing associated documentation comment in .proto file.
- def GetTensorRecord(self, request, cont... | Implement the Python class `FederatedLearningServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetJob(self, request, context): Missing associated documentation comment in .proto file.
- def GetTensorRecord(self, request, cont... | 1223619661f82733b5d66f8901cac7f16002c610 | <|skeleton|>
class FederatedLearningServicer:
"""Missing associated documentation comment in .proto file."""
def GetJob(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def GetTensorRecord(self, request, context):
"""Missing associa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FederatedLearningServicer:
"""Missing associated documentation comment in .proto file."""
def GetJob(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!... | the_stack_v2_python_sparse | src/appfl/protos/federated_learning_pb2_grpc.py | APPFL/APPFL | train | 39 |
89d851a8294be9c9e34f072b6714fbb1d600c0d6 | [
"self.keys = keys\nself.default_key = default_key\nself.token_mapping = token_mapping",
"args, kwargs = parse_args(text)\nif len(kwargs) and len(args):\n raise MixOfNamedAndOrderedArgs(text)\nif len(args):\n return self.apply_token_mapping(args, text)\nreturn self.validate_kwargs(kwargs, text)",
"if len(a... | <|body_start_0|>
self.keys = keys
self.default_key = default_key
self.token_mapping = token_mapping
<|end_body_0|>
<|body_start_1|>
args, kwargs = parse_args(text)
if len(kwargs) and len(args):
raise MixOfNamedAndOrderedArgs(text)
if len(args):
re... | Parser for options | Parser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parser:
"""Parser for options"""
def __init__(self, keys, default_key, token_mapping):
""".ctor keys (list): list of keys token_mapping (TokenMapping[]): list of token mappings default_key (string): default"""
<|body_0|>
def parse(self, text):
"""Parse argument s... | stack_v2_sparse_classes_36k_train_005994 | 8,680 | permissive | [
{
"docstring": ".ctor keys (list): list of keys token_mapping (TokenMapping[]): list of token mappings default_key (string): default",
"name": "__init__",
"signature": "def __init__(self, keys, default_key, token_mapping)"
},
{
"docstring": "Parse argument string Args: text (string): argument na... | 4 | stack_v2_sparse_classes_30k_train_015112 | Implement the Python class `Parser` described below.
Class description:
Parser for options
Method signatures and docstrings:
- def __init__(self, keys, default_key, token_mapping): .ctor keys (list): list of keys token_mapping (TokenMapping[]): list of token mappings default_key (string): default
- def parse(self, te... | Implement the Python class `Parser` described below.
Class description:
Parser for options
Method signatures and docstrings:
- def __init__(self, keys, default_key, token_mapping): .ctor keys (list): list of keys token_mapping (TokenMapping[]): list of token mappings default_key (string): default
- def parse(self, te... | d09e36f0319f5d3ac0b83ee84b8848d2b2e8e481 | <|skeleton|>
class Parser:
"""Parser for options"""
def __init__(self, keys, default_key, token_mapping):
""".ctor keys (list): list of keys token_mapping (TokenMapping[]): list of token mappings default_key (string): default"""
<|body_0|>
def parse(self, text):
"""Parse argument s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Parser:
"""Parser for options"""
def __init__(self, keys, default_key, token_mapping):
""".ctor keys (list): list of keys token_mapping (TokenMapping[]): list of token mappings default_key (string): default"""
self.keys = keys
self.default_key = default_key
self.token_mapp... | the_stack_v2_python_sparse | tml/rules/options.py | translationexchange/tml-python | train | 2 |
f02f6712d7c06880d738c68cb2b288e3f480bdc7 | [
"self.job_uids = job_uids\nself.cluster_id = cluster_id\nself.cluster_match_string = cluster_match_string\nself.encryption_keys = encryption_keys\nself.end_time_usecs = end_time_usecs\nself.job_match_string = job_match_string\nself.search_job_name = search_job_name\nself.start_time_usecs = start_time_usecs\nself.va... | <|body_start_0|>
self.job_uids = job_uids
self.cluster_id = cluster_id
self.cluster_match_string = cluster_match_string
self.encryption_keys = encryption_keys
self.end_time_usecs = end_time_usecs
self.job_match_string = job_match_string
self.search_job_name = sear... | Implementation of the 'CreateRemoteVaultSearchJobParameters' model. Specifies settings required to create a search of a remote Vault for data that has been archived from other Clusters. Attributes: job_uids (list of string): Filter by specifying a list of remote job uids in form of clusterId:clusterIncarnationId:jobId.... | CreateRemoteVaultSearchJobParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateRemoteVaultSearchJobParameters:
"""Implementation of the 'CreateRemoteVaultSearchJobParameters' model. Specifies settings required to create a search of a remote Vault for data that has been archived from other Clusters. Attributes: job_uids (list of string): Filter by specifying a list of ... | stack_v2_sparse_classes_36k_train_005995 | 5,599 | permissive | [
{
"docstring": "Constructor for the CreateRemoteVaultSearchJobParameters class",
"name": "__init__",
"signature": "def __init__(self, job_uids=None, cluster_id=None, cluster_match_string=None, encryption_keys=None, end_time_usecs=None, job_match_string=None, search_job_name=None, start_time_usecs=None, ... | 2 | stack_v2_sparse_classes_30k_train_010469 | Implement the Python class `CreateRemoteVaultSearchJobParameters` described below.
Class description:
Implementation of the 'CreateRemoteVaultSearchJobParameters' model. Specifies settings required to create a search of a remote Vault for data that has been archived from other Clusters. Attributes: job_uids (list of s... | Implement the Python class `CreateRemoteVaultSearchJobParameters` described below.
Class description:
Implementation of the 'CreateRemoteVaultSearchJobParameters' model. Specifies settings required to create a search of a remote Vault for data that has been archived from other Clusters. Attributes: job_uids (list of s... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CreateRemoteVaultSearchJobParameters:
"""Implementation of the 'CreateRemoteVaultSearchJobParameters' model. Specifies settings required to create a search of a remote Vault for data that has been archived from other Clusters. Attributes: job_uids (list of string): Filter by specifying a list of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateRemoteVaultSearchJobParameters:
"""Implementation of the 'CreateRemoteVaultSearchJobParameters' model. Specifies settings required to create a search of a remote Vault for data that has been archived from other Clusters. Attributes: job_uids (list of string): Filter by specifying a list of remote job ui... | the_stack_v2_python_sparse | cohesity_management_sdk/models/create_remote_vault_search_job_parameters.py | cohesity/management-sdk-python | train | 24 |
2ccc503f8a9efd4aa08f95ef77e3b4988adb1420 | [
"comments = CommentsReleases.query.order_by(asc(CommentsReleases.ReleaseID), asc(CommentsReleases.Created)).all()\ncontents = jsonify({'comments': [{'commentID': comment.CommentID, 'releaseID': comment.ReleaseID, 'userID': comment.UserID, 'name': get_username(comment.UserID), 'comment': comment.Comment, 'createdAt'... | <|body_start_0|>
comments = CommentsReleases.query.order_by(asc(CommentsReleases.ReleaseID), asc(CommentsReleases.Created)).all()
contents = jsonify({'comments': [{'commentID': comment.CommentID, 'releaseID': comment.ReleaseID, 'userID': comment.UserID, 'name': get_username(comment.UserID), 'comment': c... | ReleaseCommentsView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReleaseCommentsView:
def index(self):
"""Return all comments for all releases."""
<|body_0|>
def get(self, release_id):
"""Return the comments for a specific release."""
<|body_1|>
def post(self):
"""Add a comment to a release specified in the pa... | stack_v2_sparse_classes_36k_train_005996 | 26,847 | permissive | [
{
"docstring": "Return all comments for all releases.",
"name": "index",
"signature": "def index(self)"
},
{
"docstring": "Return the comments for a specific release.",
"name": "get",
"signature": "def get(self, release_id)"
},
{
"docstring": "Add a comment to a release specified... | 5 | stack_v2_sparse_classes_30k_train_005430 | Implement the Python class `ReleaseCommentsView` described below.
Class description:
Implement the ReleaseCommentsView class.
Method signatures and docstrings:
- def index(self): Return all comments for all releases.
- def get(self, release_id): Return the comments for a specific release.
- def post(self): Add a comm... | Implement the Python class `ReleaseCommentsView` described below.
Class description:
Implement the ReleaseCommentsView class.
Method signatures and docstrings:
- def index(self): Return all comments for all releases.
- def get(self, release_id): Return the comments for a specific release.
- def post(self): Add a comm... | 62f8e8e904e379541193f0cbb91a8434b47f538f | <|skeleton|>
class ReleaseCommentsView:
def index(self):
"""Return all comments for all releases."""
<|body_0|>
def get(self, release_id):
"""Return the comments for a specific release."""
<|body_1|>
def post(self):
"""Add a comment to a release specified in the pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReleaseCommentsView:
def index(self):
"""Return all comments for all releases."""
comments = CommentsReleases.query.order_by(asc(CommentsReleases.ReleaseID), asc(CommentsReleases.Created)).all()
contents = jsonify({'comments': [{'commentID': comment.CommentID, 'releaseID': comment.Rele... | the_stack_v2_python_sparse | apps/comments/views.py | Torniojaws/vortech-backend | train | 0 | |
6166892fb7115ea4a3bb2c8001f969f60a329617 | [
"tk.Tk.__init__(self, *args, **kwargs)\nself.title('MPMe')\nself.geometry('300x350')\nself.protocol('WM_DELETE_WINDOW', self.on_closing)\nMpmeFileManager.initialize_folders()\nself.settings_object = MpmeSettings()\nself.sound_object = MpmeSound(self.settings_object.get_settings())\ncontainer = tk.Frame(self)\nconta... | <|body_start_0|>
tk.Tk.__init__(self, *args, **kwargs)
self.title('MPMe')
self.geometry('300x350')
self.protocol('WM_DELETE_WINDOW', self.on_closing)
MpmeFileManager.initialize_folders()
self.settings_object = MpmeSettings()
self.sound_object = MpmeSound(self.sett... | The window class | Mpme | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mpme:
"""The window class"""
def __init__(self, *args, **kwargs):
"""Initialize the window."""
<|body_0|>
def show_frame(self, name):
"""Show the frame, that is, the container for all the pages."""
<|body_1|>
def on_closing(self):
"""Before c... | stack_v2_sparse_classes_36k_train_005997 | 28,545 | no_license | [
{
"docstring": "Initialize the window.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Show the frame, that is, the container for all the pages.",
"name": "show_frame",
"signature": "def show_frame(self, name)"
},
{
"docstring": "Before... | 3 | stack_v2_sparse_classes_30k_train_006178 | Implement the Python class `Mpme` described below.
Class description:
The window class
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the window.
- def show_frame(self, name): Show the frame, that is, the container for all the pages.
- def on_closing(self): Before closing the wind... | Implement the Python class `Mpme` described below.
Class description:
The window class
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the window.
- def show_frame(self, name): Show the frame, that is, the container for all the pages.
- def on_closing(self): Before closing the wind... | cb540fd8cc4f1c64959cf2545ae709586bfd7783 | <|skeleton|>
class Mpme:
"""The window class"""
def __init__(self, *args, **kwargs):
"""Initialize the window."""
<|body_0|>
def show_frame(self, name):
"""Show the frame, that is, the container for all the pages."""
<|body_1|>
def on_closing(self):
"""Before c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mpme:
"""The window class"""
def __init__(self, *args, **kwargs):
"""Initialize the window."""
tk.Tk.__init__(self, *args, **kwargs)
self.title('MPMe')
self.geometry('300x350')
self.protocol('WM_DELETE_WINDOW', self.on_closing)
MpmeFileManager.initialize_fo... | the_stack_v2_python_sparse | mpme.py | AaronBitman/MPMe | train | 0 |
7f4a9e0fe440133d148516e242aacede4432d4a3 | [
"super(EvaluateClassifyImagesCAE, self).__init__(**kwargs)\nself.CAE_architecture = CAE_architecture\nself.endpoint = endpoint",
"net = self.CAE_architecture(inputs, final_endpoint=self.endpoint)\nnet = slim.flatten(net, scope='PreLogitsFlatten')\nself.logits = slim.fully_connected(net, num_classes, activation_fn... | <|body_start_0|>
super(EvaluateClassifyImagesCAE, self).__init__(**kwargs)
self.CAE_architecture = CAE_architecture
self.endpoint = endpoint
<|end_body_0|>
<|body_start_1|>
net = self.CAE_architecture(inputs, final_endpoint=self.endpoint)
net = slim.flatten(net, scope='PreLogits... | Evaluate the trained perceptron built on CAE representation. This is the evaluatio part of `TrainClassifyImagesCAE`. | EvaluateClassifyImagesCAE | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluateClassifyImagesCAE:
"""Evaluate the trained perceptron built on CAE representation. This is the evaluatio part of `TrainClassifyImagesCAE`."""
def __init__(self, CAE_architecture, endpoint='Middle', **kwargs):
"""Give the used CAE architecture and the representation layer. Arg... | stack_v2_sparse_classes_36k_train_005998 | 12,295 | no_license | [
{
"docstring": "Give the used CAE architecture and the representation layer. Args: CAE_architecture: The CAE artictecture to compute the high-level representation of image. endpoint: Indicate the layer of the network that is used as the high-level representation of image. It becomes then the input of the percep... | 2 | stack_v2_sparse_classes_30k_train_005819 | Implement the Python class `EvaluateClassifyImagesCAE` described below.
Class description:
Evaluate the trained perceptron built on CAE representation. This is the evaluatio part of `TrainClassifyImagesCAE`.
Method signatures and docstrings:
- def __init__(self, CAE_architecture, endpoint='Middle', **kwargs): Give th... | Implement the Python class `EvaluateClassifyImagesCAE` described below.
Class description:
Evaluate the trained perceptron built on CAE representation. This is the evaluatio part of `TrainClassifyImagesCAE`.
Method signatures and docstrings:
- def __init__(self, CAE_architecture, endpoint='Middle', **kwargs): Give th... | 28bf50de6f2281ff87d00e495a38002918101525 | <|skeleton|>
class EvaluateClassifyImagesCAE:
"""Evaluate the trained perceptron built on CAE representation. This is the evaluatio part of `TrainClassifyImagesCAE`."""
def __init__(self, CAE_architecture, endpoint='Middle', **kwargs):
"""Give the used CAE architecture and the representation layer. Arg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EvaluateClassifyImagesCAE:
"""Evaluate the trained perceptron built on CAE representation. This is the evaluatio part of `TrainClassifyImagesCAE`."""
def __init__(self, CAE_architecture, endpoint='Middle', **kwargs):
"""Give the used CAE architecture and the representation layer. Args: CAE_archit... | the_stack_v2_python_sparse | src/images/classify_routines.py | LucasChanChan/internship_2017 | train | 0 |
c0289200fddaccd13dee700f8008b75233c74de2 | [
"time_now = timezone.now()\nmesg = Message.objects.filter(Q(id=m_id) | Q(parent_msg=m_id))\nlatest_mesg = mesg.latest('sent_at')\nother_messages = mesg.exclude(id=latest_mesg.id)\nis_recipient = latest_mesg.recipient == request.user\nif is_recipient:\n latest_mesg.read_at = time_now\n latest_mesg.save()\nif o... | <|body_start_0|>
time_now = timezone.now()
mesg = Message.objects.filter(Q(id=m_id) | Q(parent_msg=m_id))
latest_mesg = mesg.latest('sent_at')
other_messages = mesg.exclude(id=latest_mesg.id)
is_recipient = latest_mesg.recipient == request.user
if is_recipient:
... | View messages in a thread | MessageView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageView:
"""View messages in a thread"""
def get(self, request, m_id):
"""Read messages in a conversation"""
<|body_0|>
def post(self, request, m_id):
"""Dispatch a reply to a conversation"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
time... | stack_v2_sparse_classes_36k_train_005999 | 5,346 | permissive | [
{
"docstring": "Read messages in a conversation",
"name": "get",
"signature": "def get(self, request, m_id)"
},
{
"docstring": "Dispatch a reply to a conversation",
"name": "post",
"signature": "def post(self, request, m_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008589 | Implement the Python class `MessageView` described below.
Class description:
View messages in a thread
Method signatures and docstrings:
- def get(self, request, m_id): Read messages in a conversation
- def post(self, request, m_id): Dispatch a reply to a conversation | Implement the Python class `MessageView` described below.
Class description:
View messages in a thread
Method signatures and docstrings:
- def get(self, request, m_id): Read messages in a conversation
- def post(self, request, m_id): Dispatch a reply to a conversation
<|skeleton|>
class MessageView:
"""View mess... | 3704cbe6e69ba3e4c53401d3bbc339208e9ebccd | <|skeleton|>
class MessageView:
"""View messages in a thread"""
def get(self, request, m_id):
"""Read messages in a conversation"""
<|body_0|>
def post(self, request, m_id):
"""Dispatch a reply to a conversation"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MessageView:
"""View messages in a thread"""
def get(self, request, m_id):
"""Read messages in a conversation"""
time_now = timezone.now()
mesg = Message.objects.filter(Q(id=m_id) | Q(parent_msg=m_id))
latest_mesg = mesg.latest('sent_at')
other_messages = mesg.excl... | the_stack_v2_python_sparse | troupon/conversations/views.py | morristech/troupon | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.