blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
83b3e9b3555759b67953a7957bbe65c18c01cf18 | [
"self.language = constant.LANGUAGE_NAME_DICT[args.language[0]]\nself.ide_name = constant.IDE_NAME_DICT[args.ide[0]]\nself.is_launch_ide = not args.no_launch\nself.depth = args.depth\nself.full_repo = args.android_tree\nself.is_skip_build = args.skip_build\nself.targets = args.targets.copy()\nself.verbose = args.ver... | <|body_start_0|>
self.language = constant.LANGUAGE_NAME_DICT[args.language[0]]
self.ide_name = constant.IDE_NAME_DICT[args.ide[0]]
self.is_launch_ide = not args.no_launch
self.depth = args.depth
self.full_repo = args.android_tree
self.is_skip_build = args.skip_build
... | A singleton class manages AIDEGen's configurations. ProjectConfig is a singleton class that can be accessed in other modules. Usage: 1. Main module should do it once by instantiating a ProjectConfig with users' input arguments and calling init_environment(). args = aidegen_main.main(sys.argv[1:]) project_config.Project... | ProjectConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectConfig:
"""A singleton class manages AIDEGen's configurations. ProjectConfig is a singleton class that can be accessed in other modules. Usage: 1. Main module should do it once by instantiating a ProjectConfig with users' input arguments and calling init_environment(). args = aidegen_main.... | stack_v2_sparse_classes_75kplus_train_007000 | 7,145 | no_license | [
{
"docstring": "ProjectConfig initialize. Args: An argparse.Namespace object holds parsed args.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Initialize the environment settings for the whole project.",
"name": "init_environment",
"signature": "def init... | 4 | stack_v2_sparse_classes_30k_train_007049 | Implement the Python class `ProjectConfig` described below.
Class description:
A singleton class manages AIDEGen's configurations. ProjectConfig is a singleton class that can be accessed in other modules. Usage: 1. Main module should do it once by instantiating a ProjectConfig with users' input arguments and calling i... | Implement the Python class `ProjectConfig` described below.
Class description:
A singleton class manages AIDEGen's configurations. ProjectConfig is a singleton class that can be accessed in other modules. Usage: 1. Main module should do it once by instantiating a ProjectConfig with users' input arguments and calling i... | 78a61ca023cbf1a0cecfef8b97df2b274ac3a988 | <|skeleton|>
class ProjectConfig:
"""A singleton class manages AIDEGen's configurations. ProjectConfig is a singleton class that can be accessed in other modules. Usage: 1. Main module should do it once by instantiating a ProjectConfig with users' input arguments and calling init_environment(). args = aidegen_main.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectConfig:
"""A singleton class manages AIDEGen's configurations. ProjectConfig is a singleton class that can be accessed in other modules. Usage: 1. Main module should do it once by instantiating a ProjectConfig with users' input arguments and calling init_environment(). args = aidegen_main.main(sys.argv... | the_stack_v2_python_sparse | tools/asuite/aidegen/lib/project_config.py | ZYHGOD-1/Aosp11 | train | 0 |
6d06dfa76d481a42a4d4e363a4f85fda0667bbfc | [
"super().__init__()\nself.sqrtk = math.sqrt(1 / input_features)\nself.weights = nTensor(tensor=empty(size=(output_features, input_features)).uniform_(-self.sqrtk, self.sqrtk))\nself.biasbool = biasbool\nif self.biasbool:\n self.bias = nTensor(tensor=empty(size=(output_features,)).uniform_(-self.sqrtk, self.sqrtk... | <|body_start_0|>
super().__init__()
self.sqrtk = math.sqrt(1 / input_features)
self.weights = nTensor(tensor=empty(size=(output_features, input_features)).uniform_(-self.sqrtk, self.sqrtk))
self.biasbool = biasbool
if self.biasbool:
self.bias = nTensor(tensor=empty(si... | Module that applies a linear transformation Description: - OUT = IN * W^T + B, where * is in general a matrix multiplication - inherits from the Module base class Attributes: sqrtk: double The square root of (1 / input_features) Used to sample the the values of the weights and the bias weights (W): nTensor, shape D_{L}... | Linear | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linear:
"""Module that applies a linear transformation Description: - OUT = IN * W^T + B, where * is in general a matrix multiplication - inherits from the Module base class Attributes: sqrtk: double The square root of (1 / input_features) Used to sample the the values of the weights and the bias... | stack_v2_sparse_classes_75kplus_train_007001 | 4,674 | no_license | [
{
"docstring": "Parameters: input_features: int Number of input units output_features: int Number of output units biasbool: bool If true the bias is also used If false only the weights are used Description: - the bias and the weights are initially sampled from a uniform distribution with the variance inversely ... | 4 | null | Implement the Python class `Linear` described below.
Class description:
Module that applies a linear transformation Description: - OUT = IN * W^T + B, where * is in general a matrix multiplication - inherits from the Module base class Attributes: sqrtk: double The square root of (1 / input_features) Used to sample the... | Implement the Python class `Linear` described below.
Class description:
Module that applies a linear transformation Description: - OUT = IN * W^T + B, where * is in general a matrix multiplication - inherits from the Module base class Attributes: sqrtk: double The square root of (1 / input_features) Used to sample the... | 8c2ecfc5ebfa789c2f5304e11b1889eb8fb55f43 | <|skeleton|>
class Linear:
"""Module that applies a linear transformation Description: - OUT = IN * W^T + B, where * is in general a matrix multiplication - inherits from the Module base class Attributes: sqrtk: double The square root of (1 / input_features) Used to sample the the values of the weights and the bias... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Linear:
"""Module that applies a linear transformation Description: - OUT = IN * W^T + B, where * is in general a matrix multiplication - inherits from the Module base class Attributes: sqrtk: double The square root of (1 / input_features) Used to sample the the values of the weights and the bias weights (W):... | the_stack_v2_python_sparse | Proj2/dl/linear.py | dforero0896/DeepLearningProjects | train | 0 |
a62f6f85aded9fbdd42645329ecf0ab96b05126e | [
"self.name = name\nself.source = source\nself.help = help\nself.mode = mode if mode is not None else 'i'\nself.native = native if native is not None else 'optional'\nself.host = host\nself.args = args if args is not None else []\nself.params = params if params is not None else []\nself.ignores = ignores if ignores ... | <|body_start_0|>
self.name = name
self.source = source
self.help = help
self.mode = mode if mode is not None else 'i'
self.native = native if native is not None else 'optional'
self.host = host
self.args = args if args is not None else []
self.params = par... | Job Class Config class that defines a job in a Skelebot project via the config yaml file | Job | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Job:
"""Job Class Config class that defines a job in a Skelebot project via the config yaml file"""
def __init__(self, name=None, source=None, mode=None, native=None, host=None, help=None, args=None, params=None, ignores=None, mappings=None, ports=None):
"""Initialize the job object ... | stack_v2_sparse_classes_75kplus_train_007002 | 2,924 | permissive | [
{
"docstring": "Initialize the job object with all provided optional attributes",
"name": "__init__",
"signature": "def __init__(self, name=None, source=None, mode=None, native=None, host=None, help=None, args=None, params=None, ignores=None, mappings=None, ports=None)"
},
{
"docstring": "Define... | 2 | stack_v2_sparse_classes_30k_train_010346 | Implement the Python class `Job` described below.
Class description:
Job Class Config class that defines a job in a Skelebot project via the config yaml file
Method signatures and docstrings:
- def __init__(self, name=None, source=None, mode=None, native=None, host=None, help=None, args=None, params=None, ignores=Non... | Implement the Python class `Job` described below.
Class description:
Job Class Config class that defines a job in a Skelebot project via the config yaml file
Method signatures and docstrings:
- def __init__(self, name=None, source=None, mode=None, native=None, host=None, help=None, args=None, params=None, ignores=Non... | c4299702994cdd55738de4591e85f4dc2a424d19 | <|skeleton|>
class Job:
"""Job Class Config class that defines a job in a Skelebot project via the config yaml file"""
def __init__(self, name=None, source=None, mode=None, native=None, host=None, help=None, args=None, params=None, ignores=None, mappings=None, ports=None):
"""Initialize the job object ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Job:
"""Job Class Config class that defines a job in a Skelebot project via the config yaml file"""
def __init__(self, name=None, source=None, mode=None, native=None, host=None, help=None, args=None, params=None, ignores=None, mappings=None, ports=None):
"""Initialize the job object with all prov... | the_stack_v2_python_sparse | skelebot/objects/job.py | carsdotcom/skelebot | train | 37 |
324e4a110c5e79ca8f6e92ff0587e2daac808dbb | [
"re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])\nresult = re\nAssertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])",
"re = MonthTicketBill(userLogin).batchOpenMonthTicketBill(send_da... | <|body_start_0|>
re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])
result = re
Assertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])
<|end_body_0|>
<|body_start_1|>
... | 批量开通月票,开通后在页面可以查看到导入的月票,车辆进出是月票 | TestBatchOpenMonthTicket | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBatchOpenMonthTicket:
"""批量开通月票,开通后在页面可以查看到导入的月票,车辆进出是月票"""
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
<|body_0|>
def test_batchOpenMonthTicketBill(self, userLogin, send_data, expect):
"""批量开通月票"""
<|body_1|>... | stack_v2_sparse_classes_75kplus_train_007003 | 2,728 | no_license | [
{
"docstring": "创建自定义月票类型",
"name": "test_createMonthTicketConfig",
"signature": "def test_createMonthTicketConfig(self, userLogin, send_data, expect)"
},
{
"docstring": "批量开通月票",
"name": "test_batchOpenMonthTicketBill",
"signature": "def test_batchOpenMonthTicketBill(self, userLogin, se... | 5 | stack_v2_sparse_classes_30k_train_043621 | Implement the Python class `TestBatchOpenMonthTicket` described below.
Class description:
批量开通月票,开通后在页面可以查看到导入的月票,车辆进出是月票
Method signatures and docstrings:
- def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型
- def test_batchOpenMonthTicketBill(self, userLogin, send_data, expect): 批量开通月票
... | Implement the Python class `TestBatchOpenMonthTicket` described below.
Class description:
批量开通月票,开通后在页面可以查看到导入的月票,车辆进出是月票
Method signatures and docstrings:
- def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型
- def test_batchOpenMonthTicketBill(self, userLogin, send_data, expect): 批量开通月票
... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestBatchOpenMonthTicket:
"""批量开通月票,开通后在页面可以查看到导入的月票,车辆进出是月票"""
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
<|body_0|>
def test_batchOpenMonthTicketBill(self, userLogin, send_data, expect):
"""批量开通月票"""
<|body_1|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestBatchOpenMonthTicket:
"""批量开通月票,开通后在页面可以查看到导入的月票,车辆进出是月票"""
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], sen... | the_stack_v2_python_sparse | test_suite/parkingManage/monthTicket/test_batchOpenMonthTicket.py | oyebino/pomp_api | train | 1 |
004549d5c69f906d099f6de0b39e3dc97d5f592c | [
"if isinstance(key, int):\n return Group(key)\nif key not in Group._member_map_:\n extend_enum(Group, key, default)\nreturn Group[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 12 <= value <= 255:\n extend_enum(cls,... | <|body_start_0|>
if isinstance(key, int):
return Group(key)
if key not in Group._member_map_:
extend_enum(Group, key, default)
return Group[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
raise ValueError('%... | [Group] Group IDs | Group | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Group:
"""[Group] Group IDs"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if isinsta... | stack_v2_sparse_classes_75kplus_train_007004 | 1,654 | permissive | [
{
"docstring": "Backport support for original codes.",
"name": "get",
"signature": "def get(key, default=-1)"
},
{
"docstring": "Lookup function used when value is not found.",
"name": "_missing_",
"signature": "def _missing_(cls, value)"
}
] | 2 | null | Implement the Python class `Group` described below.
Class description:
[Group] Group IDs
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found. | Implement the Python class `Group` described below.
Class description:
[Group] Group IDs
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found.
<|skeleton|>
class Group:
"""[Group] Group IDs"""
... | 71363d7948003fec88cedcf5bc80b6befa2ba244 | <|skeleton|>
class Group:
"""[Group] Group IDs"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Group:
"""[Group] Group IDs"""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Group(key)
if key not in Group._member_map_:
extend_enum(Group, key, default)
return Group[key]
def _missing_(cl... | the_stack_v2_python_sparse | pcapkit/const/hip/group.py | hiok2000/PyPCAPKit | train | 0 |
879ffbc10241dc43f05e36ca9cfd1218cf97d636 | [
"self._recursive = recursive\nnop = lambda: None\nskip = lambda arg: None\nself.link_callback = skip\nself.link_content_callback = skip\nself.ext_link_callback = skip\nself.redirect_callback = skip\nself.error_callback = skip\nself.nonhtml_callback = skip\nself.stop_callback = nop\nself.ext_link_test = have_same_ba... | <|body_start_0|>
self._recursive = recursive
nop = lambda: None
skip = lambda arg: None
self.link_callback = skip
self.link_content_callback = skip
self.ext_link_callback = skip
self.redirect_callback = skip
self.error_callback = skip
self.nonhtml_... | URL-redirects crawler | LinkCrawler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkCrawler:
"""URL-redirects crawler"""
def __init__(self, recursive=True):
"""Constructor"""
<|body_0|>
def process(self, url):
"""Iterate the external links from url"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self._recursive = recursive
... | stack_v2_sparse_classes_75kplus_train_007005 | 2,502 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, recursive=True)"
},
{
"docstring": "Iterate the external links from url",
"name": "process",
"signature": "def process(self, url)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036097 | Implement the Python class `LinkCrawler` described below.
Class description:
URL-redirects crawler
Method signatures and docstrings:
- def __init__(self, recursive=True): Constructor
- def process(self, url): Iterate the external links from url | Implement the Python class `LinkCrawler` described below.
Class description:
URL-redirects crawler
Method signatures and docstrings:
- def __init__(self, recursive=True): Constructor
- def process(self, url): Iterate the external links from url
<|skeleton|>
class LinkCrawler:
"""URL-redirects crawler"""
def... | aab6927de8424f0a8e9eb9b9a462a775555a80d5 | <|skeleton|>
class LinkCrawler:
"""URL-redirects crawler"""
def __init__(self, recursive=True):
"""Constructor"""
<|body_0|>
def process(self, url):
"""Iterate the external links from url"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinkCrawler:
"""URL-redirects crawler"""
def __init__(self, recursive=True):
"""Constructor"""
self._recursive = recursive
nop = lambda: None
skip = lambda arg: None
self.link_callback = skip
self.link_content_callback = skip
self.ext_link_callback ... | the_stack_v2_python_sparse | lib/core/crawler.py | Silentsoul04/gtta-scripts | train | 0 |
421b264ed83f666dc9998d21f67a5b38a797eba7 | [
"def target1(x, pattern: BaseGeometry, pos: BaseGeometry):\n params = _TargetTransformParams(x[0], x[1], x[2], x[3])\n pos_trans = _target_affine_transform(pos, params)\n pos_overlap = pattern.intersection(pos_trans).area\n false_pos_overlap = pos_trans.difference(pattern).area\n return false_pos_ove... | <|body_start_0|>
def target1(x, pattern: BaseGeometry, pos: BaseGeometry):
params = _TargetTransformParams(x[0], x[1], x[2], x[3])
pos_trans = _target_affine_transform(pos, params)
pos_overlap = pattern.intersection(pos_trans).area
false_pos_overlap = pos_trans.di... | Aligner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Aligner:
def align(self, pattern: BaseGeometry, pos: BaseGeometry) -> TransformMatrix:
"""this method try to apply an affine transformation on pos, so the overlap between pattern and pos is maximized :param pattern: keep-it-still background :param pos: a shape we try to align it with pat... | stack_v2_sparse_classes_75kplus_train_007006 | 6,594 | no_license | [
{
"docstring": "this method try to apply an affine transformation on pos, so the overlap between pattern and pos is maximized :param pattern: keep-it-still background :param pos: a shape we try to align it with pattern :return: transformation parameters",
"name": "align",
"signature": "def align(self, p... | 2 | stack_v2_sparse_classes_30k_train_006712 | Implement the Python class `Aligner` described below.
Class description:
Implement the Aligner class.
Method signatures and docstrings:
- def align(self, pattern: BaseGeometry, pos: BaseGeometry) -> TransformMatrix: this method try to apply an affine transformation on pos, so the overlap between pattern and pos is ma... | Implement the Python class `Aligner` described below.
Class description:
Implement the Aligner class.
Method signatures and docstrings:
- def align(self, pattern: BaseGeometry, pos: BaseGeometry) -> TransformMatrix: this method try to apply an affine transformation on pos, so the overlap between pattern and pos is ma... | 86446637d87077388b318ce9be7317139b5e5428 | <|skeleton|>
class Aligner:
def align(self, pattern: BaseGeometry, pos: BaseGeometry) -> TransformMatrix:
"""this method try to apply an affine transformation on pos, so the overlap between pattern and pos is maximized :param pattern: keep-it-still background :param pos: a shape we try to align it with pat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Aligner:
def align(self, pattern: BaseGeometry, pos: BaseGeometry) -> TransformMatrix:
"""this method try to apply an affine transformation on pos, so the overlap between pattern and pos is maximized :param pattern: keep-it-still background :param pos: a shape we try to align it with pattern :return: ... | the_stack_v2_python_sparse | backend/prototype/shape_match.py | snowdmonkey/solar | train | 1 | |
8bae2b500ef7a250788418aa839f3f86f5b11fe9 | [
"analog_tile = analog_ctx.analog_tile\nctx.analog_ctx = analog_ctx\nctx.shared_weights = None\nctx.save_for_backward(input_)\nuse_indexed = analog_ctx.use_indexed\nif shared_weights is not None:\n ctx.shared_weights = shared_weights\n analog_tile.ensure_shared_weights(shared_weights)\n analog_ctx.use_torch... | <|body_start_0|>
analog_tile = analog_ctx.analog_tile
ctx.analog_ctx = analog_ctx
ctx.shared_weights = None
ctx.save_for_backward(input_)
use_indexed = analog_ctx.use_indexed
if shared_weights is not None:
ctx.shared_weights = shared_weights
analog... | Base function for analog functions. | AnalogFunctionBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalogFunctionBase:
"""Base function for analog functions."""
def forward(ctx: Any, analog_ctx: AnalogContext, input_: Tensor, shared_weights: Optional[Tensor]=None, is_test: bool=False) -> Tensor:
"""Execute the forward pass in the analog tile. Note: Indexed versions can used when a... | stack_v2_sparse_classes_75kplus_train_007007 | 4,591 | permissive | [
{
"docstring": "Execute the forward pass in the analog tile. Note: Indexed versions can used when analog_ctx.use_indexed is set to True.",
"name": "forward",
"signature": "def forward(ctx: Any, analog_ctx: AnalogContext, input_: Tensor, shared_weights: Optional[Tensor]=None, is_test: bool=False) -> Tens... | 2 | stack_v2_sparse_classes_30k_test_001721 | Implement the Python class `AnalogFunctionBase` described below.
Class description:
Base function for analog functions.
Method signatures and docstrings:
- def forward(ctx: Any, analog_ctx: AnalogContext, input_: Tensor, shared_weights: Optional[Tensor]=None, is_test: bool=False) -> Tensor: Execute the forward pass i... | Implement the Python class `AnalogFunctionBase` described below.
Class description:
Base function for analog functions.
Method signatures and docstrings:
- def forward(ctx: Any, analog_ctx: AnalogContext, input_: Tensor, shared_weights: Optional[Tensor]=None, is_test: bool=False) -> Tensor: Execute the forward pass i... | 06ac4bdd0b8769a383840d485f0467f2da0e6106 | <|skeleton|>
class AnalogFunctionBase:
"""Base function for analog functions."""
def forward(ctx: Any, analog_ctx: AnalogContext, input_: Tensor, shared_weights: Optional[Tensor]=None, is_test: bool=False) -> Tensor:
"""Execute the forward pass in the analog tile. Note: Indexed versions can used when a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnalogFunctionBase:
"""Base function for analog functions."""
def forward(ctx: Any, analog_ctx: AnalogContext, input_: Tensor, shared_weights: Optional[Tensor]=None, is_test: bool=False) -> Tensor:
"""Execute the forward pass in the analog tile. Note: Indexed versions can used when analog_ctx.use... | the_stack_v2_python_sparse | src/aihwkit/nn/functions.py | AMPIC/aihwkit | train | 0 |
239407e5449690bd558dfd226d7a2e11f21c2c7b | [
"username = form.data.get('username', '')\npassword = form.data.get('password', '')\nemail = form.data.get('email', '')\nif User.objects.filter(username=username):\n return render(self.request, 'utils/error_page.html', {'message': '该用户名已被占用'})\nuser = User.objects.create_user(username=username, email=email, pass... | <|body_start_0|>
username = form.data.get('username', '')
password = form.data.get('password', '')
email = form.data.get('email', '')
if User.objects.filter(username=username):
return render(self.request, 'utils/error_page.html', {'message': '该用户名已被占用'})
user = User.o... | The View when the user click signup | SignupView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignupView:
"""The View when the user click signup"""
def form_valid(self, form):
"""When the user submit the form and it's valid. :param form: the form from the frontend :return: super"""
<|body_0|>
def form_invalid(self, form):
"""When the user submit the form ... | stack_v2_sparse_classes_75kplus_train_007008 | 5,382 | no_license | [
{
"docstring": "When the user submit the form and it's valid. :param form: the form from the frontend :return: super",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "When the user submit the form and it's not valid. :param form: the form from the frontend :ret... | 2 | stack_v2_sparse_classes_30k_train_028435 | Implement the Python class `SignupView` described below.
Class description:
The View when the user click signup
Method signatures and docstrings:
- def form_valid(self, form): When the user submit the form and it's valid. :param form: the form from the frontend :return: super
- def form_invalid(self, form): When the ... | Implement the Python class `SignupView` described below.
Class description:
The View when the user click signup
Method signatures and docstrings:
- def form_valid(self, form): When the user submit the form and it's valid. :param form: the form from the frontend :return: super
- def form_invalid(self, form): When the ... | 8a3aebe005e1850fc741b6302b6abcd4cde902be | <|skeleton|>
class SignupView:
"""The View when the user click signup"""
def form_valid(self, form):
"""When the user submit the form and it's valid. :param form: the form from the frontend :return: super"""
<|body_0|>
def form_invalid(self, form):
"""When the user submit the form ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SignupView:
"""The View when the user click signup"""
def form_valid(self, form):
"""When the user submit the form and it's valid. :param form: the form from the frontend :return: super"""
username = form.data.get('username', '')
password = form.data.get('password', '')
em... | the_stack_v2_python_sparse | authentication/views.py | taoxinyi/ProCampus | train | 0 |
377aa05d2969f0b05dadbe738af09245b9d8181e | [
"p1 = ListNode(None)\np1.next = l1\np2 = ListNode(None)\np2.next = l2\nr = rp = ListNode(None)\nwhile p1.next != None or p2.next != None:\n if p1.next != None and p2.next != None:\n if p1.next.val < p2.next.val:\n r.val = p1.next.val\n r.next = ListNode(None)\n r = r.next\... | <|body_start_0|>
p1 = ListNode(None)
p1.next = l1
p2 = ListNode(None)
p2.next = l2
r = rp = ListNode(None)
while p1.next != None or p2.next != None:
if p1.next != None and p2.next != None:
if p1.next.val < p2.next.val:
r.val... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_007009 | 2,047 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, ... | 2 | stack_v2_sparse_classes_30k_train_015596 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
... | ef1c3bae0f6b1087df51530ba2322cfc9c970cde | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
p1 = ListNode(None)
p1.next = l1
p2 = ListNode(None)
p2.next = l2
r = rp = ListNode(None)
while p1.next != None or p2.next != None:
if p1.... | the_stack_v2_python_sparse | Leetcode/LeetCode0/21. Merge Two Sorted Lists.py | liugingko/LeetCode-Python | train | 0 | |
dd652d73f620d43c586af21026428b0d24b7ca2d | [
"empty_result = [0] * len(coins)\nif amount == 0:\n return empty_result\nbest = [-1] * len(coins)\nfor idx, coin in enumerate(coins):\n if amount >= coin:\n tmp = self.changeCoin_rec(amount - coin, coins)\n tmp[idx] += 1\n if sum(best) < 0 or sum(tmp) < sum(best):\n best = tmp\... | <|body_start_0|>
empty_result = [0] * len(coins)
if amount == 0:
return empty_result
best = [-1] * len(coins)
for idx, coin in enumerate(coins):
if amount >= coin:
tmp = self.changeCoin_rec(amount - coin, coins)
tmp[idx] += 1
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def changeCoin_rec(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def changeCoin_dp(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
def coinChange(self, co... | stack_v2_sparse_classes_75kplus_train_007010 | 2,200 | permissive | [
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "changeCoin_rec",
"signature": "def changeCoin_rec(self, coins, amount)"
},
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "changeCoin_dp",
"signature": "def changeCoin_dp(self,... | 3 | stack_v2_sparse_classes_30k_val_001771 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def changeCoin_rec(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def changeCoin_dp(self, coins, amount): :type coins: List[int] :type amount: int :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def changeCoin_rec(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def changeCoin_dp(self, coins, amount): :type coins: List[int] :type amount: int :... | f462b66ae849f4332a4b150f206dd49c7519e83b | <|skeleton|>
class Solution:
def changeCoin_rec(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def changeCoin_dp(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
def coinChange(self, co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def changeCoin_rec(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
empty_result = [0] * len(coins)
if amount == 0:
return empty_result
best = [-1] * len(coins)
for idx, coin in enumerate(coins):
if amoun... | the_stack_v2_python_sparse | Practice/DP/Easy_Coin_Change.py | hooyao/Coding-Py3 | train | 0 | |
406a695068149c4bc87f611bf748e9c2fcabd7cc | [
"tmp = self.head.next\nself.head.next = node\nnode.prev = self.head\nnode.next = tmp\ntmp.prev = node",
"node.prev.next = node.next\nnode.next.prev = node.prev\nnode.prev = node.next = None",
"self.cap = capacity\nself.cnt = 0\nself.key_to_node = {}\nself.head = Node(None, None)\nself.tail = Node(None, None)\ns... | <|body_start_0|>
tmp = self.head.next
self.head.next = node
node.prev = self.head
node.next = tmp
tmp.prev = node
<|end_body_0|>
<|body_start_1|>
node.prev.next = node.next
node.next.prev = node.prev
node.prev = node.next = None
<|end_body_1|>
<|body_sta... | Wrong. | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
"""Wrong."""
def addNode(self, node):
"""Add a node after head of the list"""
<|body_0|>
def removeNode(self, node):
"""Remove a node from the list"""
<|body_1|>
def __init__(self, capacity):
""":type capacity: int"""
<|body... | stack_v2_sparse_classes_75kplus_train_007011 | 9,208 | no_license | [
{
"docstring": "Add a node after head of the list",
"name": "addNode",
"signature": "def addNode(self, node)"
},
{
"docstring": "Remove a node from the list",
"name": "removeNode",
"signature": "def removeNode(self, node)"
},
{
"docstring": ":type capacity: int",
"name": "__i... | 5 | stack_v2_sparse_classes_30k_val_002726 | Implement the Python class `LRUCache` described below.
Class description:
Wrong.
Method signatures and docstrings:
- def addNode(self, node): Add a node after head of the list
- def removeNode(self, node): Remove a node from the list
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: in... | Implement the Python class `LRUCache` described below.
Class description:
Wrong.
Method signatures and docstrings:
- def addNode(self, node): Add a node after head of the list
- def removeNode(self, node): Remove a node from the list
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: in... | d634941087bc51869f43c0d8044db09b7bdbaf58 | <|skeleton|>
class LRUCache:
"""Wrong."""
def addNode(self, node):
"""Add a node after head of the list"""
<|body_0|>
def removeNode(self, node):
"""Remove a node from the list"""
<|body_1|>
def __init__(self, capacity):
""":type capacity: int"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
"""Wrong."""
def addNode(self, node):
"""Add a node after head of the list"""
tmp = self.head.next
self.head.next = node
node.prev = self.head
node.next = tmp
tmp.prev = node
def removeNode(self, node):
"""Remove a node from the list"... | the_stack_v2_python_sparse | 146_LRU_Cache.py | susunini/leetcode | train | 1 |
26fd1620375708d42c0a199aeecb129995def3ba | [
"self.grad_log_q = grad_log_q\nassert proposal_sig > 0\nself.proposal_sig = proposal_sig\nif seed is None:\n seed = np.random.randint(100000)\nself.rng = np.random.default_rng(seed)",
"assert x.shape == gaussian_rvs.shape == uniform_rvs.shape\nz = gaussian_rvs * self.proposal_sig\ngrad_x = self.grad_log_q(x)\n... | <|body_start_0|>
self.grad_log_q = grad_log_q
assert proposal_sig > 0
self.proposal_sig = proposal_sig
if seed is None:
seed = np.random.randint(100000)
self.rng = np.random.default_rng(seed)
<|end_body_0|>
<|body_start_1|>
assert x.shape == gaussian_rvs.shap... | BarkerProposal | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BarkerProposal:
def __init__(self, grad_log_q, proposal_sig=0.001, seed=None):
"""Robust gradient-informed proposal distribution. Supports: * sampling from proposal y ~ p(. | x) * evaluation of proposal density p(y | x) Compared to Langevin proposals, more robust to poor initialization a... | stack_v2_sparse_classes_75kplus_train_007012 | 1,972 | permissive | [
{
"docstring": "Robust gradient-informed proposal distribution. Supports: * sampling from proposal y ~ p(. | x) * evaluation of proposal density p(y | x) Compared to Langevin proposals, more robust to poor initialization and to poor choice of step size. References ---------- [Livingstone, Zanella, 2020] The Bar... | 4 | stack_v2_sparse_classes_30k_train_049976 | Implement the Python class `BarkerProposal` described below.
Class description:
Implement the BarkerProposal class.
Method signatures and docstrings:
- def __init__(self, grad_log_q, proposal_sig=0.001, seed=None): Robust gradient-informed proposal distribution. Supports: * sampling from proposal y ~ p(. | x) * evalu... | Implement the Python class `BarkerProposal` described below.
Class description:
Implement the BarkerProposal class.
Method signatures and docstrings:
- def __init__(self, grad_log_q, proposal_sig=0.001, seed=None): Robust gradient-informed proposal distribution. Supports: * sampling from proposal y ~ p(. | x) * evalu... | b853c2d287da0d1c1babb963eaec8fda41539b90 | <|skeleton|>
class BarkerProposal:
def __init__(self, grad_log_q, proposal_sig=0.001, seed=None):
"""Robust gradient-informed proposal distribution. Supports: * sampling from proposal y ~ p(. | x) * evaluation of proposal density p(y | x) Compared to Langevin proposals, more robust to poor initialization a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BarkerProposal:
def __init__(self, grad_log_q, proposal_sig=0.001, seed=None):
"""Robust gradient-informed proposal distribution. Supports: * sampling from proposal y ~ p(. | x) * evaluation of proposal density p(y | x) Compared to Langevin proposals, more robust to poor initialization and to poor cho... | the_stack_v2_python_sparse | timemachine/md/barker.py | proteneer/timemachine | train | 132 | |
1819944daf7d6ea7089c3aeeec620a5e0901788a | [
"Block.__init__(self, scenario, args)\nif self.language is None:\n raise LoadingException('Language must be defined!')\nself.lexicon = Lexicon()",
"anodes = aroot.get_descendants(ordered=True)\nfor aleft, aright in zip(anodes[:-1], anodes[1:]):\n if aleft.clause_number == aright.clause_number:\n cont... | <|body_start_0|>
Block.__init__(self, scenario, args)
if self.language is None:
raise LoadingException('Language must be defined!')
self.lexicon = Lexicon()
<|end_body_0|>
<|body_start_1|>
anodes = aroot.get_descendants(ordered=True)
for aleft, aright in zip(anodes[:... | Add commas separating subordinate clauses. Arguments: language: the language of the target tree selector: the selector of the target tree | AddSubordClausePunct | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddSubordClausePunct:
"""Add commas separating subordinate clauses. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
<|body_0|>
def p... | stack_v2_sparse_classes_75kplus_train_007013 | 4,725 | permissive | [
{
"docstring": "Constructor, just checking the argument values",
"name": "__init__",
"signature": "def __init__(self, scenario, args)"
},
{
"docstring": "Add subordinate clause punctuation to the given sentence.",
"name": "process_atree",
"signature": "def process_atree(self, aroot)"
}... | 5 | null | Implement the Python class `AddSubordClausePunct` described below.
Class description:
Add commas separating subordinate clauses. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario, args): Constructor, just chec... | Implement the Python class `AddSubordClausePunct` described below.
Class description:
Add commas separating subordinate clauses. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario, args): Constructor, just chec... | 73af644ec35c8a1cd0c37cd478c2afc1db717e0b | <|skeleton|>
class AddSubordClausePunct:
"""Add commas separating subordinate clauses. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
<|body_0|>
def p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddSubordClausePunct:
"""Add commas separating subordinate clauses. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
Block.__init__(self, scenario, arg... | the_stack_v2_python_sparse | alex/components/nlg/tectotpl/block/t2a/cs/addsubordclausepunct.py | oplatek/alex | train | 0 |
7c083965d9c593cc5611e07778410c8f0e3bf067 | [
"super().__init__(listRef.localControlRef)\nif not isinstance(nodes, list):\n nodes = [nodes]\nself.addBranch = addBranch\nself.treeFormats = None\nif treeFormats:\n self.treeFormats = copy.deepcopy(treeFormats)\nfor parent in nodes:\n if addBranch:\n for node in parent.descendantGen():\n ... | <|body_start_0|>
super().__init__(listRef.localControlRef)
if not isinstance(nodes, list):
nodes = [nodes]
self.addBranch = addBranch
self.treeFormats = None
if treeFormats:
self.treeFormats = copy.deepcopy(treeFormats)
for parent in nodes:
... | Info for undo/redo of tree node child data and lists. | ChildDataUndo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChildDataUndo:
"""Info for undo/redo of tree node child data and lists."""
def __init__(self, listRef, nodes, addBranch=False, treeFormats=None, notRedo=True):
"""Create the child data undo class and add it to the undoStore. Arguments: listRef -- a ref to the undo/redo list this gets... | stack_v2_sparse_classes_75kplus_train_007014 | 17,816 | no_license | [
{
"docstring": "Create the child data undo class and add it to the undoStore. Arguments: listRef -- a ref to the undo/redo list this gets added to nodes -- a parent node or a list of parents to save children addBranch -- if True, include all branch nodes treeFormats -- the format data to store notRedo -- if Tru... | 2 | stack_v2_sparse_classes_30k_train_032013 | Implement the Python class `ChildDataUndo` described below.
Class description:
Info for undo/redo of tree node child data and lists.
Method signatures and docstrings:
- def __init__(self, listRef, nodes, addBranch=False, treeFormats=None, notRedo=True): Create the child data undo class and add it to the undoStore. Ar... | Implement the Python class `ChildDataUndo` described below.
Class description:
Info for undo/redo of tree node child data and lists.
Method signatures and docstrings:
- def __init__(self, listRef, nodes, addBranch=False, treeFormats=None, notRedo=True): Create the child data undo class and add it to the undoStore. Ar... | c9429496e8ed15116746a23f3a90f262cf54f755 | <|skeleton|>
class ChildDataUndo:
"""Info for undo/redo of tree node child data and lists."""
def __init__(self, listRef, nodes, addBranch=False, treeFormats=None, notRedo=True):
"""Create the child data undo class and add it to the undoStore. Arguments: listRef -- a ref to the undo/redo list this gets... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChildDataUndo:
"""Info for undo/redo of tree node child data and lists."""
def __init__(self, listRef, nodes, addBranch=False, treeFormats=None, notRedo=True):
"""Create the child data undo class and add it to the undoStore. Arguments: listRef -- a ref to the undo/redo list this gets added to nod... | the_stack_v2_python_sparse | source/undo.py | doug-101/TreeLine | train | 121 |
1c167d7a407a586d34d00d8b82634e28c27759a0 | [
"self.line_search = LineSearch(c1, c2, beta, tol)\nself.tad = TorchAutoDiff()\nself.f_all = []",
"x_k = x0\nfor k in range(maxit):\n self.f_all.append(fun(x_k).detach().numpy())\n grad_k = self.tad.compute_gradient(fun, x_k)\n if use_btls:\n alpha_k = self.line_search.btls(fun, x_k, -grad_k, grad_... | <|body_start_0|>
self.line_search = LineSearch(c1, c2, beta, tol)
self.tad = TorchAutoDiff()
self.f_all = []
<|end_body_0|>
<|body_start_1|>
x_k = x0
for k in range(maxit):
self.f_all.append(fun(x_k).detach().numpy())
grad_k = self.tad.compute_gradient(fu... | SteepestDescent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SteepestDescent:
def __init__(self, c1, c2, beta, tol=1e-05):
"""Implementation of the steepest descent algorithm Input: c1 : parameter used for line search wolfe condition 1 c2 : parameter used for line search wolfe condition 2 beta : used in back tracking line search tol : value to che... | stack_v2_sparse_classes_75kplus_train_007015 | 2,463 | no_license | [
{
"docstring": "Implementation of the steepest descent algorithm Input: c1 : parameter used for line search wolfe condition 1 c2 : parameter used for line search wolfe condition 2 beta : used in back tracking line search tol : value to check equality condition (refer to line search for details)",
"name": "_... | 3 | stack_v2_sparse_classes_30k_train_049625 | Implement the Python class `SteepestDescent` described below.
Class description:
Implement the SteepestDescent class.
Method signatures and docstrings:
- def __init__(self, c1, c2, beta, tol=1e-05): Implementation of the steepest descent algorithm Input: c1 : parameter used for line search wolfe condition 1 c2 : para... | Implement the Python class `SteepestDescent` described below.
Class description:
Implement the SteepestDescent class.
Method signatures and docstrings:
- def __init__(self, c1, c2, beta, tol=1e-05): Implementation of the steepest descent algorithm Input: c1 : parameter used for line search wolfe condition 1 c2 : para... | 160f6bcef64d17c622fb9cb017bd4faa65afd858 | <|skeleton|>
class SteepestDescent:
def __init__(self, c1, c2, beta, tol=1e-05):
"""Implementation of the steepest descent algorithm Input: c1 : parameter used for line search wolfe condition 1 c2 : parameter used for line search wolfe condition 2 beta : used in back tracking line search tol : value to che... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SteepestDescent:
def __init__(self, c1, c2, beta, tol=1e-05):
"""Implementation of the steepest descent algorithm Input: c1 : parameter used for line search wolfe condition 1 c2 : parameter used for line search wolfe condition 2 beta : used in back tracking line search tol : value to check equality co... | the_stack_v2_python_sparse | python/py_solvers/unconstrained/gradient_descent.py | avadesh02/Non-Linear-Optimization-Solvers-Package | train | 4 | |
d91e25ba3d7bf1ea9de39615468b2c32f048c0dd | [
"try:\n with codecs.open(filename, 'r', sg.__encoding__) as fp:\n line = fp.readline()\n fp.close()\nexcept IOError:\n return False\nexcept UnicodeDecodeError:\n return False\ntab = line.split()\nif len(tab) < 2:\n return False\ntry:\n int(line[0])\nexcept ValueError:\n return False\... | <|body_start_0|>
try:
with codecs.open(filename, 'r', sg.__encoding__) as fp:
line = fp.readline()
fp.close()
except IOError:
return False
except UnicodeDecodeError:
return False
tab = line.split()
if len(tab) < ... | SPPAS LAB reader and writer. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Each line of a HTK label file contains the actual label optionally preceded by start and end times, an... | sppasLab | [
"GPL-3.0-only",
"MIT",
"GFDL-1.1-or-later",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sppasLab:
"""SPPAS LAB reader and writer. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Each line of a HTK label file contains the actual label optionally... | stack_v2_sparse_classes_75kplus_train_007016 | 9,938 | permissive | [
{
"docstring": "Check whether a file is of HTK-Lab format or not. :param filename: (str) Name of the file to check. :returns: (bool)",
"name": "detect",
"signature": "def detect(filename)"
},
{
"docstring": "Initialize a new sppasLab instance. :param name: (str) This transcription name.",
"n... | 4 | stack_v2_sparse_classes_30k_train_020096 | Implement the Python class `sppasLab` described below.
Class description:
SPPAS LAB reader and writer. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Each line of a HTK label fi... | Implement the Python class `sppasLab` described below.
Class description:
SPPAS LAB reader and writer. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Each line of a HTK label fi... | 3167b65f576abcc27a8767d24c274a04712bd948 | <|skeleton|>
class sppasLab:
"""SPPAS LAB reader and writer. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Each line of a HTK label file contains the actual label optionally... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class sppasLab:
"""SPPAS LAB reader and writer. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Each line of a HTK label file contains the actual label optionally preceded by ... | the_stack_v2_python_sparse | sppas/sppas/src/anndata/aio/htk.py | mirfan899/MTTS | train | 0 |
3700795e461fc6fe69f9a790c9dbf7f4e7092827 | [
"self.name = res_name\nself.num = res_num\nself._mol_name = None\nself._mol_index = None\nself._res_index = None\nself.spin = SpinList()",
"text = 'Class containing all the residue specific data.\\n'\ntext = text + '\\n'\ntext = text + 'Objects:\\n'\nfor name in dir(self):\n if name == 'spin':\n text = ... | <|body_start_0|>
self.name = res_name
self.num = res_num
self._mol_name = None
self._mol_index = None
self._res_index = None
self.spin = SpinList()
<|end_body_0|>
<|body_start_1|>
text = 'Class containing all the residue specific data.\n'
text = text + '\... | Class containing all the residue specific data. | ResidueContainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidueContainer:
"""Class containing all the residue specific data."""
def __init__(self, res_name=None, res_num=None):
"""Set up the default objects of the residue data container."""
<|body_0|>
def __repr__(self):
"""The string representation of the object. Rat... | stack_v2_sparse_classes_75kplus_train_007017 | 28,677 | no_license | [
{
"docstring": "Set up the default objects of the residue data container.",
"name": "__init__",
"signature": "def __init__(self, res_name=None, res_num=None)"
},
{
"docstring": "The string representation of the object. Rather than using the standard Python conventions (either the string represen... | 3 | null | Implement the Python class `ResidueContainer` described below.
Class description:
Class containing all the residue specific data.
Method signatures and docstrings:
- def __init__(self, res_name=None, res_num=None): Set up the default objects of the residue data container.
- def __repr__(self): The string representati... | Implement the Python class `ResidueContainer` described below.
Class description:
Class containing all the residue specific data.
Method signatures and docstrings:
- def __init__(self, res_name=None, res_num=None): Set up the default objects of the residue data container.
- def __repr__(self): The string representati... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class ResidueContainer:
"""Class containing all the residue specific data."""
def __init__(self, res_name=None, res_num=None):
"""Set up the default objects of the residue data container."""
<|body_0|>
def __repr__(self):
"""The string representation of the object. Rat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResidueContainer:
"""Class containing all the residue specific data."""
def __init__(self, res_name=None, res_num=None):
"""Set up the default objects of the residue data container."""
self.name = res_name
self.num = res_num
self._mol_name = None
self._mol_index = ... | the_stack_v2_python_sparse | data_store/mol_res_spin.py | jlec/relax | train | 4 |
72ac4cab352c2ee31abf5d482f8648441449d867 | [
"matches = Courses.objects.filter(courseCode=courseCode)\nif not matches:\n return ERR_NO_RECORD_FOUND\ncourse = matches[0]\nreturn course",
"matches = Courses.objects.filter(courseCode=courseCode)\nif matches.count() == 0:\n return ERR_NO_RECORD_FOUND\ncourse = matches[0]\nreturn course.maxUnit"
] | <|body_start_0|>
matches = Courses.objects.filter(courseCode=courseCode)
if not matches:
return ERR_NO_RECORD_FOUND
course = matches[0]
return course
<|end_body_0|>
<|body_start_1|>
matches = Courses.objects.filter(courseCode=courseCode)
if matches.count() ==... | Courses | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Courses:
def getCourseInfo(courseCode):
"""Returns Courses object given course code Args: courseCode (str): The name of the course, i.e COMPSCI.169 Returns: (Courses) course object corresponding to course code (ERR_NO_RECORD_FOUND) if course name was not valid"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_007018 | 25,281 | no_license | [
{
"docstring": "Returns Courses object given course code Args: courseCode (str): The name of the course, i.e COMPSCI.169 Returns: (Courses) course object corresponding to course code (ERR_NO_RECORD_FOUND) if course name was not valid",
"name": "getCourseInfo",
"signature": "def getCourseInfo(courseCode)... | 2 | stack_v2_sparse_classes_30k_train_038133 | Implement the Python class `Courses` described below.
Class description:
Implement the Courses class.
Method signatures and docstrings:
- def getCourseInfo(courseCode): Returns Courses object given course code Args: courseCode (str): The name of the course, i.e COMPSCI.169 Returns: (Courses) course object correspondi... | Implement the Python class `Courses` described below.
Class description:
Implement the Courses class.
Method signatures and docstrings:
- def getCourseInfo(courseCode): Returns Courses object given course code Args: courseCode (str): The name of the course, i.e COMPSCI.169 Returns: (Courses) course object correspondi... | 0317019870e8f0319412b8d2cae84f2c3ec48286 | <|skeleton|>
class Courses:
def getCourseInfo(courseCode):
"""Returns Courses object given course code Args: courseCode (str): The name of the course, i.e COMPSCI.169 Returns: (Courses) course object corresponding to course code (ERR_NO_RECORD_FOUND) if course name was not valid"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Courses:
def getCourseInfo(courseCode):
"""Returns Courses object given course code Args: courseCode (str): The name of the course, i.e COMPSCI.169 Returns: (Courses) course object corresponding to course code (ERR_NO_RECORD_FOUND) if course name was not valid"""
matches = Courses.objects.filt... | the_stack_v2_python_sparse | darsplus/models.py | DanielKoohmarey/ThinkAhead | train | 0 | |
fd5afd07ad8325ff4df2f0d9a54f82b5bb11a342 | [
"if len(nums) == 0:\n return 0\nnums = [0] + nums\nf = [0 for _ in range(len(nums))]\nf[1] = nums[1]\nfor i in range(2, len(nums)):\n f[i] = max(nums[i] + f[i - 2], f[i - 1])\nreturn f[-1]",
"if len(nums) == 0:\n return 0\nif len(nums) == 1:\n return nums[0]\nreturn max(self.rob_origin(nums[1:]), self... | <|body_start_0|>
if len(nums) == 0:
return 0
nums = [0] + nums
f = [0 for _ in range(len(nums))]
f[1] = nums[1]
for i in range(2, len(nums)):
f[i] = max(nums[i] + f[i - 2], f[i - 1])
return f[-1]
<|end_body_0|>
<|body_start_1|>
if len(nums... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob_origin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 0:
return 0
nums =... | stack_v2_sparse_classes_75kplus_train_007019 | 743 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob_origin",
"signature": "def rob_origin(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000009 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob_origin(self, nums): :type nums: List[int] :rtype: int
- def rob(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob_origin(self, nums): :type nums: List[int] :rtype: int
- def rob(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob_origin(self, num... | c2b01374942dcba7fbbe7865d13d7599bbc083f3 | <|skeleton|>
class Solution:
def rob_origin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rob_origin(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 0:
return 0
nums = [0] + nums
f = [0 for _ in range(len(nums))]
f[1] = nums[1]
for i in range(2, len(nums)):
f[i] = max(nums[i] + f[i - 2], f[i ... | the_stack_v2_python_sparse | P0213.py | chenjiahui1991/LeetCode | train | 0 | |
4b32b87914d310bda0252a1927f9eb49ede9456b | [
"self.protection_source_environment = protection_source_environment\nself.protection_source_ids = protection_source_ids\nself.rpo_policy_id = rpo_policy_id",
"if dictionary is None:\n return None\nprotection_source_environment = dictionary.get('protectionSourceEnvironment')\nprotection_source_ids = dictionary.... | <|body_start_0|>
self.protection_source_environment = protection_source_environment
self.protection_source_ids = protection_source_ids
self.rpo_policy_id = rpo_policy_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
protection_source_environment ... | Implementation of the 'ProtectObjectParameters' model. Specifies the parameters to protect an object. Attributes: protection_source_environment (ProtectionSourceEnvironmentEnum): Specifies the environment type of the Protection Source object. Supported environment types such as 'kView', 'kSQL', 'kVMware', etc. NOTE: 'k... | ProtectObjectParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectObjectParameters:
"""Implementation of the 'ProtectObjectParameters' model. Specifies the parameters to protect an object. Attributes: protection_source_environment (ProtectionSourceEnvironmentEnum): Specifies the environment type of the Protection Source object. Supported environment type... | stack_v2_sparse_classes_75kplus_train_007020 | 6,100 | permissive | [
{
"docstring": "Constructor for the ProtectObjectParameters class",
"name": "__init__",
"signature": "def __init__(self, protection_source_environment=None, protection_source_ids=None, rpo_policy_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (d... | 2 | stack_v2_sparse_classes_30k_train_042016 | Implement the Python class `ProtectObjectParameters` described below.
Class description:
Implementation of the 'ProtectObjectParameters' model. Specifies the parameters to protect an object. Attributes: protection_source_environment (ProtectionSourceEnvironmentEnum): Specifies the environment type of the Protection So... | Implement the Python class `ProtectObjectParameters` described below.
Class description:
Implementation of the 'ProtectObjectParameters' model. Specifies the parameters to protect an object. Attributes: protection_source_environment (ProtectionSourceEnvironmentEnum): Specifies the environment type of the Protection So... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectObjectParameters:
"""Implementation of the 'ProtectObjectParameters' model. Specifies the parameters to protect an object. Attributes: protection_source_environment (ProtectionSourceEnvironmentEnum): Specifies the environment type of the Protection Source object. Supported environment type... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProtectObjectParameters:
"""Implementation of the 'ProtectObjectParameters' model. Specifies the parameters to protect an object. Attributes: protection_source_environment (ProtectionSourceEnvironmentEnum): Specifies the environment type of the Protection Source object. Supported environment types such as 'kV... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protect_object_parameters.py | cohesity/management-sdk-python | train | 24 |
b170e65acf005687357ec96a18b150c5c9e74663 | [
"if context is None:\n context = {}\nres = super(stock_return_picking, self).view_init(cr, uid, fields_list, context=context)\nrecord_id = context and context.get('active_id', False)\nif record_id:\n pick_obj = self.pool.get('stock.picking')\n pick = pick_obj.browse(cr, uid, record_id, context=context)\n ... | <|body_start_0|>
if context is None:
context = {}
res = super(stock_return_picking, self).view_init(cr, uid, fields_list, context=context)
record_id = context and context.get('active_id', False)
if record_id:
pick_obj = self.pool.get('stock.picking')
p... | stock_return_picking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_return_picking:
def view_init(self, cr, uid, fields_list, context=None):
"""Creates view dynamically and adding fields at runtime. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param context: A standard dictionary @ret... | stack_v2_sparse_classes_75kplus_train_007021 | 5,659 | no_license | [
{
"docstring": "Creates view dynamically and adding fields at runtime. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param context: A standard dictionary @return: New arch of view with new columns.",
"name": "view_init",
"signature": "def v... | 3 | stack_v2_sparse_classes_30k_train_023411 | Implement the Python class `stock_return_picking` described below.
Class description:
Implement the stock_return_picking class.
Method signatures and docstrings:
- def view_init(self, cr, uid, fields_list, context=None): Creates view dynamically and adding fields at runtime. @param self: The object pointer. @param cr... | Implement the Python class `stock_return_picking` described below.
Class description:
Implement the stock_return_picking class.
Method signatures and docstrings:
- def view_init(self, cr, uid, fields_list, context=None): Creates view dynamically and adding fields at runtime. @param self: The object pointer. @param cr... | d3daac105636ac4e146816232c616298dc5bb742 | <|skeleton|>
class stock_return_picking:
def view_init(self, cr, uid, fields_list, context=None):
"""Creates view dynamically and adding fields at runtime. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param context: A standard dictionary @ret... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class stock_return_picking:
def view_init(self, cr, uid, fields_list, context=None):
"""Creates view dynamically and adding fields at runtime. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param context: A standard dictionary @return: New arch ... | the_stack_v2_python_sparse | l10n_in_mrp_subcontract/wizard/stock_return_picking.py | Odoo-India/odoo-india | train | 10 | |
b0a5170e600d915e8edab2378afcb5f17b9fc8d9 | [
"super().__init__()\nself.device = device\nself.tok_embedding = nn.Embedding(num_embeddings=output_dim, embedding_dim=hid_dim)\nself.pos_embedding = nn.Embedding(num_embeddings=max_length, embedding_dim=hid_dim)\nself.layers = nn.ModuleList([GatedDecoderLayer(hid_dim, n_heads, pf_dim, dropout, device) for _ in rang... | <|body_start_0|>
super().__init__()
self.device = device
self.tok_embedding = nn.Embedding(num_embeddings=output_dim, embedding_dim=hid_dim)
self.pos_embedding = nn.Embedding(num_embeddings=max_length, embedding_dim=hid_dim)
self.layers = nn.ModuleList([GatedDecoderLayer(hid_dim,... | Decoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
def __init__(self, output_dim: int, hid_dim: int, n_layers: int, n_heads: int, pf_dim: int, dropout: float, device: str, max_length=100):
"""Decoder class for Gated Transformer which is similar to the Encoder but also has + mask multi-head attention layer over target sequence + ... | stack_v2_sparse_classes_75kplus_train_007022 | 8,786 | permissive | [
{
"docstring": "Decoder class for Gated Transformer which is similar to the Encoder but also has + mask multi-head attention layer over target sequence + multi-head attention layer which uses the decoder representation as the query zand the encoder representation as the key and value Parameters ---------- outpu... | 2 | stack_v2_sparse_classes_30k_val_001380 | Implement the Python class `Decoder` described below.
Class description:
Implement the Decoder class.
Method signatures and docstrings:
- def __init__(self, output_dim: int, hid_dim: int, n_layers: int, n_heads: int, pf_dim: int, dropout: float, device: str, max_length=100): Decoder class for Gated Transformer which ... | Implement the Python class `Decoder` described below.
Class description:
Implement the Decoder class.
Method signatures and docstrings:
- def __init__(self, output_dim: int, hid_dim: int, n_layers: int, n_heads: int, pf_dim: int, dropout: float, device: str, max_length=100): Decoder class for Gated Transformer which ... | a6c870d4ed0788f15cfdf58c85ed5201dff60ee9 | <|skeleton|>
class Decoder:
def __init__(self, output_dim: int, hid_dim: int, n_layers: int, n_heads: int, pf_dim: int, dropout: float, device: str, max_length=100):
"""Decoder class for Gated Transformer which is similar to the Encoder but also has + mask multi-head attention layer over target sequence + ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decoder:
def __init__(self, output_dim: int, hid_dim: int, n_layers: int, n_heads: int, pf_dim: int, dropout: float, device: str, max_length=100):
"""Decoder class for Gated Transformer which is similar to the Encoder but also has + mask multi-head attention layer over target sequence + multi-head att... | the_stack_v2_python_sparse | src/gated_transformers_nlp/utils/gated_transformers/decoder.py | mnguyen0226/gated_transformers_nlp | train | 2 | |
d95b20bc35b590862b7fead29f410e323c128069 | [
"driver = obj.driver\nWebDriverWait(driver, 100).until(lambda driver: driver.find_element(By.ID, obj.locator))\ndriver.find_element(By.ID, obj.locator()).clear()\ndriver.find_element(By.ID, obj.locator()).send_keys(value)",
"driver = obj.driver\nWebDriverWait(driver, 100).until(lambda driver: driver.find_element_... | <|body_start_0|>
driver = obj.driver
WebDriverWait(driver, 100).until(lambda driver: driver.find_element(By.ID, obj.locator))
driver.find_element(By.ID, obj.locator()).clear()
driver.find_element(By.ID, obj.locator()).send_keys(value)
<|end_body_0|>
<|body_start_1|>
driver = obj... | Base page class that is initialized on every page object class. | BasePageElement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasePageElement:
"""Base page class that is initialized on every page object class."""
def __set__(self, obj, value):
"""Sets the text to the value supplied"""
<|body_0|>
def __get__(self, obj, owner):
"""Gets the text of the specified object"""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_007023 | 1,331 | no_license | [
{
"docstring": "Sets the text to the value supplied",
"name": "__set__",
"signature": "def __set__(self, obj, value)"
},
{
"docstring": "Gets the text of the specified object",
"name": "__get__",
"signature": "def __get__(self, obj, owner)"
}
] | 2 | null | Implement the Python class `BasePageElement` described below.
Class description:
Base page class that is initialized on every page object class.
Method signatures and docstrings:
- def __set__(self, obj, value): Sets the text to the value supplied
- def __get__(self, obj, owner): Gets the text of the specified object | Implement the Python class `BasePageElement` described below.
Class description:
Base page class that is initialized on every page object class.
Method signatures and docstrings:
- def __set__(self, obj, value): Sets the text to the value supplied
- def __get__(self, obj, owner): Gets the text of the specified object... | 04ed30a2b89b4ec15d9e84f83c6da099e9b5c378 | <|skeleton|>
class BasePageElement:
"""Base page class that is initialized on every page object class."""
def __set__(self, obj, value):
"""Sets the text to the value supplied"""
<|body_0|>
def __get__(self, obj, owner):
"""Gets the text of the specified object"""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasePageElement:
"""Base page class that is initialized on every page object class."""
def __set__(self, obj, value):
"""Sets the text to the value supplied"""
driver = obj.driver
WebDriverWait(driver, 100).until(lambda driver: driver.find_element(By.ID, obj.locator))
driv... | the_stack_v2_python_sparse | PYTHON_PATH/Py_0/Page_Obj_Docum.py | Ruslanindze/Auto_Tester | train | 1 |
1104099e67c7aab03e383f51abd0bb50b28196a4 | [
"if password == '':\n raise serializers.ValidationError(_('fill the password field'))\nreturn password",
"username = data.get('username')\npassword = self.validate_password(data.get('password'))\ntry:\n user = User.objects.get(username=username)\nexcept User.DoesNotExist:\n raise serializers.ValidationEr... | <|body_start_0|>
if password == '':
raise serializers.ValidationError(_('fill the password field'))
return password
<|end_body_0|>
<|body_start_1|>
username = data.get('username')
password = self.validate_password(data.get('password'))
try:
user = User.ob... | Serializer for user login. | LoginSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginSerializer:
"""Serializer for user login."""
def validate_password(self, password):
"""Check password validation."""
<|body_0|>
def validate(self, data):
"""Validation on both of the fields."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i... | stack_v2_sparse_classes_75kplus_train_007024 | 1,296 | no_license | [
{
"docstring": "Check password validation.",
"name": "validate_password",
"signature": "def validate_password(self, password)"
},
{
"docstring": "Validation on both of the fields.",
"name": "validate",
"signature": "def validate(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002116 | Implement the Python class `LoginSerializer` described below.
Class description:
Serializer for user login.
Method signatures and docstrings:
- def validate_password(self, password): Check password validation.
- def validate(self, data): Validation on both of the fields. | Implement the Python class `LoginSerializer` described below.
Class description:
Serializer for user login.
Method signatures and docstrings:
- def validate_password(self, password): Check password validation.
- def validate(self, data): Validation on both of the fields.
<|skeleton|>
class LoginSerializer:
"""Se... | 74c9eba52b4f47d60fad17b6cba874e3547b37d4 | <|skeleton|>
class LoginSerializer:
"""Serializer for user login."""
def validate_password(self, password):
"""Check password validation."""
<|body_0|>
def validate(self, data):
"""Validation on both of the fields."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoginSerializer:
"""Serializer for user login."""
def validate_password(self, password):
"""Check password validation."""
if password == '':
raise serializers.ValidationError(_('fill the password field'))
return password
def validate(self, data):
"""Valida... | the_stack_v2_python_sparse | apps/registration/serializers.py | cisin-python/django-rest-sample | train | 0 |
03109b7d29d8603eb2903950e3e02145a66905cd | [
"raw = self.session.get(f'{self.host}/{id}')\nsoup = self.soup(raw)\nmeta = self.MetaSet()\nmeta['judul'] = soup.find(class_='entry-title').text\nif (infox := soup.find(class_='cat_box_desc')):\n meta.register('(?si){id}\\\\s*:\\\\s*([^>]+?)\\\\s*?\\\\n', infox.text)\n meta.setItem('status')\n meta.setItem... | <|body_start_0|>
raw = self.session.get(f'{self.host}/{id}')
soup = self.soup(raw)
meta = self.MetaSet()
meta['judul'] = soup.find(class_='entry-title').text
if (infox := soup.find(class_='cat_box_desc')):
meta.register('(?si){id}\\s*:\\s*([^>]+?)\\s*?\\n', infox.text... | Animeindo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Animeindo:
def extract_meta(self, id: str) -> dict:
"""Ambil semua metadata dari halaman web Args: id: type 'str'"""
<|body_0|>
def extract_data(self, id: str) -> dict:
"""Ambil semua situs unduhan dari halaman web Args: id: jalur url dimulai setelah host, type 'str'... | stack_v2_sparse_classes_75kplus_train_007025 | 3,246 | permissive | [
{
"docstring": "Ambil semua metadata dari halaman web Args: id: type 'str'",
"name": "extract_meta",
"signature": "def extract_meta(self, id: str) -> dict"
},
{
"docstring": "Ambil semua situs unduhan dari halaman web Args: id: jalur url dimulai setelah host, type 'str'",
"name": "extract_da... | 3 | stack_v2_sparse_classes_30k_train_014950 | Implement the Python class `Animeindo` described below.
Class description:
Implement the Animeindo class.
Method signatures and docstrings:
- def extract_meta(self, id: str) -> dict: Ambil semua metadata dari halaman web Args: id: type 'str'
- def extract_data(self, id: str) -> dict: Ambil semua situs unduhan dari ha... | Implement the Python class `Animeindo` described below.
Class description:
Implement the Animeindo class.
Method signatures and docstrings:
- def extract_meta(self, id: str) -> dict: Ambil semua metadata dari halaman web Args: id: type 'str'
- def extract_data(self, id: str) -> dict: Ambil semua situs unduhan dari ha... | 7aef096a6fd549ae7ab11092470609518371b10a | <|skeleton|>
class Animeindo:
def extract_meta(self, id: str) -> dict:
"""Ambil semua metadata dari halaman web Args: id: type 'str'"""
<|body_0|>
def extract_data(self, id: str) -> dict:
"""Ambil semua situs unduhan dari halaman web Args: id: jalur url dimulai setelah host, type 'str'... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Animeindo:
def extract_meta(self, id: str) -> dict:
"""Ambil semua metadata dari halaman web Args: id: type 'str'"""
raw = self.session.get(f'{self.host}/{id}')
soup = self.soup(raw)
meta = self.MetaSet()
meta['judul'] = soup.find(class_='entry-title').text
if (... | the_stack_v2_python_sparse | lk21/extractors/animeindo.py | JawsKen98/lk21 | train | 0 | |
bd48d14b7a153ca5a323fbbad7dc30161407ee8d | [
"runs = compat_run.GetRuns(source=compat_run.Sources.LOCAL)\nsites = compat_site.GetSites()\nverifications = verification.GetVerificationSteps()\nlast_added = {'run': self.GetOptionalParameter('run'), 'site': self.GetOptionalParameter('site'), 'verification': self.GetOptionalParameter('verification')}\nselected_bro... | <|body_start_0|>
runs = compat_run.GetRuns(source=compat_run.Sources.LOCAL)
sites = compat_site.GetSites()
verifications = verification.GetVerificationSteps()
last_added = {'run': self.GetOptionalParameter('run'), 'site': self.GetOptionalParameter('site'), 'verification': self.GetOptiona... | Handler used to manage the Site Compatibility mappings. | MappingsHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MappingsHandler:
"""Handler used to manage the Site Compatibility mappings."""
def get(self):
"""Gets the mappings view."""
<|body_0|>
def post(self):
"""Adds a new mapping."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
runs = compat_run.GetRu... | stack_v2_sparse_classes_75kplus_train_007026 | 22,297 | permissive | [
{
"docstring": "Gets the mappings view.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Adds a new mapping.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `MappingsHandler` described below.
Class description:
Handler used to manage the Site Compatibility mappings.
Method signatures and docstrings:
- def get(self): Gets the mappings view.
- def post(self): Adds a new mapping. | Implement the Python class `MappingsHandler` described below.
Class description:
Handler used to manage the Site Compatibility mappings.
Method signatures and docstrings:
- def get(self): Gets the mappings view.
- def post(self): Adds a new mapping.
<|skeleton|>
class MappingsHandler:
"""Handler used to manage t... | 1b3a86ed01d7d47d20166d49b090d846cc98aa66 | <|skeleton|>
class MappingsHandler:
"""Handler used to manage the Site Compatibility mappings."""
def get(self):
"""Gets the mappings view."""
<|body_0|>
def post(self):
"""Adds a new mapping."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MappingsHandler:
"""Handler used to manage the Site Compatibility mappings."""
def get(self):
"""Gets the mappings view."""
runs = compat_run.GetRuns(source=compat_run.Sources.LOCAL)
sites = compat_site.GetSites()
verifications = verification.GetVerificationSteps()
... | the_stack_v2_python_sparse | server/handlers/site_compat.py | adambyram/bite-project-mod | train | 1 |
7b2bf09a4a2459b665fd981f14ebdaa76a0eb394 | [
"if isinstance(template, str):\n template = URITemplate(template)\nself.template = template\nself.permission = permission\nself.params = params\nself.when = when\nsuper().__init__(**kwargs)",
"factory = self.context.get('links_factory')\nfield_permission_check = self.context.get('field_permission_check')\nif f... | <|body_start_0|>
if isinstance(template, str):
template = URITemplate(template)
self.template = template
self.permission = permission
self.params = params
self.when = when
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
factory = self.conte... | A link field that knows how to generate a link from an object. | Link | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Link:
"""A link field that knows how to generate a link from an object."""
def __init__(self, template=None, params=None, permission=None, when=always, **kwargs):
"""Constructor."""
<|body_0|>
def _serialize(self, value, attr, obj, *args, **kwargs):
"""Dump the l... | stack_v2_sparse_classes_75kplus_train_007027 | 2,104 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, template=None, params=None, permission=None, when=always, **kwargs)"
},
{
"docstring": "Dump the link by using the context.",
"name": "_serialize",
"signature": "def _serialize(self, value, attr, obj, *ar... | 2 | stack_v2_sparse_classes_30k_train_049064 | Implement the Python class `Link` described below.
Class description:
A link field that knows how to generate a link from an object.
Method signatures and docstrings:
- def __init__(self, template=None, params=None, permission=None, when=always, **kwargs): Constructor.
- def _serialize(self, value, attr, obj, *args, ... | Implement the Python class `Link` described below.
Class description:
A link field that knows how to generate a link from an object.
Method signatures and docstrings:
- def __init__(self, template=None, params=None, permission=None, when=always, **kwargs): Constructor.
- def _serialize(self, value, attr, obj, *args, ... | 84386a1e9131171a0dcc37868970797082245fa9 | <|skeleton|>
class Link:
"""A link field that knows how to generate a link from an object."""
def __init__(self, template=None, params=None, permission=None, when=always, **kwargs):
"""Constructor."""
<|body_0|>
def _serialize(self, value, attr, obj, *args, **kwargs):
"""Dump the l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Link:
"""A link field that knows how to generate a link from an object."""
def __init__(self, template=None, params=None, permission=None, when=always, **kwargs):
"""Constructor."""
if isinstance(template, str):
template = URITemplate(template)
self.template = template... | the_stack_v2_python_sparse | marshmallow_utils/fields/links.py | fenekku/marshmallow-utils | train | 0 |
1004163f0580ebb4d564f04b4588972c282be92b | [
"output = []\nfor n in nums:\n if nums[abs(n) - 1] < 0:\n output.append(abs(n))\n else:\n nums[abs(n) - 1] *= -1\nreturn output",
"for i in range(len(nums)):\n nums[abs(nums[i]) - 1] *= -1\nprint(nums)\nreturn []"
] | <|body_start_0|>
output = []
for n in nums:
if nums[abs(n) - 1] < 0:
output.append(abs(n))
else:
nums[abs(n) - 1] *= -1
return output
<|end_body_0|>
<|body_start_1|>
for i in range(len(nums)):
nums[abs(nums[i]) - 1] *= ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicates(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findDuplicates_failed(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
output = []
... | stack_v2_sparse_classes_75kplus_train_007028 | 1,527 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findDuplicates",
"signature": "def findDuplicates(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findDuplicates_failed",
"signature": "def findDuplicates_failed(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicates(self, nums): :type nums: List[int] :rtype: List[int]
- def findDuplicates_failed(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicates(self, nums): :type nums: List[int] :rtype: List[int]
- def findDuplicates_failed(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class Solut... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def findDuplicates(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findDuplicates_failed(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findDuplicates(self, nums):
""":type nums: List[int] :rtype: List[int]"""
output = []
for n in nums:
if nums[abs(n) - 1] < 0:
output.append(abs(n))
else:
nums[abs(n) - 1] *= -1
return output
def findDupl... | the_stack_v2_python_sparse | src/lt_442.py | oxhead/CodingYourWay | train | 0 | |
21f7838cfbd440f9daf548efdcfb9d74272817e9 | [
"if not root:\n return []\nresult = []\nbfs = [root]\nwhile bfs:\n tmp_r = [node.val for node in bfs if node]\n if tmp_r:\n result.append(tmp_r)\n tmp_bfs = []\n for node in bfs:\n if node:\n tmp_bfs.append(node.left)\n tmp_bfs.append(node.right)\n bfs = tmp_bfs... | <|body_start_0|>
if not root:
return []
result = []
bfs = [root]
while bfs:
tmp_r = [node.val for node in bfs if node]
if tmp_r:
result.append(tmp_r)
tmp_bfs = []
for node in bfs:
if node:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def rewrite(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
def rewrite2(self, root):
""":type root: TreeNode :rtype: L... | stack_v2_sparse_classes_75kplus_train_007029 | 2,420 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrder",
"signature": "def levelOrder(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "rewrite",
"signature": "def rewrite(self, root)"
},
{
"docstring": ":type root... | 3 | stack_v2_sparse_classes_30k_train_036645 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def rewrite(self, root): :type root: TreeNode :rtype: List[List[int]]
- def rewrite2(self, root): :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def rewrite(self, root): :type root: TreeNode :rtype: List[List[int]]
- def rewrite2(self, root): :type... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def rewrite(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
def rewrite2(self, root):
""":type root: TreeNode :rtype: L... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
if not root:
return []
result = []
bfs = [root]
while bfs:
tmp_r = [node.val for node in bfs if node]
if tmp_r:
result.append(tmp... | the_stack_v2_python_sparse | co_fb/102_Binary_Tree_Level_Order_Traversal.py | vsdrun/lc_public | train | 6 | |
51e8396df0a638a0a9f13cb76a4e8bde6f7005d0 | [
"with db.engine.raw_connection().cursor(MySQLdb.cursors.DictCursor) as cursor:\n cursor.callproc('getTeams')\n results = cursor.fetchall()\nreturn (results, 200)",
"data = request.json\nconnection = db.engine.raw_connection()\ntry:\n with connection.cursor(MySQLdb.cursors.DictCursor) as cursor:\n ... | <|body_start_0|>
with db.engine.raw_connection().cursor(MySQLdb.cursors.DictCursor) as cursor:
cursor.callproc('getTeams')
results = cursor.fetchall()
return (results, 200)
<|end_body_0|>
<|body_start_1|>
data = request.json
connection = db.engine.raw_connection(... | Manipulations with teams. | TeamList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamList:
"""Manipulations with teams."""
def get(self):
"""Gets all teams Use Case: This endpoint can be used by a client to see a list of all teams in the league."""
<|body_0|>
def post(self):
"""Adds a new team Use Case: This endpoint can be used by an admin t... | stack_v2_sparse_classes_75kplus_train_007030 | 2,899 | no_license | [
{
"docstring": "Gets all teams Use Case: This endpoint can be used by a client to see a list of all teams in the league.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Adds a new team Use Case: This endpoint can be used by an admin to create a new team record. The endpoint chec... | 2 | stack_v2_sparse_classes_30k_train_053538 | Implement the Python class `TeamList` described below.
Class description:
Manipulations with teams.
Method signatures and docstrings:
- def get(self): Gets all teams Use Case: This endpoint can be used by a client to see a list of all teams in the league.
- def post(self): Adds a new team Use Case: This endpoint can ... | Implement the Python class `TeamList` described below.
Class description:
Manipulations with teams.
Method signatures and docstrings:
- def get(self): Gets all teams Use Case: This endpoint can be used by a client to see a list of all teams in the league.
- def post(self): Adds a new team Use Case: This endpoint can ... | 9b1852a5ba9cd8203f179bd43e3af498865f8389 | <|skeleton|>
class TeamList:
"""Manipulations with teams."""
def get(self):
"""Gets all teams Use Case: This endpoint can be used by a client to see a list of all teams in the league."""
<|body_0|>
def post(self):
"""Adds a new team Use Case: This endpoint can be used by an admin t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeamList:
"""Manipulations with teams."""
def get(self):
"""Gets all teams Use Case: This endpoint can be used by a client to see a list of all teams in the league."""
with db.engine.raw_connection().cursor(MySQLdb.cursors.DictCursor) as cursor:
cursor.callproc('getTeams')
... | the_stack_v2_python_sparse | resources/team.py | ryan-holt/FootballAnalytics | train | 0 |
17889c6eb7e0816b84fdf03be8a221891bcb466e | [
"res = []\n\ndef dfs(node, count):\n if not node:\n return\n count = count * 10 + node.val if count else node.val\n if not node.left and (not node.right):\n res.append(count)\n return\n dfs(node.left, count)\n dfs(node.right, count)\n return res\ndfs(root, 0)\nreturn sum(res)"... | <|body_start_0|>
res = []
def dfs(node, count):
if not node:
return
count = count * 10 + node.val if count else node.val
if not node.left and (not node.right):
res.append(count)
return
dfs(node.left, count)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumNumbers1(self, root: TreeNode) -> int:
"""递归记录每条path,最后结算"""
<|body_0|>
def sumNumbers2(self, root: TreeNode) -> int:
"""利用队列,每次将当前结点及其sum入队"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
def dfs(node, count):
... | stack_v2_sparse_classes_75kplus_train_007031 | 1,818 | no_license | [
{
"docstring": "递归记录每条path,最后结算",
"name": "sumNumbers1",
"signature": "def sumNumbers1(self, root: TreeNode) -> int"
},
{
"docstring": "利用队列,每次将当前结点及其sum入队",
"name": "sumNumbers2",
"signature": "def sumNumbers2(self, root: TreeNode) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_020682 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers1(self, root: TreeNode) -> int: 递归记录每条path,最后结算
- def sumNumbers2(self, root: TreeNode) -> int: 利用队列,每次将当前结点及其sum入队 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers1(self, root: TreeNode) -> int: 递归记录每条path,最后结算
- def sumNumbers2(self, root: TreeNode) -> int: 利用队列,每次将当前结点及其sum入队
<|skeleton|>
class Solution:
def sumNumber... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def sumNumbers1(self, root: TreeNode) -> int:
"""递归记录每条path,最后结算"""
<|body_0|>
def sumNumbers2(self, root: TreeNode) -> int:
"""利用队列,每次将当前结点及其sum入队"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sumNumbers1(self, root: TreeNode) -> int:
"""递归记录每条path,最后结算"""
res = []
def dfs(node, count):
if not node:
return
count = count * 10 + node.val if count else node.val
if not node.left and (not node.right):
... | the_stack_v2_python_sparse | 129_sum-root-to-leaf-numbers.py | helloocc/algorithm | train | 1 | |
9b598f467b9969ec07bb85877170609f4431188a | [
"if N <= 1:\n return N\nif N == 2:\n return 1\nprev1 = 1\nprev2 = 1\nfor i in range(2, N + 1):\n prev1, prev2 = (prev1 + prev2, prev1)\nreturn prev1",
"if N <= 1:\n return N\nreturn self.fib(N - 1) + self.fib(N - 2)"
] | <|body_start_0|>
if N <= 1:
return N
if N == 2:
return 1
prev1 = 1
prev2 = 1
for i in range(2, N + 1):
prev1, prev2 = (prev1 + prev2, prev1)
return prev1
<|end_body_0|>
<|body_start_1|>
if N <= 1:
return N
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fib2(self, N: int) -> int:
"""递推 时间复杂度: O(N) 空间复杂度: O(1) Args: N: Returns:"""
<|body_0|>
def fib(self, N: int) -> int:
"""递归 时间复杂度 O(2^N) 空间复杂度 O(N) Args: N: Returns:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if N <= 1:
... | stack_v2_sparse_classes_75kplus_train_007032 | 1,011 | no_license | [
{
"docstring": "递推 时间复杂度: O(N) 空间复杂度: O(1) Args: N: Returns:",
"name": "fib2",
"signature": "def fib2(self, N: int) -> int"
},
{
"docstring": "递归 时间复杂度 O(2^N) 空间复杂度 O(N) Args: N: Returns:",
"name": "fib",
"signature": "def fib(self, N: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_030528 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fib2(self, N: int) -> int: 递推 时间复杂度: O(N) 空间复杂度: O(1) Args: N: Returns:
- def fib(self, N: int) -> int: 递归 时间复杂度 O(2^N) 空间复杂度 O(N) Args: N: Returns: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fib2(self, N: int) -> int: 递推 时间复杂度: O(N) 空间复杂度: O(1) Args: N: Returns:
- def fib(self, N: int) -> int: 递归 时间复杂度 O(2^N) 空间复杂度 O(N) Args: N: Returns:
<|skeleton|>
class Solut... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def fib2(self, N: int) -> int:
"""递推 时间复杂度: O(N) 空间复杂度: O(1) Args: N: Returns:"""
<|body_0|>
def fib(self, N: int) -> int:
"""递归 时间复杂度 O(2^N) 空间复杂度 O(N) Args: N: Returns:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def fib2(self, N: int) -> int:
"""递推 时间复杂度: O(N) 空间复杂度: O(1) Args: N: Returns:"""
if N <= 1:
return N
if N == 2:
return 1
prev1 = 1
prev2 = 1
for i in range(2, N + 1):
prev1, prev2 = (prev1 + prev2, prev1)
re... | the_stack_v2_python_sparse | leetcode/509_斐波拉契数.py | tenqaz/crazy_arithmetic | train | 0 | |
a70464a3379fe4159330522ebad3e9fbb0b1c11a | [
"self.context = util.grabcontext(context)\nself.queue = cl.CommandQueue(self.context)\nself.setshapes(dstshape, srcshape)\nsrc = '\\n'.join(open(self._kernel, 'r').readlines())\nself.prog = cl.Program(self.context, src).build()",
"if len(dstshape) != len(srcshape):\n raise ValueError('Source and destination sh... | <|body_start_0|>
self.context = util.grabcontext(context)
self.queue = cl.CommandQueue(self.context)
self.setshapes(dstshape, srcshape)
src = '\n'.join(open(self._kernel, 'r').readlines())
self.prog = cl.Program(self.context, src).build()
<|end_body_0|>
<|body_start_1|>
... | Use OpenCL on a GPU device to linearly interpolate or rotate a 2-D image of complex float values. | InterpolatingRotator | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpolatingRotator:
"""Use OpenCL on a GPU device to linearly interpolate or rotate a 2-D image of complex float values."""
def __init__(self, dstshape, srcshape, context=None):
"""Build an OpenCL kernel that will interpolate an image with shape srcshape (which should be a tuple wi... | stack_v2_sparse_classes_75kplus_train_007033 | 7,323 | permissive | [
{
"docstring": "Build an OpenCL kernel that will interpolate an image with shape srcshape (which should be a tuple with 2 elements) into an image with shape dstshape.",
"name": "__init__",
"signature": "def __init__(self, dstshape, srcshape, context=None)"
},
{
"docstring": "Set the destination ... | 4 | stack_v2_sparse_classes_30k_train_046519 | Implement the Python class `InterpolatingRotator` described below.
Class description:
Use OpenCL on a GPU device to linearly interpolate or rotate a 2-D image of complex float values.
Method signatures and docstrings:
- def __init__(self, dstshape, srcshape, context=None): Build an OpenCL kernel that will interpolate... | Implement the Python class `InterpolatingRotator` described below.
Class description:
Use OpenCL on a GPU device to linearly interpolate or rotate a 2-D image of complex float values.
Method signatures and docstrings:
- def __init__(self, dstshape, srcshape, context=None): Build an OpenCL kernel that will interpolate... | 5fabc9c1f410bf49b674bfb4427fe1f05ad251ed | <|skeleton|>
class InterpolatingRotator:
"""Use OpenCL on a GPU device to linearly interpolate or rotate a 2-D image of complex float values."""
def __init__(self, dstshape, srcshape, context=None):
"""Build an OpenCL kernel that will interpolate an image with shape srcshape (which should be a tuple wi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterpolatingRotator:
"""Use OpenCL on a GPU device to linearly interpolate or rotate a 2-D image of complex float values."""
def __init__(self, dstshape, srcshape, context=None):
"""Build an OpenCL kernel that will interpolate an image with shape srcshape (which should be a tuple with 2 elements... | the_stack_v2_python_sparse | pycwp/cltools/interpolators.py | ahesford/pycwp | train | 0 |
df5413e371cde324fe343f5724628601072f41a2 | [
"self.__src = src\nself.__contains_classes = contains_classes\nself.__has_header = has_header\nself._read_data()",
"data = pd.read_csv(self.__src, header=None if self.__has_header is False else 'infer')\nheader = data.columns\nif self.__contains_classes:\n self._y = data.pop(header[len(header) - 1])\nself._x =... | <|body_start_0|>
self.__src = src
self.__contains_classes = contains_classes
self.__has_header = has_header
self._read_data()
<|end_body_0|>
<|body_start_1|>
data = pd.read_csv(self.__src, header=None if self.__has_header is False else 'infer')
header = data.columns
... | Implementation of CSV data reader. Date: 2020 Author: Luka Pečnik License: MIT Attributes: __src (string): Path to a CSV file. __contains_classes (bool): Tells if src contains expected classification results or only features. __has_header (bool): Tells if src contains header row. See Also: * :class:`niaaml.data.DataRea... | CSVDataReader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSVDataReader:
"""Implementation of CSV data reader. Date: 2020 Author: Luka Pečnik License: MIT Attributes: __src (string): Path to a CSV file. __contains_classes (bool): Tells if src contains expected classification results or only features. __has_header (bool): Tells if src contains header row... | stack_v2_sparse_classes_75kplus_train_007034 | 1,460 | permissive | [
{
"docstring": "Set the parameters of the algorithm. Arguments: src (string): Path to a CSV dataset file. contains_classes (Optional[bool]): Tells if src contains expected classification results or only features. has_header (Optional[bool]): Tells if src contains header row.",
"name": "_set_parameters",
... | 2 | stack_v2_sparse_classes_30k_train_008779 | Implement the Python class `CSVDataReader` described below.
Class description:
Implementation of CSV data reader. Date: 2020 Author: Luka Pečnik License: MIT Attributes: __src (string): Path to a CSV file. __contains_classes (bool): Tells if src contains expected classification results or only features. __has_header (... | Implement the Python class `CSVDataReader` described below.
Class description:
Implementation of CSV data reader. Date: 2020 Author: Luka Pečnik License: MIT Attributes: __src (string): Path to a CSV file. __contains_classes (bool): Tells if src contains expected classification results or only features. __has_header (... | 12feffb97985b2180ee7a74b28b91336c60b301f | <|skeleton|>
class CSVDataReader:
"""Implementation of CSV data reader. Date: 2020 Author: Luka Pečnik License: MIT Attributes: __src (string): Path to a CSV file. __contains_classes (bool): Tells if src contains expected classification results or only features. __has_header (bool): Tells if src contains header row... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CSVDataReader:
"""Implementation of CSV data reader. Date: 2020 Author: Luka Pečnik License: MIT Attributes: __src (string): Path to a CSV file. __contains_classes (bool): Tells if src contains expected classification results or only features. __has_header (bool): Tells if src contains header row. See Also: *... | the_stack_v2_python_sparse | niaaml/data/csv_data_reader.py | lukapecnik/NiaAML | train | 26 |
048e76cd3ea080874795d7e3bb91da1fb054a093 | [
"assert window_size > 0, 'window_size must be greater than 0'\nassert max_gap >= 0, 'max_gap must be positive (or zero)'\nself.window_size = window_size\nself.max_gap = max_gap\nself.rms = None",
"coords = []\nfor chain in sorted(structure.get_chains()):\n for resid in sorted(chain, key=_RESID_SORTER):\n ... | <|body_start_0|>
assert window_size > 0, 'window_size must be greater than 0'
assert max_gap >= 0, 'max_gap must be positive (or zero)'
self.window_size = window_size
self.max_gap = max_gap
self.rms = None
<|end_body_0|>
<|body_start_1|>
coords = []
for chain in ... | Protein Structure Alignment by Combinatorial Extension. | CEAligner | [
"BSD-3-Clause",
"LicenseRef-scancode-biopython"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CEAligner:
"""Protein Structure Alignment by Combinatorial Extension."""
def __init__(self, window_size=8, max_gap=30):
"""Superimpose one set of atoms onto another using structural data. Structures are superimposed using guide atoms, CA and C4', for protein and nucleic acid molecule... | stack_v2_sparse_classes_75kplus_train_007035 | 5,513 | permissive | [
{
"docstring": "Superimpose one set of atoms onto another using structural data. Structures are superimposed using guide atoms, CA and C4', for protein and nucleic acid molecules respectively. Parameters ---------- window_size : float, optional CE algorithm parameter. Used to define paths when building the CE s... | 4 | null | Implement the Python class `CEAligner` described below.
Class description:
Protein Structure Alignment by Combinatorial Extension.
Method signatures and docstrings:
- def __init__(self, window_size=8, max_gap=30): Superimpose one set of atoms onto another using structural data. Structures are superimposed using guide... | Implement the Python class `CEAligner` described below.
Class description:
Protein Structure Alignment by Combinatorial Extension.
Method signatures and docstrings:
- def __init__(self, window_size=8, max_gap=30): Superimpose one set of atoms onto another using structural data. Structures are superimposed using guide... | d416809344f1e345fbabbdaca4dd6dcf441e53bd | <|skeleton|>
class CEAligner:
"""Protein Structure Alignment by Combinatorial Extension."""
def __init__(self, window_size=8, max_gap=30):
"""Superimpose one set of atoms onto another using structural data. Structures are superimposed using guide atoms, CA and C4', for protein and nucleic acid molecule... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CEAligner:
"""Protein Structure Alignment by Combinatorial Extension."""
def __init__(self, window_size=8, max_gap=30):
"""Superimpose one set of atoms onto another using structural data. Structures are superimposed using guide atoms, CA and C4', for protein and nucleic acid molecules respectivel... | the_stack_v2_python_sparse | Bio/PDB/cealign.py | biopython/biopython | train | 3,669 |
7b6630ecc4d5c2af67b8a905e06a27d774e66a0e | [
"invB = smooth_pinv(B, sqrt(smooth) * L)\nL = L[:, None]\nF = F[:, None]\nself._fit_matrix = F * L / (8 * np.pi) * invB",
"data = data[..., self._where_dwi]\ndata = data.clip(self.min, self.max)\nloglog_data = np.log(-np.log(data))\nsh_coef = dot(loglog_data, self._fit_matrix.T)\nsh_coef[..., 0] = self._n0_const\... | <|body_start_0|>
invB = smooth_pinv(B, sqrt(smooth) * L)
L = L[:, None]
F = F[:, None]
self._fit_matrix = F * L / (8 * np.pi) * invB
<|end_body_0|>
<|body_start_1|>
data = data[..., self._where_dwi]
data = data.clip(self.min, self.max)
loglog_data = np.log(-np.lo... | Implementation of Constant Solid Angle reconstruction method. References ---------- .. [1] Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging With Solid Angle Consideration. | CsaOdfModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CsaOdfModel:
"""Implementation of Constant Solid Angle reconstruction method. References ---------- .. [1] Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging With Solid Angle Consideration."""
def _set_fit_matrix(self, B, L, F, smooth):
"""The fit matrix, is used by fit_coe... | stack_v2_sparse_classes_75kplus_train_007036 | 39,407 | permissive | [
{
"docstring": "The fit matrix, is used by fit_coefficients to return the coefficients of the odf",
"name": "_set_fit_matrix",
"signature": "def _set_fit_matrix(self, B, L, F, smooth)"
},
{
"docstring": "Returns the coefficients of the model",
"name": "_get_shm_coef",
"signature": "def _... | 2 | null | Implement the Python class `CsaOdfModel` described below.
Class description:
Implementation of Constant Solid Angle reconstruction method. References ---------- .. [1] Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging With Solid Angle Consideration.
Method signatures and docstrings:
- def _set_fit_matrix(s... | Implement the Python class `CsaOdfModel` described below.
Class description:
Implementation of Constant Solid Angle reconstruction method. References ---------- .. [1] Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging With Solid Angle Consideration.
Method signatures and docstrings:
- def _set_fit_matrix(s... | 3c3acc55de8ba741e673063378e6cbaf10b64c7a | <|skeleton|>
class CsaOdfModel:
"""Implementation of Constant Solid Angle reconstruction method. References ---------- .. [1] Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging With Solid Angle Consideration."""
def _set_fit_matrix(self, B, L, F, smooth):
"""The fit matrix, is used by fit_coe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CsaOdfModel:
"""Implementation of Constant Solid Angle reconstruction method. References ---------- .. [1] Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging With Solid Angle Consideration."""
def _set_fit_matrix(self, B, L, F, smooth):
"""The fit matrix, is used by fit_coefficients to ... | the_stack_v2_python_sparse | env/lib/python3.6/site-packages/dipy/reconst/shm.py | Raniac/NEURO-LEARN | train | 9 |
f98f2bd04367b414fb00d1f1b863858066055ce0 | [
"self.df = df\nself.col_name = col_name\nself.threshold = threshold\nself.relative_error = relative_error\nself.upper_bound, self.lower_bound = dict_filter(self.whiskers(), ['upper_bound', 'lower_bound'])\nsuper().__init__(df, col_name)",
"mad_value = self.df.cols.mad(self.col_name, self.relative_error, more=True... | <|body_start_0|>
self.df = df
self.col_name = col_name
self.threshold = threshold
self.relative_error = relative_error
self.upper_bound, self.lower_bound = dict_filter(self.whiskers(), ['upper_bound', 'lower_bound'])
super().__init__(df, col_name)
<|end_body_0|>
<|body_s... | Handle outliers using mad | MAD | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MAD:
"""Handle outliers using mad"""
def __init__(self, df, col_name, threshold: int, relative_error: int=RELATIVE_ERROR):
""":param df: :param col_name: :type threshold: object :type relative_error: object"""
<|body_0|>
def whiskers(self):
"""Get the wisker used... | stack_v2_sparse_classes_75kplus_train_007037 | 1,930 | permissive | [
{
"docstring": ":param df: :param col_name: :type threshold: object :type relative_error: object",
"name": "__init__",
"signature": "def __init__(self, df, col_name, threshold: int, relative_error: int=RELATIVE_ERROR)"
},
{
"docstring": "Get the wisker used to defined outliers :return:",
"na... | 3 | stack_v2_sparse_classes_30k_train_042276 | Implement the Python class `MAD` described below.
Class description:
Handle outliers using mad
Method signatures and docstrings:
- def __init__(self, df, col_name, threshold: int, relative_error: int=RELATIVE_ERROR): :param df: :param col_name: :type threshold: object :type relative_error: object
- def whiskers(self)... | Implement the Python class `MAD` described below.
Class description:
Handle outliers using mad
Method signatures and docstrings:
- def __init__(self, df, col_name, threshold: int, relative_error: int=RELATIVE_ERROR): :param df: :param col_name: :type threshold: object :type relative_error: object
- def whiskers(self)... | 13e7b180f0970addae77cafe128bd2a93be138a2 | <|skeleton|>
class MAD:
"""Handle outliers using mad"""
def __init__(self, df, col_name, threshold: int, relative_error: int=RELATIVE_ERROR):
""":param df: :param col_name: :type threshold: object :type relative_error: object"""
<|body_0|>
def whiskers(self):
"""Get the wisker used... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MAD:
"""Handle outliers using mad"""
def __init__(self, df, col_name, threshold: int, relative_error: int=RELATIVE_ERROR):
""":param df: :param col_name: :type threshold: object :type relative_error: object"""
self.df = df
self.col_name = col_name
self.threshold = threshol... | the_stack_v2_python_sparse | optimus/outliers/mad.py | XD-DENG/Optimus | train | 1 |
685f0b393a1fad3512368131f224432f5912f127 | [
"super().__init__(dataset, train_sampler, val_sampler, student_model, loss_fn, metric_fn, optimizer, scheduler, iter_scheduler, device, max_steps, epoch_per_step, iter_per_step, batches_per_iter, lower_is_better, max_grad_norm, max_grad_abs_val, extra_validation_metrics)\nself.student_model = self.model\nself.teach... | <|body_start_0|>
super().__init__(dataset, train_sampler, val_sampler, student_model, loss_fn, metric_fn, optimizer, scheduler, iter_scheduler, device, max_steps, epoch_per_step, iter_per_step, batches_per_iter, lower_is_better, max_grad_norm, max_grad_abs_val, extra_validation_metrics)
self.student_mod... | Implement a Distillation Trainer. Perform knowledge distillation between a teacher and a student model. Note that the model outputs are expected to be raw logits. Make sure that you are not applying a softmax after the decoder. You can replace the traditional Decoder with a MLPEncoder. | DistillationTrainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistillationTrainer:
"""Implement a Distillation Trainer. Perform knowledge distillation between a teacher and a student model. Note that the model outputs are expected to be raw logits. Make sure that you are not applying a softmax after the decoder. You can replace the traditional Decoder with ... | stack_v2_sparse_classes_75kplus_train_007038 | 8,763 | permissive | [
{
"docstring": "Initialize the Trainer. Parameters ---------- dataset: Dataset The dataset containing the first N columns of data for the student model, and the last N columns for the target. train_sampler : Sampler The sampler to use over training examples val_sampler : Sampler The sampler to use over validati... | 3 | stack_v2_sparse_classes_30k_train_037503 | Implement the Python class `DistillationTrainer` described below.
Class description:
Implement a Distillation Trainer. Perform knowledge distillation between a teacher and a student model. Note that the model outputs are expected to be raw logits. Make sure that you are not applying a softmax after the decoder. You ca... | Implement the Python class `DistillationTrainer` described below.
Class description:
Implement a Distillation Trainer. Perform knowledge distillation between a teacher and a student model. Note that the model outputs are expected to be raw logits. Make sure that you are not applying a softmax after the decoder. You ca... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class DistillationTrainer:
"""Implement a Distillation Trainer. Perform knowledge distillation between a teacher and a student model. Note that the model outputs are expected to be raw logits. Make sure that you are not applying a softmax after the decoder. You can replace the traditional Decoder with ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DistillationTrainer:
"""Implement a Distillation Trainer. Perform knowledge distillation between a teacher and a student model. Note that the model outputs are expected to be raw logits. Make sure that you are not applying a softmax after the decoder. You can replace the traditional Decoder with a MLPEncoder.... | the_stack_v2_python_sparse | flambe/learn/distillation.py | cle-ros/flambe | train | 1 |
a88ab2dc93f22f0b204678a82cca26cdaee9357a | [
"super().__init__()\nif scale_factor <= 0:\n raise ValueError(f'The `scale_factor` multiplier must be an integer greater than 0, got {scale_factor}.')\nself.dimensions = spatial_dims\nself.scale_factor = scale_factor\nif conv_block == 'default':\n out_channels = out_channels or in_channels\n if not out_cha... | <|body_start_0|>
super().__init__()
if scale_factor <= 0:
raise ValueError(f'The `scale_factor` multiplier must be an integer greater than 0, got {scale_factor}.')
self.dimensions = spatial_dims
self.scale_factor = scale_factor
if conv_block == 'default':
... | Upsample via using a subpixel CNN. This module supports 1D, 2D and 3D input images. The module is consisted with two parts. First of all, a convolutional layer is employed to increase the number of channels into: ``in_channels * (scale_factor ** dimensions)``. Secondly, a pixel shuffle manipulation is utilized to aggre... | SubpixelUpsample | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubpixelUpsample:
"""Upsample via using a subpixel CNN. This module supports 1D, 2D and 3D input images. The module is consisted with two parts. First of all, a convolutional layer is employed to increase the number of channels into: ``in_channels * (scale_factor ** dimensions)``. Secondly, a pix... | stack_v2_sparse_classes_75kplus_train_007039 | 13,312 | permissive | [
{
"docstring": "Args: spatial_dims: number of spatial dimensions of the input image. in_channels: number of channels of the input image. out_channels: optional number of channels of the output image. scale_factor: multiplier for spatial size. Defaults to 2. conv_block: a conv block to extract feature maps befor... | 2 | null | Implement the Python class `SubpixelUpsample` described below.
Class description:
Upsample via using a subpixel CNN. This module supports 1D, 2D and 3D input images. The module is consisted with two parts. First of all, a convolutional layer is employed to increase the number of channels into: ``in_channels * (scale_f... | Implement the Python class `SubpixelUpsample` described below.
Class description:
Upsample via using a subpixel CNN. This module supports 1D, 2D and 3D input images. The module is consisted with two parts. First of all, a convolutional layer is employed to increase the number of channels into: ``in_channels * (scale_f... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class SubpixelUpsample:
"""Upsample via using a subpixel CNN. This module supports 1D, 2D and 3D input images. The module is consisted with two parts. First of all, a convolutional layer is employed to increase the number of channels into: ``in_channels * (scale_factor ** dimensions)``. Secondly, a pix... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubpixelUpsample:
"""Upsample via using a subpixel CNN. This module supports 1D, 2D and 3D input images. The module is consisted with two parts. First of all, a convolutional layer is employed to increase the number of channels into: ``in_channels * (scale_factor ** dimensions)``. Secondly, a pixel shuffle ma... | the_stack_v2_python_sparse | monai/networks/blocks/upsample.py | Project-MONAI/MONAI | train | 4,805 |
727b4dc4e6c4034022fdcba6f13848aa3e0549a6 | [
"self.vocabulary = vocabulary\nif not self.vocabulary.vocab:\n self.vocabulary.build_vocab()",
"numerical_tokens = []\nlen_tokens = len(instance)\nfor string in instance:\n idx = self.vocabulary.get_idx_from_token(string)\n numerical_tokens.append(idx)\nassert len(numerical_tokens) == len_tokens\nreturn ... | <|body_start_0|>
self.vocabulary = vocabulary
if not self.vocabulary.vocab:
self.vocabulary.build_vocab()
<|end_body_0|>
<|body_start_1|>
numerical_tokens = []
len_tokens = len(instance)
for string in instance:
idx = self.vocabulary.get_idx_from_token(str... | Numericalizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Numericalizer:
def __init__(self, vocabulary: Vocab):
"""Numericalizer converts tokens that are strings to numbers Parameters ---------- vocabulary : Vocab A vocabulary object that is built using a set of tokenized strings"""
<|body_0|>
def numericalize_instance(self, instan... | stack_v2_sparse_classes_75kplus_train_007040 | 1,711 | permissive | [
{
"docstring": "Numericalizer converts tokens that are strings to numbers Parameters ---------- vocabulary : Vocab A vocabulary object that is built using a set of tokenized strings",
"name": "__init__",
"signature": "def __init__(self, vocabulary: Vocab)"
},
{
"docstring": "Numericalize a singl... | 3 | stack_v2_sparse_classes_30k_train_042871 | Implement the Python class `Numericalizer` described below.
Class description:
Implement the Numericalizer class.
Method signatures and docstrings:
- def __init__(self, vocabulary: Vocab): Numericalizer converts tokens that are strings to numbers Parameters ---------- vocabulary : Vocab A vocabulary object that is bu... | Implement the Python class `Numericalizer` described below.
Class description:
Implement the Numericalizer class.
Method signatures and docstrings:
- def __init__(self, vocabulary: Vocab): Numericalizer converts tokens that are strings to numbers Parameters ---------- vocabulary : Vocab A vocabulary object that is bu... | cb4c1413ddc3c749835e1cb80db31c0060e7a1eb | <|skeleton|>
class Numericalizer:
def __init__(self, vocabulary: Vocab):
"""Numericalizer converts tokens that are strings to numbers Parameters ---------- vocabulary : Vocab A vocabulary object that is built using a set of tokenized strings"""
<|body_0|>
def numericalize_instance(self, instan... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Numericalizer:
def __init__(self, vocabulary: Vocab):
"""Numericalizer converts tokens that are strings to numbers Parameters ---------- vocabulary : Vocab A vocabulary object that is built using a set of tokenized strings"""
self.vocabulary = vocabulary
if not self.vocabulary.vocab:
... | the_stack_v2_python_sparse | sciwing/numericalizer/numericalizer.py | yaxche-io/sciwing | train | 0 | |
09576aa348035d8f1e17a44b150ffa3fe8b353f6 | [
"source = 'pipeline'\npipeline_resource_name = _LegacyExperimentService._get_experiment_or_pipeline_resource_name(name=pipeline, source=source, expected_schema=constants.SYSTEM_PIPELINE)\nreturn _LegacyExperimentService._query_runs_to_data_frame(context_id=pipeline, context_resource_name=pipeline_resource_name, sou... | <|body_start_0|>
source = 'pipeline'
pipeline_resource_name = _LegacyExperimentService._get_experiment_or_pipeline_resource_name(name=pipeline, source=source, expected_schema=constants.SYSTEM_PIPELINE)
return _LegacyExperimentService._query_runs_to_data_frame(context_id=pipeline, context_resourc... | Contains the exposed APIs to interact with the Managed Metadata Service. | _LegacyExperimentService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _LegacyExperimentService:
"""Contains the exposed APIs to interact with the Managed Metadata Service."""
def get_pipeline_df(pipeline: str) -> 'pd.DataFrame':
"""Returns a Pandas DataFrame of the parameters and metrics associated with one pipeline. Args: pipeline: Name of the Pipelin... | stack_v2_sparse_classes_75kplus_train_007041 | 38,620 | permissive | [
{
"docstring": "Returns a Pandas DataFrame of the parameters and metrics associated with one pipeline. Args: pipeline: Name of the Pipeline to filter results. Returns: Pandas Dataframe of Pipeline with metrics and parameters.",
"name": "get_pipeline_df",
"signature": "def get_pipeline_df(pipeline: str) ... | 4 | stack_v2_sparse_classes_30k_test_002559 | Implement the Python class `_LegacyExperimentService` described below.
Class description:
Contains the exposed APIs to interact with the Managed Metadata Service.
Method signatures and docstrings:
- def get_pipeline_df(pipeline: str) -> 'pd.DataFrame': Returns a Pandas DataFrame of the parameters and metrics associat... | Implement the Python class `_LegacyExperimentService` described below.
Class description:
Contains the exposed APIs to interact with the Managed Metadata Service.
Method signatures and docstrings:
- def get_pipeline_df(pipeline: str) -> 'pd.DataFrame': Returns a Pandas DataFrame of the parameters and metrics associat... | 76b95b92c1d3b87c72d754d8c02b1bca652b9a27 | <|skeleton|>
class _LegacyExperimentService:
"""Contains the exposed APIs to interact with the Managed Metadata Service."""
def get_pipeline_df(pipeline: str) -> 'pd.DataFrame':
"""Returns a Pandas DataFrame of the parameters and metrics associated with one pipeline. Args: pipeline: Name of the Pipelin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _LegacyExperimentService:
"""Contains the exposed APIs to interact with the Managed Metadata Service."""
def get_pipeline_df(pipeline: str) -> 'pd.DataFrame':
"""Returns a Pandas DataFrame of the parameters and metrics associated with one pipeline. Args: pipeline: Name of the Pipeline to filter r... | the_stack_v2_python_sparse | google/cloud/aiplatform/metadata/metadata.py | googleapis/python-aiplatform | train | 418 |
e6235bad28b86d415605b8a0a75254cb404dcc9d | [
"if not os.path.isdir(input_dir):\n raise ValueError('Input directory is not exist.')\nif not os.path.isdir(output_dir):\n os.makedirs(output_dir)\nself.names = os.listdir(input_dir)\nself._resize_volume_multi(input_dir, output_dir)\nreturn",
"input_paths = [os.path.join(input_dir, name) for name in self.na... | <|body_start_0|>
if not os.path.isdir(input_dir):
raise ValueError('Input directory is not exist.')
if not os.path.isdir(output_dir):
os.makedirs(output_dir)
self.names = os.listdir(input_dir)
self._resize_volume_multi(input_dir, output_dir)
return
<|end_b... | BTCVolumes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BTCVolumes:
def __init__(self, input_dir, output_dir):
"""__INIT__ Initialization of instance. - generate folders to store resized brain volume - resize brain volumes in multi-processes Inputs: ------- - input_dir: string, the path of the directory that keeps preprocessed volume - output... | stack_v2_sparse_classes_75kplus_train_007042 | 5,954 | permissive | [
{
"docstring": "__INIT__ Initialization of instance. - generate folders to store resized brain volume - resize brain volumes in multi-processes Inputs: ------- - input_dir: string, the path of the directory that keeps preprocessed volume - output_dir: string, the path of the directory that will store resized vo... | 3 | stack_v2_sparse_classes_30k_train_001463 | Implement the Python class `BTCVolumes` described below.
Class description:
Implement the BTCVolumes class.
Method signatures and docstrings:
- def __init__(self, input_dir, output_dir): __INIT__ Initialization of instance. - generate folders to store resized brain volume - resize brain volumes in multi-processes Inp... | Implement the Python class `BTCVolumes` described below.
Class description:
Implement the BTCVolumes class.
Method signatures and docstrings:
- def __init__(self, input_dir, output_dir): __INIT__ Initialization of instance. - generate folders to store resized brain volume - resize brain volumes in multi-processes Inp... | ec98a242d4f215505f2640a8bdf12f2015bfd5c7 | <|skeleton|>
class BTCVolumes:
def __init__(self, input_dir, output_dir):
"""__INIT__ Initialization of instance. - generate folders to store resized brain volume - resize brain volumes in multi-processes Inputs: ------- - input_dir: string, the path of the directory that keeps preprocessed volume - output... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BTCVolumes:
def __init__(self, input_dir, output_dir):
"""__INIT__ Initialization of instance. - generate folders to store resized brain volume - resize brain volumes in multi-processes Inputs: ------- - input_dir: string, the path of the directory that keeps preprocessed volume - output_dir: string, ... | the_stack_v2_python_sparse | src/btc_volumes.py | DeepLearningInMedicine/BTClassification | train | 1 | |
7d5b8f28ccd51bc719d9fa6f2dd20bd5ff31892f | [
"super(DefaultNBitConvWeightsQuantizer, self).__init__(num_bits=num_bits_weight, per_axis=True, symmetric=True, narrow_range=True)\nself._num_bits_weight = num_bits_weight\nself._num_bits_activation = num_bits_activation",
"min_weight = layer.add_weight(name + '_min', shape=(tensor_shape[-1],), initializer=tf.ker... | <|body_start_0|>
super(DefaultNBitConvWeightsQuantizer, self).__init__(num_bits=num_bits_weight, per_axis=True, symmetric=True, narrow_range=True)
self._num_bits_weight = num_bits_weight
self._num_bits_activation = num_bits_activation
<|end_body_0|>
<|body_start_1|>
min_weight = layer.a... | Quantizer for handling weights in Conv2D/DepthwiseConv2D layers. | DefaultNBitConvWeightsQuantizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultNBitConvWeightsQuantizer:
"""Quantizer for handling weights in Conv2D/DepthwiseConv2D layers."""
def __init__(self, num_bits_weight: int=8, num_bits_activation: int=8):
"""Construct LastValueQuantizer with params specific for TFLite Convs."""
<|body_0|>
def build(... | stack_v2_sparse_classes_75kplus_train_007043 | 13,651 | permissive | [
{
"docstring": "Construct LastValueQuantizer with params specific for TFLite Convs.",
"name": "__init__",
"signature": "def __init__(self, num_bits_weight: int=8, num_bits_activation: int=8)"
},
{
"docstring": "Build min/max quantization variables.",
"name": "build",
"signature": "def bu... | 2 | stack_v2_sparse_classes_30k_train_017769 | Implement the Python class `DefaultNBitConvWeightsQuantizer` described below.
Class description:
Quantizer for handling weights in Conv2D/DepthwiseConv2D layers.
Method signatures and docstrings:
- def __init__(self, num_bits_weight: int=8, num_bits_activation: int=8): Construct LastValueQuantizer with params specifi... | Implement the Python class `DefaultNBitConvWeightsQuantizer` described below.
Class description:
Quantizer for handling weights in Conv2D/DepthwiseConv2D layers.
Method signatures and docstrings:
- def __init__(self, num_bits_weight: int=8, num_bits_activation: int=8): Construct LastValueQuantizer with params specifi... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class DefaultNBitConvWeightsQuantizer:
"""Quantizer for handling weights in Conv2D/DepthwiseConv2D layers."""
def __init__(self, num_bits_weight: int=8, num_bits_activation: int=8):
"""Construct LastValueQuantizer with params specific for TFLite Convs."""
<|body_0|>
def build(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DefaultNBitConvWeightsQuantizer:
"""Quantizer for handling weights in Conv2D/DepthwiseConv2D layers."""
def __init__(self, num_bits_weight: int=8, num_bits_activation: int=8):
"""Construct LastValueQuantizer with params specific for TFLite Convs."""
super(DefaultNBitConvWeightsQuantizer, ... | the_stack_v2_python_sparse | official/projects/qat/vision/n_bit/configs.py | jianzhnie/models | train | 2 |
9d3f13015360f5211533ca52f8f1ef89c3a3ee3d | [
"from tutorweb.content.transmogrifier.latex import readQuestions\nout = dict()\nwith self.context.questionfile.open() as fh:\n for qn in readQuestions(fh):\n out[qn['id']] = qn\nreturn out",
"if isinstance(data, dict) and 'question_id' in data:\n qnId = data['question_id']\n if isinstance(qnId, li... | <|body_start_0|>
from tutorweb.content.transmogrifier.latex import readQuestions
out = dict()
with self.context.questionfile.open() as fh:
for qn in readQuestions(fh):
out[qn['id']] = qn
return out
<|end_body_0|>
<|body_start_1|>
if isinstance(data, d... | QuestionPackStruct | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionPackStruct:
def allQuestionsDict(self):
"""Convert all questions to intermediate JSON"""
<|body_0|>
def asDict(self, data={}):
"""Render Selected question"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from tutorweb.content.transmogrifier.l... | stack_v2_sparse_classes_75kplus_train_007044 | 6,796 | no_license | [
{
"docstring": "Convert all questions to intermediate JSON",
"name": "allQuestionsDict",
"signature": "def allQuestionsDict(self)"
},
{
"docstring": "Render Selected question",
"name": "asDict",
"signature": "def asDict(self, data={})"
}
] | 2 | stack_v2_sparse_classes_30k_train_039727 | Implement the Python class `QuestionPackStruct` described below.
Class description:
Implement the QuestionPackStruct class.
Method signatures and docstrings:
- def allQuestionsDict(self): Convert all questions to intermediate JSON
- def asDict(self, data={}): Render Selected question | Implement the Python class `QuestionPackStruct` described below.
Class description:
Implement the QuestionPackStruct class.
Method signatures and docstrings:
- def allQuestionsDict(self): Convert all questions to intermediate JSON
- def asDict(self, data={}): Render Selected question
<|skeleton|>
class QuestionPackS... | a9ef3ba7c7d22d244a98e6b8b29f1f2843dd24aa | <|skeleton|>
class QuestionPackStruct:
def allQuestionsDict(self):
"""Convert all questions to intermediate JSON"""
<|body_0|>
def asDict(self, data={}):
"""Render Selected question"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestionPackStruct:
def allQuestionsDict(self):
"""Convert all questions to intermediate JSON"""
from tutorweb.content.transmogrifier.latex import readQuestions
out = dict()
with self.context.questionfile.open() as fh:
for qn in readQuestions(fh):
ou... | the_stack_v2_python_sparse | tutorweb/content/browser/question.py | tutor-web/tutorweb.content | train | 0 | |
84893598125c37ace7eed2810e7ebf96d52874ce | [
"assert linker_pos('TTGATCTT', 'GATC', 0) == (2, 6)\nassert linker_pos('TTGATCTT', 'GGTC', 0) == (None, None)\nassert linker_pos('TTGATCTT', 'GGTC', 1) == (2, 6)\nassert linker_pos('NATCTT', 'GATC', 1) == (1, 4)\nassert linker_pos('NATCTT', 'GATC', 0) == (None, None)",
"self.assertEqual(linker_pair_pos('TGATCTTTT... | <|body_start_0|>
assert linker_pos('TTGATCTT', 'GATC', 0) == (2, 6)
assert linker_pos('TTGATCTT', 'GGTC', 0) == (None, None)
assert linker_pos('TTGATCTT', 'GGTC', 1) == (2, 6)
assert linker_pos('NATCTT', 'GATC', 1) == (1, 4)
assert linker_pos('NATCTT', 'GATC', 0) == (None, None)
... | Test removal of two sided linkers from sequence data. | TwoSideLinkerTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoSideLinkerTest:
"""Test removal of two sided linkers from sequence data."""
def test_1_linker_pos(self):
"""Find a linker, with mismatches, in a larger sequence."""
<|body_0|>
def test_2_linker_pair_pos(self):
"""Find pair of linkers in a larger sequence"""
... | stack_v2_sparse_classes_75kplus_train_007045 | 7,424 | no_license | [
{
"docstring": "Find a linker, with mismatches, in a larger sequence.",
"name": "test_1_linker_pos",
"signature": "def test_1_linker_pos(self)"
},
{
"docstring": "Find pair of linkers in a larger sequence",
"name": "test_2_linker_pair_pos",
"signature": "def test_2_linker_pair_pos(self)"... | 3 | stack_v2_sparse_classes_30k_train_032963 | Implement the Python class `TwoSideLinkerTest` described below.
Class description:
Test removal of two sided linkers from sequence data.
Method signatures and docstrings:
- def test_1_linker_pos(self): Find a linker, with mismatches, in a larger sequence.
- def test_2_linker_pair_pos(self): Find pair of linkers in a ... | Implement the Python class `TwoSideLinkerTest` described below.
Class description:
Test removal of two sided linkers from sequence data.
Method signatures and docstrings:
- def test_1_linker_pos(self): Find a linker, with mismatches, in a larger sequence.
- def test_2_linker_pair_pos(self): Find pair of linkers in a ... | 76ea8bc6ddb5fd09fec095c80a5092facfba6e8c | <|skeleton|>
class TwoSideLinkerTest:
"""Test removal of two sided linkers from sequence data."""
def test_1_linker_pos(self):
"""Find a linker, with mismatches, in a larger sequence."""
<|body_0|>
def test_2_linker_pair_pos(self):
"""Find pair of linkers in a larger sequence"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoSideLinkerTest:
"""Test removal of two sided linkers from sequence data."""
def test_1_linker_pos(self):
"""Find a linker, with mismatches, in a larger sequence."""
assert linker_pos('TTGATCTT', 'GATC', 0) == (2, 6)
assert linker_pos('TTGATCTT', 'GGTC', 0) == (None, None)
... | the_stack_v2_python_sparse | ay_linkertrim/scripts/trim_twoside_linker.py | Rushikesh2703/projects | train | 0 |
5a63eb6abb4d161f5769fd78e873a495c24e8159 | [
"kwargs_options = {'lens_model_list': profile_list}\nself.model = SinglePlane(profile_list)\nself.cosmo = Cosmo(kwargs_cosmo)\nself._interp_grid_num = kwargs_numerics.get('interpol_grid_num', 1000)\nself._max_interpolate = kwargs_numerics.get('max_integrate', 100)\nself._min_interpolate = kwargs_numerics.get('min_i... | <|body_start_0|>
kwargs_options = {'lens_model_list': profile_list}
self.model = SinglePlane(profile_list)
self.cosmo = Cosmo(kwargs_cosmo)
self._interp_grid_num = kwargs_numerics.get('interpol_grid_num', 1000)
self._max_interpolate = kwargs_numerics.get('max_integrate', 100)
... | mass profile class | MassProfile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MassProfile:
"""mass profile class"""
def __init__(self, profile_list, kwargs_cosmo={'D_d': 1000, 'D_s': 2000, 'D_ds': 500}, kwargs_numerics={}):
""":param profile_list:"""
<|body_0|>
def mass_3d_interp(self, r, kwargs, new_compute=False):
""":param r: in arc sec... | stack_v2_sparse_classes_75kplus_train_007046 | 2,303 | permissive | [
{
"docstring": ":param profile_list:",
"name": "__init__",
"signature": "def __init__(self, profile_list, kwargs_cosmo={'D_d': 1000, 'D_s': 2000, 'D_ds': 500}, kwargs_numerics={})"
},
{
"docstring": ":param r: in arc seconds :param kwargs: lens model parameters in arc seconds :return: mass enclo... | 3 | stack_v2_sparse_classes_30k_train_038798 | Implement the Python class `MassProfile` described below.
Class description:
mass profile class
Method signatures and docstrings:
- def __init__(self, profile_list, kwargs_cosmo={'D_d': 1000, 'D_s': 2000, 'D_ds': 500}, kwargs_numerics={}): :param profile_list:
- def mass_3d_interp(self, r, kwargs, new_compute=False):... | Implement the Python class `MassProfile` described below.
Class description:
mass profile class
Method signatures and docstrings:
- def __init__(self, profile_list, kwargs_cosmo={'D_d': 1000, 'D_s': 2000, 'D_ds': 500}, kwargs_numerics={}): :param profile_list:
- def mass_3d_interp(self, r, kwargs, new_compute=False):... | dcdfc61ce5351ac94565228c822f1c94392c1ad6 | <|skeleton|>
class MassProfile:
"""mass profile class"""
def __init__(self, profile_list, kwargs_cosmo={'D_d': 1000, 'D_s': 2000, 'D_ds': 500}, kwargs_numerics={}):
""":param profile_list:"""
<|body_0|>
def mass_3d_interp(self, r, kwargs, new_compute=False):
""":param r: in arc sec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MassProfile:
"""mass profile class"""
def __init__(self, profile_list, kwargs_cosmo={'D_d': 1000, 'D_s': 2000, 'D_ds': 500}, kwargs_numerics={}):
""":param profile_list:"""
kwargs_options = {'lens_model_list': profile_list}
self.model = SinglePlane(profile_list)
self.cosmo... | the_stack_v2_python_sparse | lenstronomy/GalKin/mass_profile.py | guoxiaowhu/lenstronomy | train | 1 |
bc0cf11d7ed3624b97f5b5f3f546541c7aa7eb18 | [
"assert modality in {'rg', 'rgb', 'flow'}, 'Invalid modality.'\nif modality in {'rg', 'rgb'}:\n super().__init__('rgb', dropout_prob, weights_path=weights_path)\nelse:\n super().__init__('flow', dropout_prob, weights_path=weights_path)\nself.conv3d_0c_1x1 = None\nself.avg_pool = None\nif output_pool_class is ... | <|body_start_0|>
assert modality in {'rg', 'rgb', 'flow'}, 'Invalid modality.'
if modality in {'rg', 'rgb'}:
super().__init__('rgb', dropout_prob, weights_path=weights_path)
else:
super().__init__('flow', dropout_prob, weights_path=weights_path)
self.conv3d_0c_1x1... | I3DEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class I3DEncoder:
def __init__(self, modality='rgb', attention=False, dropout_prob=0, output_pool_class=None, output_pool_args={}, weights_path=None):
"""I3D encoder that encodes a stack of images into a block of size (length x 7 x 7)"""
<|body_0|>
def forward(self, input_tensor):... | stack_v2_sparse_classes_75kplus_train_007047 | 11,274 | permissive | [
{
"docstring": "I3D encoder that encodes a stack of images into a block of size (length x 7 x 7)",
"name": "__init__",
"signature": "def __init__(self, modality='rgb', attention=False, dropout_prob=0, output_pool_class=None, output_pool_args={}, weights_path=None)"
},
{
"docstring": "Encodes a s... | 2 | null | Implement the Python class `I3DEncoder` described below.
Class description:
Implement the I3DEncoder class.
Method signatures and docstrings:
- def __init__(self, modality='rgb', attention=False, dropout_prob=0, output_pool_class=None, output_pool_args={}, weights_path=None): I3D encoder that encodes a stack of image... | Implement the Python class `I3DEncoder` described below.
Class description:
Implement the I3DEncoder class.
Method signatures and docstrings:
- def __init__(self, modality='rgb', attention=False, dropout_prob=0, output_pool_class=None, output_pool_args={}, weights_path=None): I3D encoder that encodes a stack of image... | 182821ae6b6abe1bc3623692aeba85da8083b27b | <|skeleton|>
class I3DEncoder:
def __init__(self, modality='rgb', attention=False, dropout_prob=0, output_pool_class=None, output_pool_args={}, weights_path=None):
"""I3D encoder that encodes a stack of images into a block of size (length x 7 x 7)"""
<|body_0|>
def forward(self, input_tensor):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class I3DEncoder:
def __init__(self, modality='rgb', attention=False, dropout_prob=0, output_pool_class=None, output_pool_args={}, weights_path=None):
"""I3D encoder that encodes a stack of images into a block of size (length x 7 x 7)"""
assert modality in {'rg', 'rgb', 'flow'}, 'Invalid modality.'
... | the_stack_v2_python_sparse | pet_ct/model/i3d.py | seyuboglu/weakly-supervised-petct | train | 16 | |
769ba3c26a12b5da98c7ac272498417e41cdc123 | [
"self.port = 5555\nself.host = ''\nself.addr = (self.host, self.port)\nself.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nself.p = self.connect()",
"try:\n self.client.connect(self.addr)\n return int(self.client.recv(2048).decode())\nexcept socket.error as e:\n code = e.errno\n error = s... | <|body_start_0|>
self.port = 5555
self.host = ''
self.addr = (self.host, self.port)
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.p = self.connect()
<|end_body_0|>
<|body_start_1|>
try:
self.client.connect(self.addr)
return ... | Network | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Network:
def __init__(self):
"""Initializes the object"""
<|body_0|>
def connect(self):
"""Connects to the server :return: int (player id)"""
<|body_1|>
def send(self, data):
"""Sends codes to server :return: Game"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_007048 | 1,662 | no_license | [
{
"docstring": "Initializes the object",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Connects to the server :return: int (player id)",
"name": "connect",
"signature": "def connect(self)"
},
{
"docstring": "Sends codes to server :return: Game",
"na... | 3 | stack_v2_sparse_classes_30k_val_002542 | Implement the Python class `Network` described below.
Class description:
Implement the Network class.
Method signatures and docstrings:
- def __init__(self): Initializes the object
- def connect(self): Connects to the server :return: int (player id)
- def send(self, data): Sends codes to server :return: Game | Implement the Python class `Network` described below.
Class description:
Implement the Network class.
Method signatures and docstrings:
- def __init__(self): Initializes the object
- def connect(self): Connects to the server :return: int (player id)
- def send(self, data): Sends codes to server :return: Game
<|skele... | 3dd9f15fca25b41f20c94e7f1ece17b48f37a3fa | <|skeleton|>
class Network:
def __init__(self):
"""Initializes the object"""
<|body_0|>
def connect(self):
"""Connects to the server :return: int (player id)"""
<|body_1|>
def send(self, data):
"""Sends codes to server :return: Game"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Network:
def __init__(self):
"""Initializes the object"""
self.port = 5555
self.host = ''
self.addr = (self.host, self.port)
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.p = self.connect()
def connect(self):
"""Connects to th... | the_stack_v2_python_sparse | code/Memoria/Client/NetworkAssistant.py | StephanGuingor/Memory-GUI-Client-Server | train | 0 | |
fd06f31cdb2c0b077ec611fa94005ba008bd2d53 | [
"login_page.LoginPage(self.driver).login()\nsleep(2)\nlandlord_nav_page.LandlordNavPage(self.driver).Iamlandlord()\nsleep(2)\nlandlord_nav_page.LandlordNavPage(self.driver).close_weiChat()\npo = landlord_microshop_page.LandlordMicroshopPage(self.driver)\npo.microshop()\npo.microshop_order_details()\npo.microshop_re... | <|body_start_0|>
login_page.LoginPage(self.driver).login()
sleep(2)
landlord_nav_page.LandlordNavPage(self.driver).Iamlandlord()
sleep(2)
landlord_nav_page.LandlordNavPage(self.driver).close_weiChat()
po = landlord_microshop_page.LandlordMicroshopPage(self.driver)
... | 微店订单 | TestMicroshop | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMicroshop:
"""微店订单"""
def test_microshop_return_myorder(self):
"""返回我的订单并打印第一个状态"""
<|body_0|>
def test_microshop_status(self):
"""进入订单详情页并打印状态"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
login_page.LoginPage(self.driver).login()
... | stack_v2_sparse_classes_75kplus_train_007049 | 1,620 | permissive | [
{
"docstring": "返回我的订单并打印第一个状态",
"name": "test_microshop_return_myorder",
"signature": "def test_microshop_return_myorder(self)"
},
{
"docstring": "进入订单详情页并打印状态",
"name": "test_microshop_status",
"signature": "def test_microshop_status(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048492 | Implement the Python class `TestMicroshop` described below.
Class description:
微店订单
Method signatures and docstrings:
- def test_microshop_return_myorder(self): 返回我的订单并打印第一个状态
- def test_microshop_status(self): 进入订单详情页并打印状态 | Implement the Python class `TestMicroshop` described below.
Class description:
微店订单
Method signatures and docstrings:
- def test_microshop_return_myorder(self): 返回我的订单并打印第一个状态
- def test_microshop_status(self): 进入订单详情页并打印状态
<|skeleton|>
class TestMicroshop:
"""微店订单"""
def test_microshop_return_myorder(self)... | 192c70c49a8e9e072b9d0d0136f02c653c589410 | <|skeleton|>
class TestMicroshop:
"""微店订单"""
def test_microshop_return_myorder(self):
"""返回我的订单并打印第一个状态"""
<|body_0|>
def test_microshop_status(self):
"""进入订单详情页并打印状态"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMicroshop:
"""微店订单"""
def test_microshop_return_myorder(self):
"""返回我的订单并打印第一个状态"""
login_page.LoginPage(self.driver).login()
sleep(2)
landlord_nav_page.LandlordNavPage(self.driver).Iamlandlord()
sleep(2)
landlord_nav_page.LandlordNavPage(self.driver).c... | the_stack_v2_python_sparse | mayi/test_case/test_landlord_microshop.py | 18701016443/mayi | train | 0 |
cff5c31ed2eeebbecd2b022ae775f33c140a241b | [
"p = 0\nn = len(a)\nm = len(a[0])\nfor i in range(m):\n if self.is_non_alpha_order(i, n, a):\n p += 1\nreturn p",
"for j in range(n - 1):\n if a[j][i].lower() > a[j + 1][i].lower():\n return True\nreturn False"
] | <|body_start_0|>
p = 0
n = len(a)
m = len(a[0])
for i in range(m):
if self.is_non_alpha_order(i, n, a):
p += 1
return p
<|end_body_0|>
<|body_start_1|>
for j in range(n - 1):
if a[j][i].lower() > a[j + 1][i].lower():
... | Traverse all indicies in each string. Time complexity: O(n * m) - Amortized traverse all string characters Space complexity: O(1) - Update constant pointer value | Solution | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Traverse all indicies in each string. Time complexity: O(n * m) - Amortized traverse all string characters Space complexity: O(1) - Update constant pointer value"""
def count_min_deletions(self, a):
"""Determines number of word indicies not in alphabetical order. :param ... | stack_v2_sparse_classes_75kplus_train_007050 | 2,278 | permissive | [
{
"docstring": "Determines number of word indicies not in alphabetical order. :param list[str] a: array of identical-length strings :return: number of word indicies not in alphabetical order :rtype: int",
"name": "count_min_deletions",
"signature": "def count_min_deletions(self, a)"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_val_000600 | Implement the Python class `Solution` described below.
Class description:
Traverse all indicies in each string. Time complexity: O(n * m) - Amortized traverse all string characters Space complexity: O(1) - Update constant pointer value
Method signatures and docstrings:
- def count_min_deletions(self, a): Determines n... | Implement the Python class `Solution` described below.
Class description:
Traverse all indicies in each string. Time complexity: O(n * m) - Amortized traverse all string characters Space complexity: O(1) - Update constant pointer value
Method signatures and docstrings:
- def count_min_deletions(self, a): Determines n... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution:
"""Traverse all indicies in each string. Time complexity: O(n * m) - Amortized traverse all string characters Space complexity: O(1) - Update constant pointer value"""
def count_min_deletions(self, a):
"""Determines number of word indicies not in alphabetical order. :param ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""Traverse all indicies in each string. Time complexity: O(n * m) - Amortized traverse all string characters Space complexity: O(1) - Update constant pointer value"""
def count_min_deletions(self, a):
"""Determines number of word indicies not in alphabetical order. :param list[str] a: ... | the_stack_v2_python_sparse | 0944_delete_string_columns_sorted/python_source.py | arthurdysart/LeetCode | train | 0 |
86b1cc914415341186c1aa16f2afe8e666ea174c | [
"if isinstance(A, Sample):\n dl1 = Samples({k: [v] for k, v in A.items()}).get_dataloader(batch_size=1)\nelif isinstance(A, Samples):\n dl1 = A.get_dataloader(batch_size=batch_size)\nelse:\n dl1 = A\nif isinstance(B, Sample):\n dl2 = Samples({k: [v] for k, v in B.items()}).get_dataloader(batch_size=1)\n... | <|body_start_0|>
if isinstance(A, Sample):
dl1 = Samples({k: [v] for k, v in A.items()}).get_dataloader(batch_size=1)
elif isinstance(A, Samples):
dl1 = A.get_dataloader(batch_size=batch_size)
else:
dl1 = A
if isinstance(B, Sample):
dl2 = S... | Base class: pytorch_lightning.Trainer It provides training functionality for swyft.SwyftModule. The functionality is identical to `pytorch_lightning.Trainer`, see corresponding documentation for more details. Two additional methods are defined: - `infer` for performing parameter inference tasks with a trained network -... | SwyftTrainer | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwyftTrainer:
"""Base class: pytorch_lightning.Trainer It provides training functionality for swyft.SwyftModule. The functionality is identical to `pytorch_lightning.Trainer`, see corresponding documentation for more details. Two additional methods are defined: - `infer` for performing parameter ... | stack_v2_sparse_classes_75kplus_train_007051 | 16,173 | permissive | [
{
"docstring": "Run through model in inference mode. Args: A: Sample, Samples, or dataloader for samples A. B: Sample, Samples, or dataloader for samples B. return_sample_ratios: If true (default), return results as collated collection of `LogRatioSamples` objects. Otherwise, return batches. batch_size: batch_s... | 2 | stack_v2_sparse_classes_30k_test_000972 | Implement the Python class `SwyftTrainer` described below.
Class description:
Base class: pytorch_lightning.Trainer It provides training functionality for swyft.SwyftModule. The functionality is identical to `pytorch_lightning.Trainer`, see corresponding documentation for more details. Two additional methods are defin... | Implement the Python class `SwyftTrainer` described below.
Class description:
Base class: pytorch_lightning.Trainer It provides training functionality for swyft.SwyftModule. The functionality is identical to `pytorch_lightning.Trainer`, see corresponding documentation for more details. Two additional methods are defin... | bd1a71b8f1ea1c9f0db81383d8568dd47dfdca28 | <|skeleton|>
class SwyftTrainer:
"""Base class: pytorch_lightning.Trainer It provides training functionality for swyft.SwyftModule. The functionality is identical to `pytorch_lightning.Trainer`, see corresponding documentation for more details. Two additional methods are defined: - `infer` for performing parameter ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SwyftTrainer:
"""Base class: pytorch_lightning.Trainer It provides training functionality for swyft.SwyftModule. The functionality is identical to `pytorch_lightning.Trainer`, see corresponding documentation for more details. Two additional methods are defined: - `infer` for performing parameter inference tas... | the_stack_v2_python_sparse | swyft/lightning/core.py | undark-lab/swyft | train | 162 |
691309036235a389ffc9efbe8b932d616fc9fb9f | [
"validation = get_object_or_404(Validation.objects, pk=pk)\nitems = []\nfor item in validation.results.values_list('id', 'item__name', 'status__test_status', 'issues', named=True):\n for existing in items:\n if existing['c0'] == item.item__name:\n existing['c2'].append(item.issues)\n ... | <|body_start_0|>
validation = get_object_or_404(Validation.objects, pk=pk)
items = []
for item in validation.results.values_list('id', 'item__name', 'status__test_status', 'issues', named=True):
for existing in items:
if existing['c0'] == item.item__name:
... | AssingJiraView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssingJiraView:
def get(self, request: HttpRequest, pk: int, *args, **kwargs) -> Response:
"""Return list of Test Items and attached Jira issues for validation with id=pk"""
<|body_0|>
def post(self, request: HttpRequest, pk: int, test_result_id: int, defect_id: str) -> Resp... | stack_v2_sparse_classes_75kplus_train_007052 | 3,085 | no_license | [
{
"docstring": "Return list of Test Items and attached Jira issues for validation with id=pk",
"name": "get",
"signature": "def get(self, request: HttpRequest, pk: int, *args, **kwargs) -> Response"
},
{
"docstring": "Add new issue with defect_id to test_result_id",
"name": "post",
"sign... | 3 | stack_v2_sparse_classes_30k_train_054198 | Implement the Python class `AssingJiraView` described below.
Class description:
Implement the AssingJiraView class.
Method signatures and docstrings:
- def get(self, request: HttpRequest, pk: int, *args, **kwargs) -> Response: Return list of Test Items and attached Jira issues for validation with id=pk
- def post(sel... | Implement the Python class `AssingJiraView` described below.
Class description:
Implement the AssingJiraView class.
Method signatures and docstrings:
- def get(self, request: HttpRequest, pk: int, *args, **kwargs) -> Response: Return list of Test Items and attached Jira issues for validation with id=pk
- def post(sel... | f9177abf4fd235ad0aef5bd70ebe6150f1fce7be | <|skeleton|>
class AssingJiraView:
def get(self, request: HttpRequest, pk: int, *args, **kwargs) -> Response:
"""Return list of Test Items and attached Jira issues for validation with id=pk"""
<|body_0|>
def post(self, request: HttpRequest, pk: int, test_result_id: int, defect_id: str) -> Resp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssingJiraView:
def get(self, request: HttpRequest, pk: int, *args, **kwargs) -> Response:
"""Return list of Test Items and attached Jira issues for validation with id=pk"""
validation = get_object_or_404(Validation.objects, pk=pk)
items = []
for item in validation.results.valu... | the_stack_v2_python_sparse | backend/reporting/api/views/jira_issues_report.py | ChangyuHE/justForTestRespository | train | 0 | |
8f05c5c951e0514ff47f1ddc05ca68fb1b7379e7 | [
"operator.create_userfullname = str(operator.create_userfullname)\nif 'str' not in str(type(operator.create_userfullname)):\n create_userfullname_str = '-'.join([str(operator.create_userfullname.year), str(operator.create_userfullname.month), str(operator.create_userfullname.day)])\nelse:\n create_userfullnam... | <|body_start_0|>
operator.create_userfullname = str(operator.create_userfullname)
if 'str' not in str(type(operator.create_userfullname)):
create_userfullname_str = '-'.join([str(operator.create_userfullname.year), str(operator.create_userfullname.month), str(operator.create_userfullname.day... | This class is used by serializer.OperatorPDFSerializer.OperatorPDFSerializer and by serializer.OperatorCSVSerializer.OperatorCSVSerializer . | OperatorListMapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OperatorListMapper:
"""This class is used by serializer.OperatorPDFSerializer.OperatorPDFSerializer and by serializer.OperatorCSVSerializer.OperatorCSVSerializer ."""
def map_to_list(self, operator):
"""creates list of from model.Operator.Operator :param operator: model.Operator.Oper... | stack_v2_sparse_classes_75kplus_train_007053 | 2,021 | no_license | [
{
"docstring": "creates list of from model.Operator.Operator :param operator: model.Operator.Operator :return: list of strings",
"name": "map_to_list",
"signature": "def map_to_list(self, operator)"
},
{
"docstring": "create model.Operator.Operator instance from list of strings - data :param dat... | 2 | null | Implement the Python class `OperatorListMapper` described below.
Class description:
This class is used by serializer.OperatorPDFSerializer.OperatorPDFSerializer and by serializer.OperatorCSVSerializer.OperatorCSVSerializer .
Method signatures and docstrings:
- def map_to_list(self, operator): creates list of from mod... | Implement the Python class `OperatorListMapper` described below.
Class description:
This class is used by serializer.OperatorPDFSerializer.OperatorPDFSerializer and by serializer.OperatorCSVSerializer.OperatorCSVSerializer .
Method signatures and docstrings:
- def map_to_list(self, operator): creates list of from mod... | d710b88193d98662f8972a29e279366dc363f332 | <|skeleton|>
class OperatorListMapper:
"""This class is used by serializer.OperatorPDFSerializer.OperatorPDFSerializer and by serializer.OperatorCSVSerializer.OperatorCSVSerializer ."""
def map_to_list(self, operator):
"""creates list of from model.Operator.Operator :param operator: model.Operator.Oper... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OperatorListMapper:
"""This class is used by serializer.OperatorPDFSerializer.OperatorPDFSerializer and by serializer.OperatorCSVSerializer.OperatorCSVSerializer ."""
def map_to_list(self, operator):
"""creates list of from model.Operator.Operator :param operator: model.Operator.Operator :return:... | the_stack_v2_python_sparse | mapper/OperatorListMapper.py | darkmagic9/PythonSciStudentProject | train | 0 |
51531e0f4022e8f1be1dd60777de8f5a591476b1 | [
"statement = 'if a then b <- 3 endif'\nself.assertEqual(ycc.parse_ps2py(statement).get('errors'), '')\nself.assertEqual(ycc.parse_ps2py(statement).get('result'), 'if a:\\n\\tb = 3')\nstatement = 'if a<3 then b <- 3 endif'\nself.assertEqual(ycc.parse_ps2py(statement).get('errors'), '')\nself.assertEqual(ycc.parse_ps... | <|body_start_0|>
statement = 'if a then b <- 3 endif'
self.assertEqual(ycc.parse_ps2py(statement).get('errors'), '')
self.assertEqual(ycc.parse_ps2py(statement).get('result'), 'if a:\n\tb = 3')
statement = 'if a<3 then b <- 3 endif'
self.assertEqual(ycc.parse_ps2py(statement).get... | Class for testing conditions. | TestConditions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConditions:
"""Class for testing conditions."""
def test_ifcond(self):
"""Tests if-conditions. Keyword arguments: self -- the TestConditions instance"""
<|body_0|>
def test_ifelsecond(self):
"""Tests if-else-conditions. Keyword arguments: self -- the TestCond... | stack_v2_sparse_classes_75kplus_train_007054 | 9,275 | no_license | [
{
"docstring": "Tests if-conditions. Keyword arguments: self -- the TestConditions instance",
"name": "test_ifcond",
"signature": "def test_ifcond(self)"
},
{
"docstring": "Tests if-else-conditions. Keyword arguments: self -- the TestConditions instance",
"name": "test_ifelsecond",
"sign... | 3 | stack_v2_sparse_classes_30k_train_012847 | Implement the Python class `TestConditions` described below.
Class description:
Class for testing conditions.
Method signatures and docstrings:
- def test_ifcond(self): Tests if-conditions. Keyword arguments: self -- the TestConditions instance
- def test_ifelsecond(self): Tests if-else-conditions. Keyword arguments:... | Implement the Python class `TestConditions` described below.
Class description:
Class for testing conditions.
Method signatures and docstrings:
- def test_ifcond(self): Tests if-conditions. Keyword arguments: self -- the TestConditions instance
- def test_ifelsecond(self): Tests if-else-conditions. Keyword arguments:... | 2c0b907f5d9e74265e87ab3e36753f764a965f21 | <|skeleton|>
class TestConditions:
"""Class for testing conditions."""
def test_ifcond(self):
"""Tests if-conditions. Keyword arguments: self -- the TestConditions instance"""
<|body_0|>
def test_ifelsecond(self):
"""Tests if-else-conditions. Keyword arguments: self -- the TestCond... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestConditions:
"""Class for testing conditions."""
def test_ifcond(self):
"""Tests if-conditions. Keyword arguments: self -- the TestConditions instance"""
statement = 'if a then b <- 3 endif'
self.assertEqual(ycc.parse_ps2py(statement).get('errors'), '')
self.assertEqual... | the_stack_v2_python_sparse | AlgoBooster/ab_ui/ab_main/ab_unittests/parser_unittests.py | danielaboeing/algobooster | train | 0 |
ecf0e1889c0920e9e40c245e3381e4ab07b56dc4 | [
"self.config = config\nself.device = config['device_str']\nself.model = CollaborativeMemoryNetwork(config, user_embeddings, item_embeddings, item_user_list, self.device)\nself.regs = config['regs']\nself.batch_size = config['batch_size']\nself.optimizer = torch.optim.RMSprop(self.model.parameters(), lr=config['lr']... | <|body_start_0|>
self.config = config
self.device = config['device_str']
self.model = CollaborativeMemoryNetwork(config, user_embeddings, item_embeddings, item_user_list, self.device)
self.regs = config['regs']
self.batch_size = config['batch_size']
self.optimizer = torch... | CMN Engine. | cmnEngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cmnEngine:
"""CMN Engine."""
def __init__(self, config, user_embeddings, item_embeddings, item_user_list):
"""Initialize CMN Engine."""
<|body_0|>
def train_single_batch(self, batch_data):
"""Train a single batch data. Train a single batch data. Args: batch_data ... | stack_v2_sparse_classes_75kplus_train_007055 | 9,498 | permissive | [
{
"docstring": "Initialize CMN Engine.",
"name": "__init__",
"signature": "def __init__(self, config, user_embeddings, item_embeddings, item_user_list)"
},
{
"docstring": "Train a single batch data. Train a single batch data. Args: batch_data (list): batch users, positive items and negative item... | 4 | stack_v2_sparse_classes_30k_train_001981 | Implement the Python class `cmnEngine` described below.
Class description:
CMN Engine.
Method signatures and docstrings:
- def __init__(self, config, user_embeddings, item_embeddings, item_user_list): Initialize CMN Engine.
- def train_single_batch(self, batch_data): Train a single batch data. Train a single batch da... | Implement the Python class `cmnEngine` described below.
Class description:
CMN Engine.
Method signatures and docstrings:
- def __init__(self, config, user_embeddings, item_embeddings, item_user_list): Initialize CMN Engine.
- def train_single_batch(self, batch_data): Train a single batch data. Train a single batch da... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class cmnEngine:
"""CMN Engine."""
def __init__(self, config, user_embeddings, item_embeddings, item_user_list):
"""Initialize CMN Engine."""
<|body_0|>
def train_single_batch(self, batch_data):
"""Train a single batch data. Train a single batch data. Args: batch_data ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class cmnEngine:
"""CMN Engine."""
def __init__(self, config, user_embeddings, item_embeddings, item_user_list):
"""Initialize CMN Engine."""
self.config = config
self.device = config['device_str']
self.model = CollaborativeMemoryNetwork(config, user_embeddings, item_embeddings,... | the_stack_v2_python_sparse | beta_rec/models/cmn.py | beta-team/beta-recsys | train | 156 |
7d7e04be5b580e152c47d3ebaecf4b619e0c7e74 | [
"self.tokenizer = Tokenizer(num_words=None, oov_token='oovtok', lower=False)\nself.enc2targs = defaultdict(set)\nself.targ2int = {}\nself.train_dir = train_dir\nself.targ_file = targ_file\nself.model_dir = model_dir\nself.min_examples_per_targ = min_examples_per_targ\nif os.path.isdir(model_dir):\n shutil.rmtree... | <|body_start_0|>
self.tokenizer = Tokenizer(num_words=None, oov_token='oovtok', lower=False)
self.enc2targs = defaultdict(set)
self.targ2int = {}
self.train_dir = train_dir
self.targ_file = targ_file
self.model_dir = model_dir
self.min_examples_per_targ = min_exam... | Make x and y from raw data | DatasetProvider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetProvider:
"""Make x and y from raw data"""
def __init__(self, train_dir, targ_file, model_dir, min_examples_per_targ):
"""Constructor"""
<|body_0|>
def index_targets(self):
"""Process medication file"""
<|body_1|>
def load(self):
"""Pr... | stack_v2_sparse_classes_75kplus_train_007056 | 3,543 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, train_dir, targ_file, model_dir, min_examples_per_targ)"
},
{
"docstring": "Process medication file",
"name": "index_targets",
"signature": "def index_targets(self)"
},
{
"docstring": "Process note... | 3 | null | Implement the Python class `DatasetProvider` described below.
Class description:
Make x and y from raw data
Method signatures and docstrings:
- def __init__(self, train_dir, targ_file, model_dir, min_examples_per_targ): Constructor
- def index_targets(self): Process medication file
- def load(self): Process notes to ... | Implement the Python class `DatasetProvider` described below.
Class description:
Make x and y from raw data
Method signatures and docstrings:
- def __init__(self, train_dir, targ_file, model_dir, min_examples_per_targ): Constructor
- def index_targets(self): Process medication file
- def load(self): Process notes to ... | 4fcb7aa9c5f7ed41277f6b369aff3b36ad47a118 | <|skeleton|>
class DatasetProvider:
"""Make x and y from raw data"""
def __init__(self, train_dir, targ_file, model_dir, min_examples_per_targ):
"""Constructor"""
<|body_0|>
def index_targets(self):
"""Process medication file"""
<|body_1|>
def load(self):
"""Pr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatasetProvider:
"""Make x and y from raw data"""
def __init__(self, train_dir, targ_file, model_dir, min_examples_per_targ):
"""Constructor"""
self.tokenizer = Tokenizer(num_words=None, oov_token='oovtok', lower=False)
self.enc2targs = defaultdict(set)
self.targ2int = {}
... | the_stack_v2_python_sparse | Meds/dataset.py | dmitriydligach/Universal | train | 1 |
26d6e211c524aae3668176e7f54638f589b9226c | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"while len(self.x_values) < self.num_points:\n x_direction = choice([1, -1])\n x_distance = choice([0, 1, 2, 3, 4])\n x_step = x_direction * x_distance\n y_direction = choice([1, -1])\n y_distance = choice([0, 1, 2, 3, 4])\n ... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
while len(self.x_values) < self.num_points:
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction *... | Generates random walks. | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""Generates random walks."""
def __init__(self, num_points=5000):
"""Initializes walk attributes."""
<|body_0|>
def fill_walk(self):
"""Calculate all the points in a walk."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.num_poi... | stack_v2_sparse_classes_75kplus_train_007057 | 945 | no_license | [
{
"docstring": "Initializes walk attributes.",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "Calculate all the points in a walk.",
"name": "fill_walk",
"signature": "def fill_walk(self)"
}
] | 2 | null | Implement the Python class `RandomWalk` described below.
Class description:
Generates random walks.
Method signatures and docstrings:
- def __init__(self, num_points=5000): Initializes walk attributes.
- def fill_walk(self): Calculate all the points in a walk. | Implement the Python class `RandomWalk` described below.
Class description:
Generates random walks.
Method signatures and docstrings:
- def __init__(self, num_points=5000): Initializes walk attributes.
- def fill_walk(self): Calculate all the points in a walk.
<|skeleton|>
class RandomWalk:
"""Generates random w... | 811981a8ac07922b5e435e23329466a380b8f795 | <|skeleton|>
class RandomWalk:
"""Generates random walks."""
def __init__(self, num_points=5000):
"""Initializes walk attributes."""
<|body_0|>
def fill_walk(self):
"""Calculate all the points in a walk."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomWalk:
"""Generates random walks."""
def __init__(self, num_points=5000):
"""Initializes walk attributes."""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""Calculate all the points in a walk."""
while ... | the_stack_v2_python_sparse | Ch. 15/random_walk.py | nicholasrokosz/python-crash-course | train | 0 |
6f3c36b84bab5d454c3f756b23101caf4dde89dc | [
"super(EncoderBlock, self).__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(... | <|body_start_0|>
super(EncoderBlock, self).__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)
... | Encoder block for a transformer | EncoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderBlock:
"""Encoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""initialization"""
<|body_0|>
def call(self, x, training, mask):
"""call function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Encod... | stack_v2_sparse_classes_75kplus_train_007058 | 1,234 | no_license | [
{
"docstring": "initialization",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "call function",
"name": "call",
"signature": "def call(self, x, training, mask)"
}
] | 2 | null | Implement the Python class `EncoderBlock` described below.
Class description:
Encoder block for a transformer
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): initialization
- def call(self, x, training, mask): call function | Implement the Python class `EncoderBlock` described below.
Class description:
Encoder block for a transformer
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): initialization
- def call(self, x, training, mask): call function
<|skeleton|>
class EncoderBlock:
"""Encoder block f... | 16dc37d1c6dc00a271053b60724c51763914029a | <|skeleton|>
class EncoderBlock:
"""Encoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""initialization"""
<|body_0|>
def call(self, x, training, mask):
"""call function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EncoderBlock:
"""Encoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""initialization"""
super(EncoderBlock, self).__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/7-transformer_encoder_block.py | jaycer95/holbertonschool-machine_learning | train | 0 |
577775ef0368b510bb27cb1d2f3ef08829db1ace | [
"self.is_game_over = False\nself.board = board\nself.is_legal = legal_function\nself.is_winning = winning_function",
"current_move = self.ask_for_move(board, player, None)\nprev_move_list = []\nis_turn_over = False\nwinning_player = None\nwhile not is_turn_over:\n current_move = player.move(board)\n if curr... | <|body_start_0|>
self.is_game_over = False
self.board = board
self.is_legal = legal_function
self.is_winning = winning_function
<|end_body_0|>
<|body_start_1|>
current_move = self.ask_for_move(board, player, None)
prev_move_list = []
is_turn_over = False
... | Referee | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Referee:
def __init__(self, board, legal_function=lambda x: None, winning_function=lambda x: None):
"""This class models a referee for a game. Args: board : The board of the game being played``"""
<|body_0|>
def update_board(self, board, player, other_player) -> object:
... | stack_v2_sparse_classes_75kplus_train_007059 | 3,100 | no_license | [
{
"docstring": "This class models a referee for a game. Args: board : The board of the game being played``",
"name": "__init__",
"signature": "def __init__(self, board, legal_function=lambda x: None, winning_function=lambda x: None)"
},
{
"docstring": "This method will handle updating the game b... | 3 | stack_v2_sparse_classes_30k_train_026660 | Implement the Python class `Referee` described below.
Class description:
Implement the Referee class.
Method signatures and docstrings:
- def __init__(self, board, legal_function=lambda x: None, winning_function=lambda x: None): This class models a referee for a game. Args: board : The board of the game being played`... | Implement the Python class `Referee` described below.
Class description:
Implement the Referee class.
Method signatures and docstrings:
- def __init__(self, board, legal_function=lambda x: None, winning_function=lambda x: None): This class models a referee for a game. Args: board : The board of the game being played`... | 4ec458d10bc6a377df212ebffe60562ee281c678 | <|skeleton|>
class Referee:
def __init__(self, board, legal_function=lambda x: None, winning_function=lambda x: None):
"""This class models a referee for a game. Args: board : The board of the game being played``"""
<|body_0|>
def update_board(self, board, player, other_player) -> object:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Referee:
def __init__(self, board, legal_function=lambda x: None, winning_function=lambda x: None):
"""This class models a referee for a game. Args: board : The board of the game being played``"""
self.is_game_over = False
self.board = board
self.is_legal = legal_function
... | the_stack_v2_python_sparse | simple_games/generic_classes/referee.py | andrewpenland/TwoPlayerGames | train | 0 | |
56d5e0e35200bf6629d652c3bac6fd3f4f6121d5 | [
"self.data_point_vec = data_point_vec\nself.metric_name = metric_name\nself.mtype = mtype",
"if dictionary is None:\n return None\ndata_point_vec = None\nif dictionary.get('dataPointVec') != None:\n data_point_vec = list()\n for structure in dictionary.get('dataPointVec'):\n data_point_vec.append(... | <|body_start_0|>
self.data_point_vec = data_point_vec
self.metric_name = metric_name
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
data_point_vec = None
if dictionary.get('dataPointVec') != None:
data_point_... | Implementation of the 'MetricDataBlock' model. Specifies a series of metric data points for a time series. Attributes: data_point_vec (list of MetricDataPoint): Array of Data Points. Specifies a list of metric data points for a time series. metric_name (string): Specifies the name of a metric such as 'kDiskAwaitTimeMse... | MetricDataBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricDataBlock:
"""Implementation of the 'MetricDataBlock' model. Specifies a series of metric data points for a time series. Attributes: data_point_vec (list of MetricDataPoint): Array of Data Points. Specifies a list of metric data points for a time series. metric_name (string): Specifies the ... | stack_v2_sparse_classes_75kplus_train_007060 | 2,460 | permissive | [
{
"docstring": "Constructor for the MetricDataBlock class",
"name": "__init__",
"signature": "def __init__(self, data_point_vec=None, metric_name=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation o... | 2 | stack_v2_sparse_classes_30k_val_002082 | Implement the Python class `MetricDataBlock` described below.
Class description:
Implementation of the 'MetricDataBlock' model. Specifies a series of metric data points for a time series. Attributes: data_point_vec (list of MetricDataPoint): Array of Data Points. Specifies a list of metric data points for a time serie... | Implement the Python class `MetricDataBlock` described below.
Class description:
Implementation of the 'MetricDataBlock' model. Specifies a series of metric data points for a time series. Attributes: data_point_vec (list of MetricDataPoint): Array of Data Points. Specifies a list of metric data points for a time serie... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class MetricDataBlock:
"""Implementation of the 'MetricDataBlock' model. Specifies a series of metric data points for a time series. Attributes: data_point_vec (list of MetricDataPoint): Array of Data Points. Specifies a list of metric data points for a time series. metric_name (string): Specifies the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetricDataBlock:
"""Implementation of the 'MetricDataBlock' model. Specifies a series of metric data points for a time series. Attributes: data_point_vec (list of MetricDataPoint): Array of Data Points. Specifies a list of metric data points for a time series. metric_name (string): Specifies the name of a met... | the_stack_v2_python_sparse | cohesity_management_sdk/models/metric_data_block.py | cohesity/management-sdk-python | train | 24 |
97ba2c8dbb90199871ebead20570ddb79ccca4d5 | [
"try:\n movie = db.get_movie_by_id(list_id=list_id, movie_id=movie_id, session=session)\nexcept NoResultFound:\n raise NotFoundError('could not find movie with id %d in list %d' % (movie_id, list_id))\nreturn jsonify(movie.to_dict())",
"try:\n movie = db.get_movie_by_id(list_id=list_id, movie_id=movie_id... | <|body_start_0|>
try:
movie = db.get_movie_by_id(list_id=list_id, movie_id=movie_id, session=session)
except NoResultFound:
raise NotFoundError('could not find movie with id %d in list %d' % (movie_id, list_id))
return jsonify(movie.to_dict())
<|end_body_0|>
<|body_start... | MovieListMovieAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovieListMovieAPI:
def get(self, list_id, movie_id, session=None):
"""Get a movie by list ID and movie ID"""
<|body_0|>
def delete(self, list_id, movie_id, session=None):
"""Delete a movie by list ID and movie ID"""
<|body_1|>
def put(self, list_id, movi... | stack_v2_sparse_classes_75kplus_train_007061 | 12,846 | permissive | [
{
"docstring": "Get a movie by list ID and movie ID",
"name": "get",
"signature": "def get(self, list_id, movie_id, session=None)"
},
{
"docstring": "Delete a movie by list ID and movie ID",
"name": "delete",
"signature": "def delete(self, list_id, movie_id, session=None)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_036662 | Implement the Python class `MovieListMovieAPI` described below.
Class description:
Implement the MovieListMovieAPI class.
Method signatures and docstrings:
- def get(self, list_id, movie_id, session=None): Get a movie by list ID and movie ID
- def delete(self, list_id, movie_id, session=None): Delete a movie by list ... | Implement the Python class `MovieListMovieAPI` described below.
Class description:
Implement the MovieListMovieAPI class.
Method signatures and docstrings:
- def get(self, list_id, movie_id, session=None): Get a movie by list ID and movie ID
- def delete(self, list_id, movie_id, session=None): Delete a movie by list ... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class MovieListMovieAPI:
def get(self, list_id, movie_id, session=None):
"""Get a movie by list ID and movie ID"""
<|body_0|>
def delete(self, list_id, movie_id, session=None):
"""Delete a movie by list ID and movie ID"""
<|body_1|>
def put(self, list_id, movi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovieListMovieAPI:
def get(self, list_id, movie_id, session=None):
"""Get a movie by list ID and movie ID"""
try:
movie = db.get_movie_by_id(list_id=list_id, movie_id=movie_id, session=session)
except NoResultFound:
raise NotFoundError('could not find movie with... | the_stack_v2_python_sparse | flexget/components/managed_lists/lists/movie_list/api.py | BrutuZ/Flexget | train | 1 | |
4e611717f2cacd7ba2b28d4fc72a41a17544449d | [
"for n in range(1, 10):\n moves = tower_of_hanoi(n, 'a', 'b', 'c')\n self.assertEqual(len(moves), 2 ** n - 1)",
"moves = tower_of_hanoi(3, 'a', 'b', 'c')\nlen_moves = 2 ** 3 - 1\nexpected_moves = [['a', 'b'], ['a', 'c'], ['b', 'c'], ['a', 'b'], ['c', 'a'], ['c', 'b'], ['a', 'b']]\nself.assertEqual(len(moves... | <|body_start_0|>
for n in range(1, 10):
moves = tower_of_hanoi(n, 'a', 'b', 'c')
self.assertEqual(len(moves), 2 ** n - 1)
<|end_body_0|>
<|body_start_1|>
moves = tower_of_hanoi(3, 'a', 'b', 'c')
len_moves = 2 ** 3 - 1
expected_moves = [['a', 'b'], ['a', 'c'], ['b... | Test Tower of Hanoi. | TestTowerOfHanoi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTowerOfHanoi:
"""Test Tower of Hanoi."""
def test_n(self):
"""Test n."""
<|body_0|>
def test_3(self):
"""Test 3."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for n in range(1, 10):
moves = tower_of_hanoi(n, 'a', 'b', 'c')
... | stack_v2_sparse_classes_75kplus_train_007062 | 4,475 | no_license | [
{
"docstring": "Test n.",
"name": "test_n",
"signature": "def test_n(self)"
},
{
"docstring": "Test 3.",
"name": "test_3",
"signature": "def test_3(self)"
}
] | 2 | null | Implement the Python class `TestTowerOfHanoi` described below.
Class description:
Test Tower of Hanoi.
Method signatures and docstrings:
- def test_n(self): Test n.
- def test_3(self): Test 3. | Implement the Python class `TestTowerOfHanoi` described below.
Class description:
Test Tower of Hanoi.
Method signatures and docstrings:
- def test_n(self): Test n.
- def test_3(self): Test 3.
<|skeleton|>
class TestTowerOfHanoi:
"""Test Tower of Hanoi."""
def test_n(self):
"""Test n."""
<|b... | 8b01517c9cc3a9b07e6a103d52b87b5f56c4d394 | <|skeleton|>
class TestTowerOfHanoi:
"""Test Tower of Hanoi."""
def test_n(self):
"""Test n."""
<|body_0|>
def test_3(self):
"""Test 3."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestTowerOfHanoi:
"""Test Tower of Hanoi."""
def test_n(self):
"""Test n."""
for n in range(1, 10):
moves = tower_of_hanoi(n, 'a', 'b', 'c')
self.assertEqual(len(moves), 2 ** n - 1)
def test_3(self):
"""Test 3."""
moves = tower_of_hanoi(3, 'a',... | the_stack_v2_python_sparse | Recursion/test_what_is_recursion.py | ohduran/problemsolvingalgorithms | train | 0 |
ca29d42d1bed4bac7ffb6edb0e8ab94fd5891b5f | [
"super().__init__()\nself.pos_iou_thr = desc['pos_iou_thr']\nself.neg_iou_thr = desc['neg_iou_thr']\nself.min_pos_iou = desc['min_pos_iou'] if 'min_pos_iou' in desc else 0.0\nself.gt_max_assign_all = desc['gt_max_assign_all'] if 'gt_max_assign_all' in desc else True\nself.ignore_iof_thr = desc['ignore_iof_thr'] if ... | <|body_start_0|>
super().__init__()
self.pos_iou_thr = desc['pos_iou_thr']
self.neg_iou_thr = desc['neg_iou_thr']
self.min_pos_iou = desc['min_pos_iou'] if 'min_pos_iou' in desc else 0.0
self.gt_max_assign_all = desc['gt_max_assign_all'] if 'gt_max_assign_all' in desc else True
... | All negative assigner use max iou. | MaxIoUAllNegAssigner | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxIoUAllNegAssigner:
"""All negative assigner use max iou."""
def __init__(self, desc):
"""Init Max iou all neg assigner. :param desc: config dict"""
<|body_0|>
def assign(self, bboxes, gt_bboxes, gt_bboxes_ignore=None, gt_labels=None):
"""Assign. :param bboxes:... | stack_v2_sparse_classes_75kplus_train_007063 | 5,437 | permissive | [
{
"docstring": "Init Max iou all neg assigner. :param desc: config dict",
"name": "__init__",
"signature": "def __init__(self, desc)"
},
{
"docstring": "Assign. :param bboxes: bboxes :param gt_bboxes: ground truth boxes :param gt_bboxes_ignore: ground truth boxes need to be ignored :param gt_lab... | 3 | stack_v2_sparse_classes_30k_train_049382 | Implement the Python class `MaxIoUAllNegAssigner` described below.
Class description:
All negative assigner use max iou.
Method signatures and docstrings:
- def __init__(self, desc): Init Max iou all neg assigner. :param desc: config dict
- def assign(self, bboxes, gt_bboxes, gt_bboxes_ignore=None, gt_labels=None): A... | Implement the Python class `MaxIoUAllNegAssigner` described below.
Class description:
All negative assigner use max iou.
Method signatures and docstrings:
- def __init__(self, desc): Init Max iou all neg assigner. :param desc: config dict
- def assign(self, bboxes, gt_bboxes, gt_bboxes_ignore=None, gt_labels=None): A... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class MaxIoUAllNegAssigner:
"""All negative assigner use max iou."""
def __init__(self, desc):
"""Init Max iou all neg assigner. :param desc: config dict"""
<|body_0|>
def assign(self, bboxes, gt_bboxes, gt_bboxes_ignore=None, gt_labels=None):
"""Assign. :param bboxes:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaxIoUAllNegAssigner:
"""All negative assigner use max iou."""
def __init__(self, desc):
"""Init Max iou all neg assigner. :param desc: config dict"""
super().__init__()
self.pos_iou_thr = desc['pos_iou_thr']
self.neg_iou_thr = desc['neg_iou_thr']
self.min_pos_iou ... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/pytorch/utils/bbox_utils/assigner/all_neg_assigner.py | Huawei-Ascend/modelzoo | train | 1 |
98d1d8a708a1b16ac650b4e544af3495781d7e19 | [
"tenant_id = self.request.user.tenant_id\nipsecsiteconnections = api.vpn.ipsecsiteconnection_list(request, tenant_id=tenant_id)\nreturn {'items': [u.to_dict() for u in ipsecsiteconnections]}",
"new_ipsecsiteconnection = api.vpn.ipsecsiteconnection_create(request, **request.DATA)\ni = api.vpn.ipsecsiteconnection_g... | <|body_start_0|>
tenant_id = self.request.user.tenant_id
ipsecsiteconnections = api.vpn.ipsecsiteconnection_list(request, tenant_id=tenant_id)
return {'items': [u.to_dict() for u in ipsecsiteconnections]}
<|end_body_0|>
<|body_start_1|>
new_ipsecsiteconnection = api.vpn.ipsecsiteconnect... | API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html | IPSecSiteConnections | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPSecSiteConnections:
"""API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html"""
def get(self, request):
"""Get a list of ikepolicies for a project The listing result is an object with property "items". Each item is a network."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_007064 | 11,907 | permissive | [
{
"docstring": "Get a list of ikepolicies for a project The listing result is an object with property \"items\". Each item is a network.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Create IPSecSiteConnection :param request: request context :param name: name for IPSe... | 2 | stack_v2_sparse_classes_30k_train_053749 | Implement the Python class `IPSecSiteConnections` described below.
Class description:
API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html
Method signatures and docstrings:
- def get(self, request): Get a list of ikepolicies for a project The listing result is an object with property "it... | Implement the Python class `IPSecSiteConnections` described below.
Class description:
API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html
Method signatures and docstrings:
- def get(self, request): Get a list of ikepolicies for a project The listing result is an object with property "it... | 9524f1952461c83db485d5d1702c350b158d7ce0 | <|skeleton|>
class IPSecSiteConnections:
"""API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html"""
def get(self, request):
"""Get a list of ikepolicies for a project The listing result is an object with property "items". Each item is a network."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IPSecSiteConnections:
"""API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html"""
def get(self, request):
"""Get a list of ikepolicies for a project The listing result is an object with property "items". Each item is a network."""
tenant_id = self.request.user... | the_stack_v2_python_sparse | easystack_dashboard/api/rest/vpn.py | oksbsb/horizon-acc | train | 0 |
a45bd42e3b29a6af758443782d1d7d411982823b | [
"super(Decoder, self).__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(target_vocab, dm)\nself.positional_encoding = positional_encoding(max_seq_len, dm)\nself.blocks = [DecoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]\nself.dropout = tf.keras.layers.Dropout(drop_rate)",
"... | <|body_start_0|>
super(Decoder, self).__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(target_vocab, dm)
self.positional_encoding = positional_encoding(max_seq_len, dm)
self.blocks = [DecoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]
... | Decoder class for machine translation | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Decoder class for machine translation"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""[summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] target_vocab ([type]):... | stack_v2_sparse_classes_75kplus_train_007065 | 12,086 | no_license | [
{
"docstring": "[summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] target_vocab ([type]): [description] max_seq_len ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.",
"name": "__init__",
"signa... | 2 | stack_v2_sparse_classes_30k_train_048103 | Implement the Python class `Decoder` described below.
Class description:
Decoder class for machine translation
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1): [summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [descripti... | Implement the Python class `Decoder` described below.
Class description:
Decoder class for machine translation
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1): [summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [descripti... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class Decoder:
"""Decoder class for machine translation"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""[summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] target_vocab ([type]):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decoder:
"""Decoder class for machine translation"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""[summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] target_vocab ([type]): [description... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
2bb855a3d7f5bc9fd694dd4c61ae17dc624cc0af | [
"if not p:\n return not s\nfirst_match = bool(s) and p[0] in {s[0], '.'}\nif len(p) >= 2 and p[1] == '*':\n return self.isMatch(s, p[2:]) or (first_match and self.isMatch(s[1:], p))\nelse:\n return first_match and self.isMatch(s[1:], p[1:])",
"def charMatch(i, j):\n if i < 0:\n return False\n ... | <|body_start_0|>
if not p:
return not s
first_match = bool(s) and p[0] in {s[0], '.'}
if len(p) >= 2 and p[1] == '*':
return self.isMatch(s, p[2:]) or (first_match and self.isMatch(s[1:], p))
else:
return first_match and self.isMatch(s[1:], p[1:])
<|en... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_0|>
def otherIsMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not p:
return not s
... | stack_v2_sparse_classes_75kplus_train_007066 | 1,239 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: bool",
"name": "isMatch",
"signature": "def isMatch(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: bool",
"name": "otherIsMatch",
"signature": "def otherIsMatch(self, s, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009306 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
- def otherIsMatch(self, s, p): :type s: str :type p: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
- def otherIsMatch(self, s, p): :type s: str :type p: str :rtype: bool
<|skeleton|>
class Solution:
def isMa... | e178f91ebffff06977e8c231de12786a72b3b13d | <|skeleton|>
class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_0|>
def otherIsMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
if not p:
return not s
first_match = bool(s) and p[0] in {s[0], '.'}
if len(p) >= 2 and p[1] == '*':
return self.isMatch(s, p[2:]) or (first_match and self.isMatch(s[1:], p))... | the_stack_v2_python_sparse | iamsochun/Leetcode10.py | moonlight035/algorithm | train | 0 | |
074f616a41123d13a08d584651f97c99aad3f450 | [
"self._filename: str = filename\nself._seen_so_far: float = 0\nself._lock = threading.Lock()\nself._size: float = 0\nif bucket and client:\n if not version_id:\n self._size = client.head_object(Bucket=bucket, Key=filename).get('ContentLength')\n else:\n self._size = client.head_object(Bucket=buc... | <|body_start_0|>
self._filename: str = filename
self._seen_so_far: float = 0
self._lock = threading.Lock()
self._size: float = 0
if bucket and client:
if not version_id:
self._size = client.head_object(Bucket=bucket, Key=filename).get('ContentLength')
... | The progress bar for s3 transfering. Helper class for displaying s3 upload/download/copy percentage. Upload: spcify the filename only. Download/Copy: require a bucket and client parameter as well as the filename. This class should be used within the callback of the S3Transfer class from boto. references: https://boto3.... | S3Progress | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3Progress:
"""The progress bar for s3 transfering. Helper class for displaying s3 upload/download/copy percentage. Upload: spcify the filename only. Download/Copy: require a bucket and client parameter as well as the filename. This class should be used within the callback of the S3Transfer class... | stack_v2_sparse_classes_75kplus_train_007067 | 3,490 | permissive | [
{
"docstring": "Construct the progress bar instance.",
"name": "__init__",
"signature": "def __init__(self, filename: str, bucket: str=None, client=None, version_id: str=None) -> None"
},
{
"docstring": "Create the bar. Locking the thread to a single file.",
"name": "__call__",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_041700 | Implement the Python class `S3Progress` described below.
Class description:
The progress bar for s3 transfering. Helper class for displaying s3 upload/download/copy percentage. Upload: spcify the filename only. Download/Copy: require a bucket and client parameter as well as the filename. This class should be used with... | Implement the Python class `S3Progress` described below.
Class description:
The progress bar for s3 transfering. Helper class for displaying s3 upload/download/copy percentage. Upload: spcify the filename only. Download/Copy: require a bucket and client parameter as well as the filename. This class should be used with... | 4abefb2301f7b489b11ed3f0b303faafa5941d5b | <|skeleton|>
class S3Progress:
"""The progress bar for s3 transfering. Helper class for displaying s3 upload/download/copy percentage. Upload: spcify the filename only. Download/Copy: require a bucket and client parameter as well as the filename. This class should be used within the callback of the S3Transfer class... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class S3Progress:
"""The progress bar for s3 transfering. Helper class for displaying s3 upload/download/copy percentage. Upload: spcify the filename only. Download/Copy: require a bucket and client parameter as well as the filename. This class should be used within the callback of the S3Transfer class from boto. r... | the_stack_v2_python_sparse | fzfaws/s3/helper/s3progress.py | kazhala/fzf.aws | train | 68 |
3ab3ff2e12a7bf30f41febfbde312a1df96c64de | [
"self.dictionary = set(dictionary)\nself.count = {}\nfor word in self.dictionary:\n if len(word) >= 3:\n abbr = word[0] + str(len(word) - 1) + word[-1]\n else:\n abbr = word\n if abbr not in self.count:\n self.count[abbr] = 1\n else:\n self.count[abbr] = 2",
"if len(word) >... | <|body_start_0|>
self.dictionary = set(dictionary)
self.count = {}
for word in self.dictionary:
if len(word) >= 3:
abbr = word[0] + str(len(word) - 1) + word[-1]
else:
abbr = word
if abbr not in self.count:
self.... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
"""check if a word is unique. :type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_007068 | 893 | no_license | [
{
"docstring": "initialize your data structure here. :type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": "check if a word is unique. :type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
... | 2 | stack_v2_sparse_classes_30k_train_012680 | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str]
- def isUnique(self, word): check if a word is unique. :type word: str ... | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str]
- def isUnique(self, word): check if a word is unique. :type word: str ... | 15f012927dc34b5d751af6633caa5e8882d26ff7 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
"""check if a word is unique. :type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
self.dictionary = set(dictionary)
self.count = {}
for word in self.dictionary:
if len(word) >= 3:
abbr = word[0] + str(len(word) - 1... | the_stack_v2_python_sparse | python/288.UniqueWordAbbreviation.py | MaxPoon/Leetcode | train | 15 | |
2944f6f3ab6fcc732264db3ce87dc8c8234e4075 | [
"super().__init__()\nself.rnn_type = rnn_type\nself.input_size = input_size\nself.hidden_size = hidden_size\nself.enforce_sorted = enforce_sorted\nif rnn_type in ['lstm', 'gru']:\n if kwargs:\n logger.warn(f\"The following '{kwargs}' will be ignored \" + \"as they are only considered when using 'sru' as \... | <|body_start_0|>
super().__init__()
self.rnn_type = rnn_type
self.input_size = input_size
self.hidden_size = hidden_size
self.enforce_sorted = enforce_sorted
if rnn_type in ['lstm', 'gru']:
if kwargs:
logger.warn(f"The following '{kwargs}' will... | Implements a multi-layer RNN. This module can be used to create multi-layer RNN models, and provides a way to reduce to output of the RNN to a single hidden state by pooling the encoder states either by taking the maximum, average, or by taking the last hidden state before padding. Padding is delt with by using torch's... | RNNEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""Implements a multi-layer RNN. This module can be used to create multi-layer RNN models, and provides a way to reduce to output of the RNN to a single hidden state by pooling the encoder states either by taking the maximum, average, or by taking the last hidden state before padding.... | stack_v2_sparse_classes_75kplus_train_007069 | 9,960 | permissive | [
{
"docstring": "Initializes the RNNEncoder object. Parameters ---------- input_size : int The dimension the input data hidden_size : int The hidden dimension to encode the data in n_layers : int, optional The number of rnn layers, defaults to 1 rnn_type : str, optional The type of rnn cell, one of: `lstm`, `gru... | 2 | stack_v2_sparse_classes_30k_train_022209 | Implement the Python class `RNNEncoder` described below.
Class description:
Implements a multi-layer RNN. This module can be used to create multi-layer RNN models, and provides a way to reduce to output of the RNN to a single hidden state by pooling the encoder states either by taking the maximum, average, or by takin... | Implement the Python class `RNNEncoder` described below.
Class description:
Implements a multi-layer RNN. This module can be used to create multi-layer RNN models, and provides a way to reduce to output of the RNN to a single hidden state by pooling the encoder states either by taking the maximum, average, or by takin... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class RNNEncoder:
"""Implements a multi-layer RNN. This module can be used to create multi-layer RNN models, and provides a way to reduce to output of the RNN to a single hidden state by pooling the encoder states either by taking the maximum, average, or by taking the last hidden state before padding.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNEncoder:
"""Implements a multi-layer RNN. This module can be used to create multi-layer RNN models, and provides a way to reduce to output of the RNN to a single hidden state by pooling the encoder states either by taking the maximum, average, or by taking the last hidden state before padding. Padding is d... | the_stack_v2_python_sparse | flambe/nn/rnn.py | cle-ros/flambe | train | 1 |
de5046c3c097aa3d4113f44fb92654c9c4a67e9a | [
"vowerls = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\nleft = 0\ns = list(s)\nright = len(s) - 1\nwhile left < right:\n if s[left] in vowerls:\n if s[right] in vowerls:\n s[left], s[right] = (s[right], s[left])\n left += 1\n right -= 1\n else:\n r... | <|body_start_0|>
vowerls = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
left = 0
s = list(s)
right = len(s) - 1
while left < right:
if s[left] in vowerls:
if s[right] in vowerls:
s[left], s[right] = (s[right], s[left])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels1(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
vowerls = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
... | stack_v2_sparse_classes_75kplus_train_007070 | 1,824 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels",
"signature": "def reverseVowels(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels1",
"signature": "def reverseVowels1(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047137 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels1(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels1(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def reverseVowels(self, s):
... | 70b7a0f031ef4bc1b04ae787ac1fd78f2f25a04d | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels1(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
vowerls = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
left = 0
s = list(s)
right = len(s) - 1
while left < right:
if s[left] in vowerls:
if s[right] in vowerl... | the_stack_v2_python_sparse | doubleHand/345reverseVowels.py | tzhou2018/LeetCode | train | 6 | |
9cca4d0436123088fc965a428d3ef9cdc99d9176 | [
"if not root:\n return True\nif not self.isValidBST(root.left):\n return False\nif not self.isValidBST(root.right):\n return False\nif root.left:\n if not self.get_largest(root.left) < root.val:\n return False\nif root.right:\n if not root.val < self.get_smallest(root.right):\n return F... | <|body_start_0|>
if not root:
return True
if not self.isValidBST(root.left):
return False
if not self.isValidBST(root.right):
return False
if root.left:
if not self.get_largest(root.left) < root.val:
return False
if ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidBST(self, root):
"""Google Phone Interview Question, 20 Sep 2013 recursive dfs alternative answer: convert the tree the array and judge whether it is sorted :param root: a tree node :return: boolean"""
<|body_0|>
def get_largest(self, root):
"""p... | stack_v2_sparse_classes_75kplus_train_007071 | 1,874 | permissive | [
{
"docstring": "Google Phone Interview Question, 20 Sep 2013 recursive dfs alternative answer: convert the tree the array and judge whether it is sorted :param root: a tree node :return: boolean",
"name": "isValidBST",
"signature": "def isValidBST(self, root)"
},
{
"docstring": "possible dp :par... | 3 | stack_v2_sparse_classes_30k_train_008162 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root): Google Phone Interview Question, 20 Sep 2013 recursive dfs alternative answer: convert the tree the array and judge whether it is sorted :param root: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root): Google Phone Interview Question, 20 Sep 2013 recursive dfs alternative answer: convert the tree the array and judge whether it is sorted :param root: ... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def isValidBST(self, root):
"""Google Phone Interview Question, 20 Sep 2013 recursive dfs alternative answer: convert the tree the array and judge whether it is sorted :param root: a tree node :return: boolean"""
<|body_0|>
def get_largest(self, root):
"""p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isValidBST(self, root):
"""Google Phone Interview Question, 20 Sep 2013 recursive dfs alternative answer: convert the tree the array and judge whether it is sorted :param root: a tree node :return: boolean"""
if not root:
return True
if not self.isValidBST(roo... | the_stack_v2_python_sparse | 098 Validate Binary Search Tree.py | Aminaba123/LeetCode | train | 1 | |
cb4d63f5ec7b397f980cb7810c8f5a9f0551b2d5 | [
"self.hparams = ultra.utils.hparams.HParams(hidden_layer_sizes=[512, 256, 128], activation_func='elu', initializer='None', norm='layer', output_size=1)\nself.hparams.parse(hparams_str)\nself.initializer = None\nself.act_func = None\nself.layer_norm = None\nif self.hparams.activation_func in BaseRankingModel.ACT_FUN... | <|body_start_0|>
self.hparams = ultra.utils.hparams.HParams(hidden_layer_sizes=[512, 256, 128], activation_func='elu', initializer='None', norm='layer', output_size=1)
self.hparams.parse(hparams_str)
self.initializer = None
self.act_func = None
self.layer_norm = None
if s... | The deep neural network model for learning to rank. This class implements a deep neural network (DNN) based ranking model. It's essientially a multi-layer perceptron network. | DNN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DNN:
"""The deep neural network model for learning to rank. This class implements a deep neural network (DNN) based ranking model. It's essientially a multi-layer perceptron network."""
def __init__(self, hparams_str):
"""Create the network. Args: hparams_str: (String) The hyper-para... | stack_v2_sparse_classes_75kplus_train_007072 | 4,249 | permissive | [
{
"docstring": "Create the network. Args: hparams_str: (String) The hyper-parameters used to build the network.",
"name": "__init__",
"signature": "def __init__(self, hparams_str)"
},
{
"docstring": "Create the DNN model Args: input_list: (list<tf.tensor>) A list of tensors containing the featur... | 2 | stack_v2_sparse_classes_30k_train_049757 | Implement the Python class `DNN` described below.
Class description:
The deep neural network model for learning to rank. This class implements a deep neural network (DNN) based ranking model. It's essientially a multi-layer perceptron network.
Method signatures and docstrings:
- def __init__(self, hparams_str): Creat... | Implement the Python class `DNN` described below.
Class description:
The deep neural network model for learning to rank. This class implements a deep neural network (DNN) based ranking model. It's essientially a multi-layer perceptron network.
Method signatures and docstrings:
- def __init__(self, hparams_str): Creat... | 89ffcaeb1049627d90518c2045dad7a996dfe2aa | <|skeleton|>
class DNN:
"""The deep neural network model for learning to rank. This class implements a deep neural network (DNN) based ranking model. It's essientially a multi-layer perceptron network."""
def __init__(self, hparams_str):
"""Create the network. Args: hparams_str: (String) The hyper-para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DNN:
"""The deep neural network model for learning to rank. This class implements a deep neural network (DNN) based ranking model. It's essientially a multi-layer perceptron network."""
def __init__(self, hparams_str):
"""Create the network. Args: hparams_str: (String) The hyper-parameters used t... | the_stack_v2_python_sparse | ultra/ranking_model/DNN.py | ULTR-Community/ULTRA | train | 281 |
b5704333b3b6fce945e8c7fe3cbdb603b2cf9b8c | [
"self.X = X\nself.y = y\nself.predictor = predictor",
"reg0 = copy.deepcopy(self.predictor)\nreg0.fit(self.X, costs_0)\nreg1 = copy.deepcopy(self.predictor)\nreg1.fit(self.X, costs_1)\nfunc = RegOracle(reg0, reg1)\nreturn func",
"new_predictions = np.multiply(1.0 / iteration, q.predict(self.X))\nds = np.multipl... | <|body_start_0|>
self.X = X
self.y = y
self.predictor = predictor
<|end_body_0|>
<|body_start_1|>
reg0 = copy.deepcopy(self.predictor)
reg0.fit(self.X, costs_0)
reg1 = copy.deepcopy(self.predictor)
reg1.fit(self.X, costs_1)
func = RegOracle(reg0, reg1)
... | Class implementing the Learner in the FairFictPlay algorithm for rich subgroup fairness in [KRNW18]. | Learner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Learner:
"""Class implementing the Learner in the FairFictPlay algorithm for rich subgroup fairness in [KRNW18]."""
def __init__(self, X, y, predictor):
"""Constructor the class :param X: pandas dataframe of attributes :param y: tuple of predictions :param predictor: regressor with s... | stack_v2_sparse_classes_75kplus_train_007073 | 2,648 | permissive | [
{
"docstring": "Constructor the class :param X: pandas dataframe of attributes :param y: tuple of predictions :param predictor: regressor with sklearn api (e.g. fit(), predict() methods). ex: LinearRegression()",
"name": "__init__",
"signature": "def __init__(self, X, y, predictor)"
},
{
"docstr... | 3 | null | Implement the Python class `Learner` described below.
Class description:
Class implementing the Learner in the FairFictPlay algorithm for rich subgroup fairness in [KRNW18].
Method signatures and docstrings:
- def __init__(self, X, y, predictor): Constructor the class :param X: pandas dataframe of attributes :param y... | Implement the Python class `Learner` described below.
Class description:
Class implementing the Learner in the FairFictPlay algorithm for rich subgroup fairness in [KRNW18].
Method signatures and docstrings:
- def __init__(self, X, y, predictor): Constructor the class :param X: pandas dataframe of attributes :param y... | 6f9972e4a7dbca2402f29b86ea67889143dbeb3e | <|skeleton|>
class Learner:
"""Class implementing the Learner in the FairFictPlay algorithm for rich subgroup fairness in [KRNW18]."""
def __init__(self, X, y, predictor):
"""Constructor the class :param X: pandas dataframe of attributes :param y: tuple of predictions :param predictor: regressor with s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Learner:
"""Class implementing the Learner in the FairFictPlay algorithm for rich subgroup fairness in [KRNW18]."""
def __init__(self, X, y, predictor):
"""Constructor the class :param X: pandas dataframe of attributes :param y: tuple of predictions :param predictor: regressor with sklearn api (e... | the_stack_v2_python_sparse | aif360/algorithms/inprocessing/gerryfair/learner.py | Trusted-AI/AIF360 | train | 1,157 |
507f5598e4e11afc704f0ef8a8b8fab32626ab73 | [
"Output = [[1]]\nif numRows == 0:\n return []\nfor l in range(numRows - 1):\n row = Output[l][:]\n row.append(0)\n row.insert(0, 0)\n new_row = []\n for i in range(len(row) - 1):\n new_row.append(row[i] + row[i + 1])\n Output.append(new_row)\nreturn Output",
"res = []\nfor i in range(0... | <|body_start_0|>
Output = [[1]]
if numRows == 0:
return []
for l in range(numRows - 1):
row = Output[l][:]
row.append(0)
row.insert(0, 0)
new_row = []
for i in range(len(row) - 1):
new_row.append(row[i] + row... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generate(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_0|>
def generate2(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Output = [[1]]
if ... | stack_v2_sparse_classes_75kplus_train_007074 | 1,205 | no_license | [
{
"docstring": ":type numRows: int :rtype: List[List[int]]",
"name": "generate",
"signature": "def generate(self, numRows)"
},
{
"docstring": ":type numRows: int :rtype: List[List[int]]",
"name": "generate2",
"signature": "def generate2(self, numRows)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generate(self, numRows): :type numRows: int :rtype: List[List[int]]
- def generate2(self, numRows): :type numRows: int :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generate(self, numRows): :type numRows: int :rtype: List[List[int]]
- def generate2(self, numRows): :type numRows: int :rtype: List[List[int]]
<|skeleton|>
class Solution:
... | 4650eba11361e4286f5d2ee299cf5d2db460d2f3 | <|skeleton|>
class Solution:
def generate(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_0|>
def generate2(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generate(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
Output = [[1]]
if numRows == 0:
return []
for l in range(numRows - 1):
row = Output[l][:]
row.append(0)
row.insert(0, 0)
new_row =... | the_stack_v2_python_sparse | LeetCode-easy/Others/LC_PascalsTriangle.py | ponggung/testPython | train | 0 | |
9d98bef6556da0c0ef934ad3d7a2cc47a0cbbbf4 | [
"json_str = request.body.decode('utf-8')\nif not json_str:\n return api_response(-1, 'post参数为空', {})\nrequest_data_dict = json.loads(json_str)\nworkflow_data = {}\napp_name = request.META.get('HTTP_APPNAME')\nusername = request.META.get('HTTP_USERNAME')\nname = request_data_dict.get('name', '')\nis_hidden = requ... | <|body_start_0|>
json_str = request.body.decode('utf-8')
if not json_str:
return api_response(-1, 'post参数为空', {})
request_data_dict = json.loads(json_str)
workflow_data = {}
app_name = request.META.get('HTTP_APPNAME')
username = request.META.get('HTTP_USERNAME... | WorkflowStateDetailView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowStateDetailView:
def patch(self, request, *args, **kwargs):
"""编辑状态 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def delete(self, request, *args, **kwargs):
"""删除状态 delete state :param request: :param args: :param kwargs: :return:"""
... | stack_v2_sparse_classes_75kplus_train_007075 | 48,278 | permissive | [
{
"docstring": "编辑状态 :param request: :param args: :param kwargs: :return:",
"name": "patch",
"signature": "def patch(self, request, *args, **kwargs)"
},
{
"docstring": "删除状态 delete state :param request: :param args: :param kwargs: :return:",
"name": "delete",
"signature": "def delete(sel... | 2 | null | Implement the Python class `WorkflowStateDetailView` described below.
Class description:
Implement the WorkflowStateDetailView class.
Method signatures and docstrings:
- def patch(self, request, *args, **kwargs): 编辑状态 :param request: :param args: :param kwargs: :return:
- def delete(self, request, *args, **kwargs): 删... | Implement the Python class `WorkflowStateDetailView` described below.
Class description:
Implement the WorkflowStateDetailView class.
Method signatures and docstrings:
- def patch(self, request, *args, **kwargs): 编辑状态 :param request: :param args: :param kwargs: :return:
- def delete(self, request, *args, **kwargs): 删... | b0e236b314286c5f6cc6959622c9c8505e776443 | <|skeleton|>
class WorkflowStateDetailView:
def patch(self, request, *args, **kwargs):
"""编辑状态 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def delete(self, request, *args, **kwargs):
"""删除状态 delete state :param request: :param args: :param kwargs: :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkflowStateDetailView:
def patch(self, request, *args, **kwargs):
"""编辑状态 :param request: :param args: :param kwargs: :return:"""
json_str = request.body.decode('utf-8')
if not json_str:
return api_response(-1, 'post参数为空', {})
request_data_dict = json.loads(json_s... | the_stack_v2_python_sparse | apps/workflow/views.py | blackholll/loonflow | train | 1,864 | |
aa97a846ddb2d59e07ed7fcd8bff805b59b50010 | [
"menu_item.MenuItem.__init__(self, main_menu, frame)\nself.create_menu_item_button('New Challenge')\nself.menu_item_button['command'] = self.get_new_challenge_window",
"self.gui.active_window.hide()\nself.associated_window = start_challenge_window.StartChallengeWindow(self.gui)\nself.gui.active_window = self.asso... | <|body_start_0|>
menu_item.MenuItem.__init__(self, main_menu, frame)
self.create_menu_item_button('New Challenge')
self.menu_item_button['command'] = self.get_new_challenge_window
<|end_body_0|>
<|body_start_1|>
self.gui.active_window.hide()
self.associated_window = start_challe... | This class is used to create a button that will bring the user to the new challenge menu. | NewChallengeMenuItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewChallengeMenuItem:
"""This class is used to create a button that will bring the user to the new challenge menu."""
def __init__(self, main_menu, frame):
"""Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's... | stack_v2_sparse_classes_75kplus_train_007076 | 1,081 | no_license | [
{
"docstring": "Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's active window",
"name": "__init__",
"signature": "def __init__(self, main_menu, frame)"
},
{
"docstring": "This function will hide everything on the activ... | 2 | stack_v2_sparse_classes_30k_train_005630 | Implement the Python class `NewChallengeMenuItem` described below.
Class description:
This class is used to create a button that will bring the user to the new challenge menu.
Method signatures and docstrings:
- def __init__(self, main_menu, frame): Args: main_menu ([]): this class must know about the main menu becau... | Implement the Python class `NewChallengeMenuItem` described below.
Class description:
This class is used to create a button that will bring the user to the new challenge menu.
Method signatures and docstrings:
- def __init__(self, main_menu, frame): Args: main_menu ([]): this class must know about the main menu becau... | e26d9450b98fa0f372bcdf6eaf251a2c9dcba44e | <|skeleton|>
class NewChallengeMenuItem:
"""This class is used to create a button that will bring the user to the new challenge menu."""
def __init__(self, main_menu, frame):
"""Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NewChallengeMenuItem:
"""This class is used to create a button that will bring the user to the new challenge menu."""
def __init__(self, main_menu, frame):
"""Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's active windo... | the_stack_v2_python_sparse | user_interface/menu_items/new_challenge_menu_item.py | pucheng-tan/WordFlow | train | 0 |
b5666fbb3af62fe0f4f38e3403d46b938c0c423e | [
"super().__init__(problem)\nself.best_path = None\nself.bound = bound",
"self.frontier = [Path(self.problem.start_node())]\nself.num_expanded = 0\nwhile self.frontier:\n path = self.frontier.pop()\n if path.cost + self.problem.heuristic(path.end()) < self.bound:\n self.display(3, 'Expanding:', path, ... | <|body_start_0|>
super().__init__(problem)
self.best_path = None
self.bound = bound
<|end_body_0|>
<|body_start_1|>
self.frontier = [Path(self.problem.start_node())]
self.num_expanded = 0
while self.frontier:
path = self.frontier.pop()
if path.cos... | returns a branch and bound searcher for a problem. An optimal path with cost less than bound can be found by calling search() | DF_branch_and_bound | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DF_branch_and_bound:
"""returns a branch and bound searcher for a problem. An optimal path with cost less than bound can be found by calling search()"""
def __init__(self, problem, bound=float('inf')):
"""creates a searcher than can be used with search() to find an optimal path. boun... | stack_v2_sparse_classes_75kplus_train_007077 | 2,841 | no_license | [
{
"docstring": "creates a searcher than can be used with search() to find an optimal path. bound gives the initial bound. By default this is infinite - meaning there is no initial pruning due to depth bound",
"name": "__init__",
"signature": "def __init__(self, problem, bound=float('inf'))"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_052537 | Implement the Python class `DF_branch_and_bound` described below.
Class description:
returns a branch and bound searcher for a problem. An optimal path with cost less than bound can be found by calling search()
Method signatures and docstrings:
- def __init__(self, problem, bound=float('inf')): creates a searcher tha... | Implement the Python class `DF_branch_and_bound` described below.
Class description:
returns a branch and bound searcher for a problem. An optimal path with cost less than bound can be found by calling search()
Method signatures and docstrings:
- def __init__(self, problem, bound=float('inf')): creates a searcher tha... | 479d6120b75ac0ff602f032474cad440cadd9f31 | <|skeleton|>
class DF_branch_and_bound:
"""returns a branch and bound searcher for a problem. An optimal path with cost less than bound can be found by calling search()"""
def __init__(self, problem, bound=float('inf')):
"""creates a searcher than can be used with search() to find an optimal path. boun... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DF_branch_and_bound:
"""returns a branch and bound searcher for a problem. An optimal path with cost less than bound can be found by calling search()"""
def __init__(self, problem, bound=float('inf')):
"""creates a searcher than can be used with search() to find an optimal path. bound gives the i... | the_stack_v2_python_sparse | ass1/aipython/searchBranchAndBound.py | fckphil/COMP9814 | train | 5 |
fb33404d8a10db0c348a29a18afbc58737943e00 | [
"LayoutItem.__init__(self, dom, parent_element, polygon_object, mxd, arc_doc)\nself.dom = dom\nself.parent_element = parent_element\nself.polygon_object = polygon_object\nself.mxd = mxd\nself.arc_doc = arc_doc",
"arcpy_item = LayoutItem.get_arcpy_layout_element(self, self.polygon_object)\nPolygonElement.set_size_... | <|body_start_0|>
LayoutItem.__init__(self, dom, parent_element, polygon_object, mxd, arc_doc)
self.dom = dom
self.parent_element = parent_element
self.polygon_object = polygon_object
self.mxd = mxd
self.arc_doc = arc_doc
<|end_body_0|>
<|body_start_1|>
arcpy_item... | PolygonElement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolygonElement:
def __init__(self, dom, parent_element, polygon_object, mxd, arc_doc):
"""This function creates a Polygon-Item for the layout :param dom: the Document Object Model :param parent_element: the main layout element, where to put the layout-items :param polygon_object: the pol... | stack_v2_sparse_classes_75kplus_train_007078 | 2,436 | permissive | [
{
"docstring": "This function creates a Polygon-Item for the layout :param dom: the Document Object Model :param parent_element: the main layout element, where to put the layout-items :param polygon_object: the polygon_object as ArcObject :param mxd: the arcpy mxd-document :param arc_doc: the ArcObject IMxDocum... | 2 | stack_v2_sparse_classes_30k_train_048244 | Implement the Python class `PolygonElement` described below.
Class description:
Implement the PolygonElement class.
Method signatures and docstrings:
- def __init__(self, dom, parent_element, polygon_object, mxd, arc_doc): This function creates a Polygon-Item for the layout :param dom: the Document Object Model :para... | Implement the Python class `PolygonElement` described below.
Class description:
Implement the PolygonElement class.
Method signatures and docstrings:
- def __init__(self, dom, parent_element, polygon_object, mxd, arc_doc): This function creates a Polygon-Item for the layout :param dom: the Document Object Model :para... | cd0aa5f533194c85cf6e098fadc079ea61b63fce | <|skeleton|>
class PolygonElement:
def __init__(self, dom, parent_element, polygon_object, mxd, arc_doc):
"""This function creates a Polygon-Item for the layout :param dom: the Document Object Model :param parent_element: the main layout element, where to put the layout-items :param polygon_object: the pol... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PolygonElement:
def __init__(self, dom, parent_element, polygon_object, mxd, arc_doc):
"""This function creates a Polygon-Item for the layout :param dom: the Document Object Model :param parent_element: the main layout element, where to put the layout-items :param polygon_object: the polygon_object as... | the_stack_v2_python_sparse | layout/polygonElement.py | avaldeon/mapqonverter | train | 0 | |
6ff4563f378351837c34620dc8d0add23d232edc | [
"self.neg_pos_ratio = neg_pos_ratio\nself.n_neg_min = n_neg_min\nself.alpha = alpha",
"absolute_loss = tf.abs(y_true - y_pred)\nsquare_loss = 0.5 * (y_true - y_pred) ** 2\nl1_loss = tf.where(tf.less(absolute_loss, 1.0), square_loss, absolute_loss - 0.5)\nreturn tf.reduce_sum(l1_loss, axis=-1)",
"y_pred = tf.max... | <|body_start_0|>
self.neg_pos_ratio = neg_pos_ratio
self.n_neg_min = n_neg_min
self.alpha = alpha
<|end_body_0|>
<|body_start_1|>
absolute_loss = tf.abs(y_true - y_pred)
square_loss = 0.5 * (y_true - y_pred) ** 2
l1_loss = tf.where(tf.less(absolute_loss, 1.0), square_los... | The SSD loss, see https://arxiv.org/abs/1512.02325. | FocalLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FocalLoss:
"""The SSD loss, see https://arxiv.org/abs/1512.02325."""
def __init__(self, neg_pos_ratio=3, n_neg_min=0, alpha=1.0):
"""Arguments: neg_pos_ratio (int, optional): The maximum ratio of negative (i.e. background) to positive ground truth boxes to include in the loss computa... | stack_v2_sparse_classes_75kplus_train_007079 | 28,099 | permissive | [
{
"docstring": "Arguments: neg_pos_ratio (int, optional): The maximum ratio of negative (i.e. background) to positive ground truth boxes to include in the loss computation. There are no actual background ground truth boxes of course, but `y_true` contains anchor boxes labeled with the background class. Since th... | 4 | stack_v2_sparse_classes_30k_train_048728 | Implement the Python class `FocalLoss` described below.
Class description:
The SSD loss, see https://arxiv.org/abs/1512.02325.
Method signatures and docstrings:
- def __init__(self, neg_pos_ratio=3, n_neg_min=0, alpha=1.0): Arguments: neg_pos_ratio (int, optional): The maximum ratio of negative (i.e. background) to p... | Implement the Python class `FocalLoss` described below.
Class description:
The SSD loss, see https://arxiv.org/abs/1512.02325.
Method signatures and docstrings:
- def __init__(self, neg_pos_ratio=3, n_neg_min=0, alpha=1.0): Arguments: neg_pos_ratio (int, optional): The maximum ratio of negative (i.e. background) to p... | 69a5f2ed9990f71e7e19054c4e6e1206396f24e3 | <|skeleton|>
class FocalLoss:
"""The SSD loss, see https://arxiv.org/abs/1512.02325."""
def __init__(self, neg_pos_ratio=3, n_neg_min=0, alpha=1.0):
"""Arguments: neg_pos_ratio (int, optional): The maximum ratio of negative (i.e. background) to positive ground truth boxes to include in the loss computa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FocalLoss:
"""The SSD loss, see https://arxiv.org/abs/1512.02325."""
def __init__(self, neg_pos_ratio=3, n_neg_min=0, alpha=1.0):
"""Arguments: neg_pos_ratio (int, optional): The maximum ratio of negative (i.e. background) to positive ground truth boxes to include in the loss computation. There a... | the_stack_v2_python_sparse | solartf/core/loss.py | solarfresh/solartf | train | 0 |
09d2c33f15fa5fcfb3e9381e3a0d4452161e99ac | [
"mask = 1\ncount = 0\nfor i in range(0, 32):\n if n & mask != 0:\n count += 1\n mask <<= 1\nreturn count",
"count = 0\nwhile n != 0:\n count += 1\n n &= n - 1\nreturn count"
] | <|body_start_0|>
mask = 1
count = 0
for i in range(0, 32):
if n & mask != 0:
count += 1
mask <<= 1
return count
<|end_body_0|>
<|body_start_1|>
count = 0
while n != 0:
count += 1
n &= n - 1
return co... | CountBits | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CountBits:
def calculate_hamming_weight(n):
""":type n: int :rtype: int"""
<|body_0|>
def calculate_hamming_weight_optimized(n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
mask = 1
count = 0
for i in ... | stack_v2_sparse_classes_75kplus_train_007080 | 550 | permissive | [
{
"docstring": ":type n: int :rtype: int",
"name": "calculate_hamming_weight",
"signature": "def calculate_hamming_weight(n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "calculate_hamming_weight_optimized",
"signature": "def calculate_hamming_weight_optimized(n)"
}
] | 2 | null | Implement the Python class `CountBits` described below.
Class description:
Implement the CountBits class.
Method signatures and docstrings:
- def calculate_hamming_weight(n): :type n: int :rtype: int
- def calculate_hamming_weight_optimized(n): :type n: int :rtype: int | Implement the Python class `CountBits` described below.
Class description:
Implement the CountBits class.
Method signatures and docstrings:
- def calculate_hamming_weight(n): :type n: int :rtype: int
- def calculate_hamming_weight_optimized(n): :type n: int :rtype: int
<|skeleton|>
class CountBits:
def calculat... | 77838c37e3fdae0f2ec628aa7ddc59f4a5949bbe | <|skeleton|>
class CountBits:
def calculate_hamming_weight(n):
""":type n: int :rtype: int"""
<|body_0|>
def calculate_hamming_weight_optimized(n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CountBits:
def calculate_hamming_weight(n):
""":type n: int :rtype: int"""
mask = 1
count = 0
for i in range(0, 32):
if n & mask != 0:
count += 1
mask <<= 1
return count
def calculate_hamming_weight_optimized(n):
""":... | the_stack_v2_python_sparse | Python/dev/bitwise/count_bits.py | faisaldialpad/hellouniverse | train | 0 | |
22c6982b5b34d904f8aba29ef2f0a39e8fb64f14 | [
"self.k = k\nself.heap = nums\nheapify(self.heap)\nwhile len(self.heap) > k:\n heappop(self.heap)",
"if len(self.heap) < self.k:\n heappush(self.heap, val)\nelif val > self.heap[0]:\n heapreplace(self.heap, val)\nreturn self.heap[0]"
] | <|body_start_0|>
self.k = k
self.heap = nums
heapify(self.heap)
while len(self.heap) > k:
heappop(self.heap)
<|end_body_0|>
<|body_start_1|>
if len(self.heap) < self.k:
heappush(self.heap, val)
elif val > self.heap[0]:
heapreplace(self... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.heap = nums
heapify(self.h... | stack_v2_sparse_classes_75kplus_train_007081 | 967 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002742 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.heap = nums
heapify(self.heap)
while len(self.heap) > k:
heappop(self.heap)
def add(self, val):
""":type val: int :rtype: int"""
if len(sel... | the_stack_v2_python_sparse | LC703.py | Qiao-Liang/LeetCode | train | 0 | |
ea77c4372e2487595aef7b6f32eac23de6f6fe8c | [
"rDao = RentalDAO()\ntry:\n stripeID = rDao.getStripeToken(rid)\n rDao.wasDispatched(rid)\n if stripeID != 'CASH':\n stripe.Subscription.delete(stripeID)\n scheduler.remove_job('debt' + str(rid))\nexcept Exception as e:\n traceback.print_exc()\n scheduler.add_job(func=self.wasDispatched, ar... | <|body_start_0|>
rDao = RentalDAO()
try:
stripeID = rDao.getStripeToken(rid)
rDao.wasDispatched(rid)
if stripeID != 'CASH':
stripe.Subscription.delete(stripeID)
scheduler.remove_job('debt' + str(rid))
except Exception as e:
... | SchedulerHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedulerHandler:
def wasDispatched(self, rid):
"""Method that verifies if the bicycle was dispatched after a certain time period :param rid: Rental ID :return: Nothing"""
<|body_0|>
def hasDebt(self, rid):
"""Method that verifies if the bicycle was dispatched after ... | stack_v2_sparse_classes_75kplus_train_007082 | 1,505 | no_license | [
{
"docstring": "Method that verifies if the bicycle was dispatched after a certain time period :param rid: Rental ID :return: Nothing",
"name": "wasDispatched",
"signature": "def wasDispatched(self, rid)"
},
{
"docstring": "Method that verifies if the bicycle was dispatched after a certain time ... | 2 | stack_v2_sparse_classes_30k_train_038277 | Implement the Python class `SchedulerHandler` described below.
Class description:
Implement the SchedulerHandler class.
Method signatures and docstrings:
- def wasDispatched(self, rid): Method that verifies if the bicycle was dispatched after a certain time period :param rid: Rental ID :return: Nothing
- def hasDebt(... | Implement the Python class `SchedulerHandler` described below.
Class description:
Implement the SchedulerHandler class.
Method signatures and docstrings:
- def wasDispatched(self, rid): Method that verifies if the bicycle was dispatched after a certain time period :param rid: Rental ID :return: Nothing
- def hasDebt(... | 9ec1028dbd477a6d0e6dbb5d225a208c288c42f1 | <|skeleton|>
class SchedulerHandler:
def wasDispatched(self, rid):
"""Method that verifies if the bicycle was dispatched after a certain time period :param rid: Rental ID :return: Nothing"""
<|body_0|>
def hasDebt(self, rid):
"""Method that verifies if the bicycle was dispatched after ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SchedulerHandler:
def wasDispatched(self, rid):
"""Method that verifies if the bicycle was dispatched after a certain time period :param rid: Rental ID :return: Nothing"""
rDao = RentalDAO()
try:
stripeID = rDao.getStripeToken(rid)
rDao.wasDispatched(rid)
... | the_stack_v2_python_sparse | handler/applicationScheduler.py | elnoisnorat/Bici-Coop-Rental | train | 0 | |
2c1ce9b33fc0b7ac96c0e683692982322e64f2ae | [
"q = quantity.DipoleMoment(1.0, 'C*m')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 1.0, 6)\nself.assertEqual(q.units, 'C*m')",
"q = quantity.DipoleMoment(1.0, 'De')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si * constants.c * 1e+21, 1.0, 6)\nself.ass... | <|body_start_0|>
q = quantity.DipoleMoment(1.0, 'C*m')
self.assertAlmostEqual(q.value, 1.0, 6)
self.assertAlmostEqual(q.value_si, 1.0, 6)
self.assertEqual(q.units, 'C*m')
<|end_body_0|>
<|body_start_1|>
q = quantity.DipoleMoment(1.0, 'De')
self.assertAlmostEqual(q.value,... | Contains unit tests of the DipoleMoment unit type object. | TestDipoleMoment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDipoleMoment:
"""Contains unit tests of the DipoleMoment unit type object."""
def test_Ctimesm(self):
"""Test the creation of a dipole moment quantity with units of C*m."""
<|body_0|>
def test_D(self):
"""Test the creation of a dipole moment quantity with uni... | stack_v2_sparse_classes_75kplus_train_007083 | 33,010 | permissive | [
{
"docstring": "Test the creation of a dipole moment quantity with units of C*m.",
"name": "test_Ctimesm",
"signature": "def test_Ctimesm(self)"
},
{
"docstring": "Test the creation of a dipole moment quantity with units of J/mol.",
"name": "test_D",
"signature": "def test_D(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038785 | Implement the Python class `TestDipoleMoment` described below.
Class description:
Contains unit tests of the DipoleMoment unit type object.
Method signatures and docstrings:
- def test_Ctimesm(self): Test the creation of a dipole moment quantity with units of C*m.
- def test_D(self): Test the creation of a dipole mom... | Implement the Python class `TestDipoleMoment` described below.
Class description:
Contains unit tests of the DipoleMoment unit type object.
Method signatures and docstrings:
- def test_Ctimesm(self): Test the creation of a dipole moment quantity with units of C*m.
- def test_D(self): Test the creation of a dipole mom... | 0937b2e0a955dcf21b79674a4e89f43941c0dd85 | <|skeleton|>
class TestDipoleMoment:
"""Contains unit tests of the DipoleMoment unit type object."""
def test_Ctimesm(self):
"""Test the creation of a dipole moment quantity with units of C*m."""
<|body_0|>
def test_D(self):
"""Test the creation of a dipole moment quantity with uni... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDipoleMoment:
"""Contains unit tests of the DipoleMoment unit type object."""
def test_Ctimesm(self):
"""Test the creation of a dipole moment quantity with units of C*m."""
q = quantity.DipoleMoment(1.0, 'C*m')
self.assertAlmostEqual(q.value, 1.0, 6)
self.assertAlmostE... | the_stack_v2_python_sparse | rmgpy/quantityTest.py | vrlambert/RMG-Py | train | 1 |
afd86debba5ca56b71e393cc47d5956885f2d2c4 | [
"self.name = name.title()\nself.model = model.title()\nself.year = year",
"print('Name of car: ' + self.name)\nprint('Model of car: ' + self.model)\nprint('Manufactured year: ' + str(self.year))"
] | <|body_start_0|>
self.name = name.title()
self.model = model.title()
self.year = year
<|end_body_0|>
<|body_start_1|>
print('Name of car: ' + self.name)
print('Model of car: ' + self.model)
print('Manufactured year: ' + str(self.year))
<|end_body_1|>
| An attempt to model a car. | Car | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Car:
"""An attempt to model a car."""
def __init__(self, name, model, year):
"""To initialize the car attributes."""
<|body_0|>
def describe_car(self):
"""To display car information."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.name = na... | stack_v2_sparse_classes_75kplus_train_007084 | 2,347 | no_license | [
{
"docstring": "To initialize the car attributes.",
"name": "__init__",
"signature": "def __init__(self, name, model, year)"
},
{
"docstring": "To display car information.",
"name": "describe_car",
"signature": "def describe_car(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021177 | Implement the Python class `Car` described below.
Class description:
An attempt to model a car.
Method signatures and docstrings:
- def __init__(self, name, model, year): To initialize the car attributes.
- def describe_car(self): To display car information. | Implement the Python class `Car` described below.
Class description:
An attempt to model a car.
Method signatures and docstrings:
- def __init__(self, name, model, year): To initialize the car attributes.
- def describe_car(self): To display car information.
<|skeleton|>
class Car:
"""An attempt to model a car."... | 4a9a7cd14d91d8e9e52039006c0c7fe560d6eb5f | <|skeleton|>
class Car:
"""An attempt to model a car."""
def __init__(self, name, model, year):
"""To initialize the car attributes."""
<|body_0|>
def describe_car(self):
"""To display car information."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Car:
"""An attempt to model a car."""
def __init__(self, name, model, year):
"""To initialize the car attributes."""
self.name = name.title()
self.model = model.title()
self.year = year
def describe_car(self):
"""To display car information."""
print('N... | the_stack_v2_python_sparse | Chap_9 - Classes/9_9_battery_upgrade.py | huzaifabaloch/Python_Crash_Book_Exercises | train | 3 |
878b449a69805e34d28be822bc45eccfb2609c2f | [
"super().__init__(name=name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself.blackboard = self.attach_blackboard_client()\nself.blackboard.register_key(key='/foo/bar/wow', access=py_trees.common.Access.WRITE, remap_to=remap_to['/foo/bar/wow'])",
"self.logger.debug('%s.update()' % self.__class_... | <|body_start_0|>
super().__init__(name=name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self.blackboard = self.attach_blackboard_client()
self.blackboard.register_key(key='/foo/bar/wow', access=py_trees.common.Access.WRITE, remap_to=remap_to['/foo/bar/wow'])
<|end_body_... | Custom writer that submits a more complicated variable to the blackboard. | Remap | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Remap:
"""Custom writer that submits a more complicated variable to the blackboard."""
def __init__(self, name: str, remap_to: typing.Dict[str, str]):
"""Set up the blackboard and remap variables. Args: name: behaviour name remap_to: remappings (from variable name to variable name)""... | stack_v2_sparse_classes_75kplus_train_007085 | 4,268 | permissive | [
{
"docstring": "Set up the blackboard and remap variables. Args: name: behaviour name remap_to: remappings (from variable name to variable name)",
"name": "__init__",
"signature": "def __init__(self, name: str, remap_to: typing.Dict[str, str])"
},
{
"docstring": "Write a dictionary to the blackb... | 2 | stack_v2_sparse_classes_30k_train_010832 | Implement the Python class `Remap` described below.
Class description:
Custom writer that submits a more complicated variable to the blackboard.
Method signatures and docstrings:
- def __init__(self, name: str, remap_to: typing.Dict[str, str]): Set up the blackboard and remap variables. Args: name: behaviour name rem... | Implement the Python class `Remap` described below.
Class description:
Custom writer that submits a more complicated variable to the blackboard.
Method signatures and docstrings:
- def __init__(self, name: str, remap_to: typing.Dict[str, str]): Set up the blackboard and remap variables. Args: name: behaviour name rem... | 17fc0aeed83ec57b1494deac848324ff61e64232 | <|skeleton|>
class Remap:
"""Custom writer that submits a more complicated variable to the blackboard."""
def __init__(self, name: str, remap_to: typing.Dict[str, str]):
"""Set up the blackboard and remap variables. Args: name: behaviour name remap_to: remappings (from variable name to variable name)""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Remap:
"""Custom writer that submits a more complicated variable to the blackboard."""
def __init__(self, name: str, remap_to: typing.Dict[str, str]):
"""Set up the blackboard and remap variables. Args: name: behaviour name remap_to: remappings (from variable name to variable name)"""
sup... | the_stack_v2_python_sparse | py_trees/demos/blackboard_remappings.py | jstyrud/py_trees | train | 0 |
99ed3718b007c4a69255ee846055500825ef1978 | [
"def dfs(node):\n if not node:\n return 0\n ret = 0\n if low <= node.val <= high:\n ret += node.val\n if node.val < low:\n ret += dfs(node.right)\n elif node.val > high:\n ret += dfs(node.left)\n else:\n ret += dfs(node.left) + dfs(node.right)\n return ret\nre... | <|body_start_0|>
def dfs(node):
if not node:
return 0
ret = 0
if low <= node.val <= high:
ret += node.val
if node.val < low:
ret += dfs(node.right)
elif node.val > high:
ret += dfs(node.le... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
"""Dec 23, 2021 13:06"""
<|body_0|>
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
"""Dec 11, 2022 16:13"""
<|body_1|>
def rangeSumBST(se... | stack_v2_sparse_classes_75kplus_train_007086 | 2,887 | no_license | [
{
"docstring": "Dec 23, 2021 13:06",
"name": "rangeSumBST",
"signature": "def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int"
},
{
"docstring": "Dec 11, 2022 16:13",
"name": "rangeSumBST",
"signature": "def rangeSumBST(self, root: Optional[TreeNode], low: int, hi... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: Dec 23, 2021 13:06
- def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: Dec... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: Dec 23, 2021 13:06
- def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: Dec... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
"""Dec 23, 2021 13:06"""
<|body_0|>
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
"""Dec 11, 2022 16:13"""
<|body_1|>
def rangeSumBST(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
"""Dec 23, 2021 13:06"""
def dfs(node):
if not node:
return 0
ret = 0
if low <= node.val <= high:
ret += node.val
if node.val <... | the_stack_v2_python_sparse | leetcode/solved/975_Range_Sum_of_BST/solution.py | sungminoh/algorithms | train | 0 | |
8adca997da2b08fc2bc967d0664327512f41497e | [
"pages = [panel.PanelPage(sheet, self.map_state) for sheet in BASIC]\nself.panel = panel.Panel(self.map_state, pages)\nbackground_page = [panel.BackGroundPage(self.map_state)]\nself.background_panel = panel.Panel(self.map_state, background_page)",
"if self.map_state.layer != 'BG Colors':\n return self.panel\ne... | <|body_start_0|>
pages = [panel.PanelPage(sheet, self.map_state) for sheet in BASIC]
self.panel = panel.Panel(self.map_state, pages)
background_page = [panel.BackGroundPage(self.map_state)]
self.background_panel = panel.Panel(self.map_state, background_page)
<|end_body_0|>
<|body_start_... | Standard mode in the primary map editor. | Standard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Standard:
"""Standard mode in the primary map editor."""
def make_panels(self):
"""Create necessary panels and their pages."""
<|body_0|>
def active_panel(self):
"""Get the currently active panel (generally based on layer)."""
<|body_1|>
def set_add_... | stack_v2_sparse_classes_75kplus_train_007087 | 14,407 | no_license | [
{
"docstring": "Create necessary panels and their pages.",
"name": "make_panels",
"signature": "def make_panels(self)"
},
{
"docstring": "Get the currently active panel (generally based on layer).",
"name": "active_panel",
"signature": "def active_panel(self)"
},
{
"docstring": "... | 5 | null | Implement the Python class `Standard` described below.
Class description:
Standard mode in the primary map editor.
Method signatures and docstrings:
- def make_panels(self): Create necessary panels and their pages.
- def active_panel(self): Get the currently active panel (generally based on layer).
- def set_add_del(... | Implement the Python class `Standard` described below.
Class description:
Standard mode in the primary map editor.
Method signatures and docstrings:
- def make_panels(self): Create necessary panels and their pages.
- def active_panel(self): Get the currently active panel (generally based on layer).
- def set_add_del(... | cee7e4b5dc28c57a6c912852827652b5f51005ae | <|skeleton|>
class Standard:
"""Standard mode in the primary map editor."""
def make_panels(self):
"""Create necessary panels and their pages."""
<|body_0|>
def active_panel(self):
"""Get the currently active panel (generally based on layer)."""
<|body_1|>
def set_add_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Standard:
"""Standard mode in the primary map editor."""
def make_panels(self):
"""Create necessary panels and their pages."""
pages = [panel.PanelPage(sheet, self.map_state) for sheet in BASIC]
self.panel = panel.Panel(self.map_state, pages)
background_page = [panel.BackG... | the_stack_v2_python_sparse | IE_games_3/cabbages-and-kings-master/data/map_components/modes.py | IndexErrorCoders/PygamesCompilation | train | 2 |
8f96f4cf517af6c4da30d7cd0a5f5f03c47ab13f | [
"task_callback(status=TaskStatus.IN_PROGRESS)\nresult_code, message = self.do()\nlogger.info('Restart command invoked on: %s: Result: %s, %s', self.sdp_subarray_adapter.dev_name, result_code, message)\ntask_callback(status=TaskStatus.COMPLETED, result=result_code, exception=message)",
"result_code, message = self... | <|body_start_0|>
task_callback(status=TaskStatus.IN_PROGRESS)
result_code, message = self.do()
logger.info('Restart command invoked on: %s: Result: %s, %s', self.sdp_subarray_adapter.dev_name, result_code, message)
task_callback(status=TaskStatus.COMPLETED, result=result_code, exception=... | A class for Sdp Subarray Restart command. Restarts the Sdp Subarray device. | Restart | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Restart:
"""A class for Sdp Subarray Restart command. Restarts the Sdp Subarray device."""
def restart(self, logger: Logger, task_callback: Callable, task_abort_event: Optional[threading.Event]=None) -> None:
"""This is a long-running method for a Restart command, it executes do hook... | stack_v2_sparse_classes_75kplus_train_007088 | 2,930 | permissive | [
{
"docstring": "This is a long-running method for a Restart command, it executes do hook :param logger: logger :type logger: logging.Logger :param task_callback: Update task state, defaults to None :type task_callback: Callable, optional :param task_abort_event: Check for abort, defaults to None :type task_abor... | 2 | null | Implement the Python class `Restart` described below.
Class description:
A class for Sdp Subarray Restart command. Restarts the Sdp Subarray device.
Method signatures and docstrings:
- def restart(self, logger: Logger, task_callback: Callable, task_abort_event: Optional[threading.Event]=None) -> None: This is a long-... | Implement the Python class `Restart` described below.
Class description:
A class for Sdp Subarray Restart command. Restarts the Sdp Subarray device.
Method signatures and docstrings:
- def restart(self, logger: Logger, task_callback: Callable, task_abort_event: Optional[threading.Event]=None) -> None: This is a long-... | 7ee65a9c8dada9b28893144b372a398bd0646195 | <|skeleton|>
class Restart:
"""A class for Sdp Subarray Restart command. Restarts the Sdp Subarray device."""
def restart(self, logger: Logger, task_callback: Callable, task_abort_event: Optional[threading.Event]=None) -> None:
"""This is a long-running method for a Restart command, it executes do hook... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Restart:
"""A class for Sdp Subarray Restart command. Restarts the Sdp Subarray device."""
def restart(self, logger: Logger, task_callback: Callable, task_abort_event: Optional[threading.Event]=None) -> None:
"""This is a long-running method for a Restart command, it executes do hook :param logge... | the_stack_v2_python_sparse | src/ska_tmc_sdpsubarrayleafnode/commands/restart_command.py | ska-telescope/tmc-prototype | train | 4 |
8a0df03cb743d8d5818818c61fc699fa86c1505e | [
"self.d_model = d_model\nself.d_k = d_k\nself.d_v = d_v\nself.sequence_length = sequence_length\nself.h = h\nself.num_layer = num_layer\nself.batch_size = batch_size\nself.decoder_sent_length = decoder_sent_length",
"with tf.variable_scope('sub_layer_postion_wise_feed_forward' + str(layer_index)):\n postion_wi... | <|body_start_0|>
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.sequence_length = sequence_length
self.h = h
self.num_layer = num_layer
self.batch_size = batch_size
self.decoder_sent_length = decoder_sent_length
<|end_body_0|>
<|body_start_1|>
... | base class has some common fields and functions. | BaseClass | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseClass:
"""base class has some common fields and functions."""
def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None):
""":param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embed... | stack_v2_sparse_classes_75kplus_train_007089 | 4,426 | permissive | [
{
"docstring": ":param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embedded_words: shape:[batch_size,sequence_length,embed_size]",
"name": "__init__",
"signature": "def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder... | 4 | stack_v2_sparse_classes_30k_train_004471 | Implement the Python class `BaseClass` described below.
Class description:
base class has some common fields and functions.
Method signatures and docstrings:
- def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None): :param d_model: :param d_k: :param d_v: :param s... | Implement the Python class `BaseClass` described below.
Class description:
base class has some common fields and functions.
Method signatures and docstrings:
- def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None): :param d_model: :param d_k: :param d_v: :param s... | 480c909e0835a455606e829310ff949c9dd23549 | <|skeleton|>
class BaseClass:
"""base class has some common fields and functions."""
def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None):
""":param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embed... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseClass:
"""base class has some common fields and functions."""
def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None):
""":param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embedded_words: sh... | the_stack_v2_python_sparse | bert_language_understanding-master/bert_language_understanding-master/model/base_model.py | yyht/BERT | train | 37 |
6a05d3f6bfbb4dca10c7da10d0aed6d4cc334656 | [
"hero_name = {1: '曹操', 2: '张飞', 3: '刘备'}\nhero = hero_name[hero_number]\nreturn hero",
"fist = {1: '石头', 2: '剪刀', 3: '布'}\nweapon = fist[fist_number]\nreturn weapon",
"import random\nfist = {1: '石头', 2: '剪刀', 3: '布'}\nrandom_01 = random.randint(1, 3)\nquan = fist[random_01]\nreturn quan",
"victory = 0\nlose =... | <|body_start_0|>
hero_name = {1: '曹操', 2: '张飞', 3: '刘备'}
hero = hero_name[hero_number]
return hero
<|end_body_0|>
<|body_start_1|>
fist = {1: '石头', 2: '剪刀', 3: '布'}
weapon = fist[fist_number]
return weapon
<|end_body_1|>
<|body_start_2|>
import random
fi... | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
def hero_select(self, hero_number):
"""定义一个英雄 ,写一个字典,获取用户输入数字,来挑选英雄 记录用户选择的英雄,给下面函数使用"""
<|body_0|>
def hero_fist(self, fist_number):
"""拳, 定义拳,获取用户输入 写一个字典,获取用户输入数字,来挑选拳"""
<|body_1|>
def hrobot_fist(self):
"""记录电脑出拳 import random 随机数:rand... | stack_v2_sparse_classes_75kplus_train_007090 | 8,115 | no_license | [
{
"docstring": "定义一个英雄 ,写一个字典,获取用户输入数字,来挑选英雄 记录用户选择的英雄,给下面函数使用",
"name": "hero_select",
"signature": "def hero_select(self, hero_number)"
},
{
"docstring": "拳, 定义拳,获取用户输入 写一个字典,获取用户输入数字,来挑选拳",
"name": "hero_fist",
"signature": "def hero_fist(self, fist_number)"
},
{
"docstring": ... | 4 | stack_v2_sparse_classes_30k_train_017808 | Implement the Python class `Game` described below.
Class description:
Implement the Game class.
Method signatures and docstrings:
- def hero_select(self, hero_number): 定义一个英雄 ,写一个字典,获取用户输入数字,来挑选英雄 记录用户选择的英雄,给下面函数使用
- def hero_fist(self, fist_number): 拳, 定义拳,获取用户输入 写一个字典,获取用户输入数字,来挑选拳
- def hrobot_fist(self): 记录电脑出拳 i... | Implement the Python class `Game` described below.
Class description:
Implement the Game class.
Method signatures and docstrings:
- def hero_select(self, hero_number): 定义一个英雄 ,写一个字典,获取用户输入数字,来挑选英雄 记录用户选择的英雄,给下面函数使用
- def hero_fist(self, fist_number): 拳, 定义拳,获取用户输入 写一个字典,获取用户输入数字,来挑选拳
- def hrobot_fist(self): 记录电脑出拳 i... | cfadd3132c2c7c518c784589e0dab6510a662a6c | <|skeleton|>
class Game:
def hero_select(self, hero_number):
"""定义一个英雄 ,写一个字典,获取用户输入数字,来挑选英雄 记录用户选择的英雄,给下面函数使用"""
<|body_0|>
def hero_fist(self, fist_number):
"""拳, 定义拳,获取用户输入 写一个字典,获取用户输入数字,来挑选拳"""
<|body_1|>
def hrobot_fist(self):
"""记录电脑出拳 import random 随机数:rand... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Game:
def hero_select(self, hero_number):
"""定义一个英雄 ,写一个字典,获取用户输入数字,来挑选英雄 记录用户选择的英雄,给下面函数使用"""
hero_name = {1: '曹操', 2: '张飞', 3: '刘备'}
hero = hero_name[hero_number]
return hero
def hero_fist(self, fist_number):
"""拳, 定义拳,获取用户输入 写一个字典,获取用户输入数字,来挑选拳"""
fist =... | the_stack_v2_python_sparse | lemon/python22/lemon_12_190911_类和对象2/lemon_190911_作业.py | songyongzhuang/PythonCode_office | train | 0 | |
30ba9c21f32cea9d098dc8596f28ec061def3b8a | [
"step1()\nr = xptest_case_register_Delete\nif '恭喜您,账号已成功注册' in r.text:\n print('注册成功')\nassert '恭喜您,账号已成功注册' in r.text",
"step1_1()\nr = xptest_case_register\nif '该用户名已被注册,请更换用户名' in r.text:\n print('账户已注册,请输入新的账号')\nassert '该用户名已被注册,请更换用户名' in r.text",
"step2_1()\nstep2_2()\nr = xptest_case_register\nif ... | <|body_start_0|>
step1()
r = xptest_case_register_Delete
if '恭喜您,账号已成功注册' in r.text:
print('注册成功')
assert '恭喜您,账号已成功注册' in r.text
<|end_body_0|>
<|body_start_1|>
step1_1()
r = xptest_case_register
if '该用户名已被注册,请更换用户名' in r.text:
print('账户已... | Test_regist | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_regist:
def test_register1(self, xptest_case_register_Delete):
"""用例详情的描述: 接口地址:http://web.juhe.cn:8080/constellation/getAll 请求方式:post 请求类型:Content-Type: application/json 头信息: X-Requested-With: XMLHttpRequest Content-Type: application/json 参数:{"account":"test1","email":"1@qq.com","p... | stack_v2_sparse_classes_75kplus_train_007091 | 8,089 | no_license | [
{
"docstring": "用例详情的描述: 接口地址:http://web.juhe.cn:8080/constellation/getAll 请求方式:post 请求类型:Content-Type: application/json 头信息: X-Requested-With: XMLHttpRequest Content-Type: application/json 参数:{\"account\":\"test1\",\"email\":\"1@qq.com\",\"password\":\"123456\",\"repassword\":\"123456\"} 大概步骤: 1.删除账号test1 2.注册... | 3 | stack_v2_sparse_classes_30k_train_037428 | Implement the Python class `Test_regist` described below.
Class description:
Implement the Test_regist class.
Method signatures and docstrings:
- def test_register1(self, xptest_case_register_Delete): 用例详情的描述: 接口地址:http://web.juhe.cn:8080/constellation/getAll 请求方式:post 请求类型:Content-Type: application/json 头信息: X-Reque... | Implement the Python class `Test_regist` described below.
Class description:
Implement the Test_regist class.
Method signatures and docstrings:
- def test_register1(self, xptest_case_register_Delete): 用例详情的描述: 接口地址:http://web.juhe.cn:8080/constellation/getAll 请求方式:post 请求类型:Content-Type: application/json 头信息: X-Reque... | c3ca50f34dedb3d400fd303957198c4ca006a821 | <|skeleton|>
class Test_regist:
def test_register1(self, xptest_case_register_Delete):
"""用例详情的描述: 接口地址:http://web.juhe.cn:8080/constellation/getAll 请求方式:post 请求类型:Content-Type: application/json 头信息: X-Requested-With: XMLHttpRequest Content-Type: application/json 参数:{"account":"test1","email":"1@qq.com","p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_regist:
def test_register1(self, xptest_case_register_Delete):
"""用例详情的描述: 接口地址:http://web.juhe.cn:8080/constellation/getAll 请求方式:post 请求类型:Content-Type: application/json 头信息: X-Requested-With: XMLHttpRequest Content-Type: application/json 参数:{"account":"test1","email":"1@qq.com","password":"1234... | the_stack_v2_python_sparse | project_hrun/test_login_registers/test_regist_login.py | haloyazhou/halo_1 | train | 0 | |
7567f9d2d28214548d857e5cc3dc4b25cffb5f72 | [
"dic = {}\nfor i, c in enumerate(s):\n if c in dic:\n dic[c][0] = False\n else:\n dic[c] = [True, i]\nr = -1\nfor i in dic:\n t = dic[i]\n if t[0]:\n if r == -1 or t[1] < r:\n r = t[1]\nreturn r",
"l = len(s)\nfor i, c in enumerate(s):\n t = s[0:i] + s[i + 1:l]\n ... | <|body_start_0|>
dic = {}
for i, c in enumerate(s):
if c in dic:
dic[c][0] = False
else:
dic[c] = [True, i]
r = -1
for i in dic:
t = dic[i]
if t[0]:
if r == -1 or t[1] < r:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dic = {}
for i, c in enumerate(s):
if c in d... | stack_v2_sparse_classes_75kplus_train_007092 | 742 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar",
"signature": "def firstUniqChar(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar1",
"signature": "def firstUniqChar1(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047669 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar(self, s): :type s: str :rtype: int
- def firstUniqChar1(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar(self, s): :type s: str :rtype: int
- def firstUniqChar1(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def firstUniqChar(self, s):
... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
dic = {}
for i, c in enumerate(s):
if c in dic:
dic[c][0] = False
else:
dic[c] = [True, i]
r = -1
for i in dic:
t = dic[i]
... | the_stack_v2_python_sparse | py/leetcode/387.py | wfeng1991/learnpy | train | 0 | |
13bf17edb20b60bef2ca1380fc1df989cf64456c | [
"self.url = url\nself.auth_token = auth_token\nself.xapi_version = xapi_version",
"headers = {'Authorization': self.auth_token, 'Content-Type': 'application/json', 'X-Experience-API-Version': self.xapi_version}\nresponse = requests.post(self.url, json=xapi_statement.get_statement(), headers=headers, timeout=setti... | <|body_start_0|>
self.url = url
self.auth_token = auth_token
self.xapi_version = xapi_version
<|end_body_0|>
<|body_start_1|>
headers = {'Authorization': self.auth_token, 'Content-Type': 'application/json', 'X-Experience-API-Version': self.xapi_version}
response = requests.post(... | The XAPI object compute statements and send them to a LRS. | XAPI | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XAPI:
"""The XAPI object compute statements and send them to a LRS."""
def __init__(self, url, auth_token, xapi_version='1.0.3'):
"""Initialize the XAPI module. Parameters ---------- url: string The LRS endpoint to fetch auth_token: string The basic_auth token used to authenticate on... | stack_v2_sparse_classes_75kplus_train_007093 | 11,009 | permissive | [
{
"docstring": "Initialize the XAPI module. Parameters ---------- url: string The LRS endpoint to fetch auth_token: string The basic_auth token used to authenticate on the LRS xapi_version: string The xAPI version used.",
"name": "__init__",
"signature": "def __init__(self, url, auth_token, xapi_version... | 2 | stack_v2_sparse_classes_30k_train_001735 | Implement the Python class `XAPI` described below.
Class description:
The XAPI object compute statements and send them to a LRS.
Method signatures and docstrings:
- def __init__(self, url, auth_token, xapi_version='1.0.3'): Initialize the XAPI module. Parameters ---------- url: string The LRS endpoint to fetch auth_t... | Implement the Python class `XAPI` described below.
Class description:
The XAPI object compute statements and send them to a LRS.
Method signatures and docstrings:
- def __init__(self, url, auth_token, xapi_version='1.0.3'): Initialize the XAPI module. Parameters ---------- url: string The LRS endpoint to fetch auth_t... | f767f1bdc12c9712f26ea17cb8b19f536389f0ed | <|skeleton|>
class XAPI:
"""The XAPI object compute statements and send them to a LRS."""
def __init__(self, url, auth_token, xapi_version='1.0.3'):
"""Initialize the XAPI module. Parameters ---------- url: string The LRS endpoint to fetch auth_token: string The basic_auth token used to authenticate on... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XAPI:
"""The XAPI object compute statements and send them to a LRS."""
def __init__(self, url, auth_token, xapi_version='1.0.3'):
"""Initialize the XAPI module. Parameters ---------- url: string The LRS endpoint to fetch auth_token: string The basic_auth token used to authenticate on the LRS xapi... | the_stack_v2_python_sparse | src/backend/marsha/core/xapi.py | openfun/marsha | train | 92 |
22967d5ae9a84b89ccf0c31c0200765a1c308a72 | [
"if null_default_value is None:\n null_default_value = math.log2(min_included)\nelse:\n null_default_value = math.log2(null_default_value)\nself.min_included: float = min_included\nself.max_included: float = max_included\nself.log2_min_included = math.log2(min_included)\nself.log2_max_included = math.log2(max... | <|body_start_0|>
if null_default_value is None:
null_default_value = math.log2(min_included)
else:
null_default_value = math.log2(null_default_value)
self.min_included: float = min_included
self.max_included: float = max_included
self.log2_min_included = m... | Get a LogUniform distribution. Refer to: :class:`scipy.stats.loguniform`. .. seealso:: :func:`~neuraxle.base.BaseStep.set_hyperparams_space`, :class:`ScipyDistributionWrapper`, | ScipyLogUniform | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScipyLogUniform:
"""Get a LogUniform distribution. Refer to: :class:`scipy.stats.loguniform`. .. seealso:: :func:`~neuraxle.base.BaseStep.set_hyperparams_space`, :class:`ScipyDistributionWrapper`,"""
def __init__(self, min_included: float, max_included: float, null_default_value=None):
... | stack_v2_sparse_classes_75kplus_train_007094 | 19,816 | permissive | [
{
"docstring": "Create a quantized random log uniform distribution. A random float between the two values inclusively will be returned. :param min_included: minimum integer, should be somehow included. :param max_included: maximum integer, should be somehow included. :param null_default_value: null default valu... | 2 | stack_v2_sparse_classes_30k_test_000031 | Implement the Python class `ScipyLogUniform` described below.
Class description:
Get a LogUniform distribution. Refer to: :class:`scipy.stats.loguniform`. .. seealso:: :func:`~neuraxle.base.BaseStep.set_hyperparams_space`, :class:`ScipyDistributionWrapper`,
Method signatures and docstrings:
- def __init__(self, min_i... | Implement the Python class `ScipyLogUniform` described below.
Class description:
Get a LogUniform distribution. Refer to: :class:`scipy.stats.loguniform`. .. seealso:: :func:`~neuraxle.base.BaseStep.set_hyperparams_space`, :class:`ScipyDistributionWrapper`,
Method signatures and docstrings:
- def __init__(self, min_i... | af917c984241178436a759be3b830e6d8b03245f | <|skeleton|>
class ScipyLogUniform:
"""Get a LogUniform distribution. Refer to: :class:`scipy.stats.loguniform`. .. seealso:: :func:`~neuraxle.base.BaseStep.set_hyperparams_space`, :class:`ScipyDistributionWrapper`,"""
def __init__(self, min_included: float, max_included: float, null_default_value=None):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScipyLogUniform:
"""Get a LogUniform distribution. Refer to: :class:`scipy.stats.loguniform`. .. seealso:: :func:`~neuraxle.base.BaseStep.set_hyperparams_space`, :class:`ScipyDistributionWrapper`,"""
def __init__(self, min_included: float, max_included: float, null_default_value=None):
"""Create ... | the_stack_v2_python_sparse | neuraxle/hyperparams/scipy_distributions.py | Neuraxio/Neuraxle | train | 597 |
d6e539c4998a5c96d939241236f88c98ccf941d0 | [
"self.lamda = lamda\nself.mu = mu\nsuper(PoissonGenerator, self).__init__(sim=sim)",
"i = 0\nwhile True:\n yield (hold, self, expovariate(self.lamda))\n self.sim.arrivalMonitor.observe(1)\n i = i + 1\n L = User('User %s' % i, sim=self.sim)\n service_time = expovariate(self.mu)\n if service_time ... | <|body_start_0|>
self.lamda = lamda
self.mu = mu
super(PoissonGenerator, self).__init__(sim=sim)
<|end_body_0|>
<|body_start_1|>
i = 0
while True:
yield (hold, self, expovariate(self.lamda))
self.sim.arrivalMonitor.observe(1)
i = i + 1
... | Generates Users at a Poisson rate of lamda | PoissonGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoissonGenerator:
"""Generates Users at a Poisson rate of lamda"""
def __init__(self, sim, lamda, mu):
"""Creates the Poisson user generator sim -- the sim users should arrive at for service lamda -- the parameter to a Poisson distribution which defines the arrival process mu -- the ... | stack_v2_sparse_classes_75kplus_train_007095 | 4,725 | no_license | [
{
"docstring": "Creates the Poisson user generator sim -- the sim users should arrive at for service lamda -- the parameter to a Poisson distribution which defines the arrival process mu -- the parameter to a Poisson distribution which defines the service time process",
"name": "__init__",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_007032 | Implement the Python class `PoissonGenerator` described below.
Class description:
Generates Users at a Poisson rate of lamda
Method signatures and docstrings:
- def __init__(self, sim, lamda, mu): Creates the Poisson user generator sim -- the sim users should arrive at for service lamda -- the parameter to a Poisson ... | Implement the Python class `PoissonGenerator` described below.
Class description:
Generates Users at a Poisson rate of lamda
Method signatures and docstrings:
- def __init__(self, sim, lamda, mu): Creates the Poisson user generator sim -- the sim users should arrive at for service lamda -- the parameter to a Poisson ... | 30dc0702f6189307ff776525a2f3006ec471de47 | <|skeleton|>
class PoissonGenerator:
"""Generates Users at a Poisson rate of lamda"""
def __init__(self, sim, lamda, mu):
"""Creates the Poisson user generator sim -- the sim users should arrive at for service lamda -- the parameter to a Poisson distribution which defines the arrival process mu -- the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PoissonGenerator:
"""Generates Users at a Poisson rate of lamda"""
def __init__(self, sim, lamda, mu):
"""Creates the Poisson user generator sim -- the sim users should arrive at for service lamda -- the parameter to a Poisson distribution which defines the arrival process mu -- the parameter to ... | the_stack_v2_python_sparse | appsim/user_generators.py | bmbouter/vcl_simulation | train | 0 |
ab66a09350d3b10fbf77a06f96d1fd7f7753cdd3 | [
"if name in method_names:\n cpp_call_ast = method_names[name](node)\n return (cpp_call_ast is not None, cpp_call_ast)\nreturn (False, None)",
"self.generic_visit(node)\nfunc = node.func\nif type(func) is ast.Attribute and type(func.value) is ast.Name:\n ok, new_node = self.try_call(func.attr, node)\n ... | <|body_start_0|>
if name in method_names:
cpp_call_ast = method_names[name](node)
return (cpp_call_ast is not None, cpp_call_ast)
return (False, None)
<|end_body_0|>
<|body_start_1|>
self.generic_visit(node)
func = node.func
if type(func) is ast.Attribute... | Look through the complete ast and replace method calls that are to a C++ plug in with a c++ ast node. | cpp_ast_finder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cpp_ast_finder:
"""Look through the complete ast and replace method calls that are to a C++ plug in with a c++ ast node."""
def try_call(self, name, node):
"""Try to use name to do the call. Returns (ok, result) monad"""
<|body_0|>
def visit_Call(self, node):
"""... | stack_v2_sparse_classes_75kplus_train_007096 | 5,586 | no_license | [
{
"docstring": "Try to use name to do the call. Returns (ok, result) monad",
"name": "try_call",
"signature": "def try_call(self, name, node)"
},
{
"docstring": "Looking for a member call of a particular name. We rewrite that as another name. WARNING: currently the namespace is global, so the pa... | 2 | null | Implement the Python class `cpp_ast_finder` described below.
Class description:
Look through the complete ast and replace method calls that are to a C++ plug in with a c++ ast node.
Method signatures and docstrings:
- def try_call(self, name, node): Try to use name to do the call. Returns (ok, result) monad
- def vis... | Implement the Python class `cpp_ast_finder` described below.
Class description:
Look through the complete ast and replace method calls that are to a C++ plug in with a c++ ast node.
Method signatures and docstrings:
- def try_call(self, name, node): Try to use name to do the call. Returns (ok, result) monad
- def vis... | a691229c102658c98e71c8374cd80174a86834a1 | <|skeleton|>
class cpp_ast_finder:
"""Look through the complete ast and replace method calls that are to a C++ plug in with a c++ ast node."""
def try_call(self, name, node):
"""Try to use name to do the call. Returns (ok, result) monad"""
<|body_0|>
def visit_Call(self, node):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class cpp_ast_finder:
"""Look through the complete ast and replace method calls that are to a C++ plug in with a c++ ast node."""
def try_call(self, name, node):
"""Try to use name to do the call. Returns (ok, result) monad"""
if name in method_names:
cpp_call_ast = method_names[nam... | the_stack_v2_python_sparse | adl_func_backend/cpplib/cpp_ast.py | gordonwatts/functional_adl | train | 1 |
0d3f930d073c1590558a69d556e3016cff47fc7a | [
"self.k = k\nself.nm_samples = len(trainset)\nself.indices = list(range(self.nm_samples))\nself.trainset = trainset\nself.batch_size = batch_size\nself.use_gpu = use_gpu",
"for i in range(self.k):\n train_idx = [idx for j, idx in enumerate(self.indices) if j % self.k != i]\n valid_idx = [idx for j, idx in e... | <|body_start_0|>
self.k = k
self.nm_samples = len(trainset)
self.indices = list(range(self.nm_samples))
self.trainset = trainset
self.batch_size = batch_size
self.use_gpu = use_gpu
<|end_body_0|>
<|body_start_1|>
for i in range(self.k):
train_idx = [i... | CrossValidation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossValidation:
def __init__(self, k, batch_size, trainset, use_gpu):
"""k: number of folds batch_size: batch size for training trainset: training data as pytorch iterator use_gpu: boolean variable to use gpus"""
<|body_0|>
def kfold(self):
"""k-fold split"""
... | stack_v2_sparse_classes_75kplus_train_007097 | 4,783 | no_license | [
{
"docstring": "k: number of folds batch_size: batch size for training trainset: training data as pytorch iterator use_gpu: boolean variable to use gpus",
"name": "__init__",
"signature": "def __init__(self, k, batch_size, trainset, use_gpu)"
},
{
"docstring": "k-fold split",
"name": "kfold"... | 4 | stack_v2_sparse_classes_30k_train_037695 | Implement the Python class `CrossValidation` described below.
Class description:
Implement the CrossValidation class.
Method signatures and docstrings:
- def __init__(self, k, batch_size, trainset, use_gpu): k: number of folds batch_size: batch size for training trainset: training data as pytorch iterator use_gpu: bo... | Implement the Python class `CrossValidation` described below.
Class description:
Implement the CrossValidation class.
Method signatures and docstrings:
- def __init__(self, k, batch_size, trainset, use_gpu): k: number of folds batch_size: batch size for training trainset: training data as pytorch iterator use_gpu: bo... | 0d2e07ad43790b39aa038272ec42accedda89683 | <|skeleton|>
class CrossValidation:
def __init__(self, k, batch_size, trainset, use_gpu):
"""k: number of folds batch_size: batch size for training trainset: training data as pytorch iterator use_gpu: boolean variable to use gpus"""
<|body_0|>
def kfold(self):
"""k-fold split"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CrossValidation:
def __init__(self, k, batch_size, trainset, use_gpu):
"""k: number of folds batch_size: batch size for training trainset: training data as pytorch iterator use_gpu: boolean variable to use gpus"""
self.k = k
self.nm_samples = len(trainset)
self.indices = list(r... | the_stack_v2_python_sparse | Session2/kfold.py | MdAsifKhan/cudavision | train | 1 | |
8490fd537ed5d3c28cd597e45f54b5668d6934b4 | [
"super().__init__()\nself.lstm = nn.LSTM(dim_in, hidden_dim, batch_first=True, dropout=dropout, bidirectional=bidirectional)\nself.lstm.flatten_parameters()\nself.output_dim = 2 * hidden_dim if bidirectional else hidden_dim\nself.bidirectional = bidirectional",
"assert data.dim() == 3\nb, t = (data.shape[0], data... | <|body_start_0|>
super().__init__()
self.lstm = nn.LSTM(dim_in, hidden_dim, batch_first=True, dropout=dropout, bidirectional=bidirectional)
self.lstm.flatten_parameters()
self.output_dim = 2 * hidden_dim if bidirectional else hidden_dim
self.bidirectional = bidirectional
<|end_bo... | Wrapper for torch.nn.LSTM that handles masked inputs. | LSTM | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTM:
"""Wrapper for torch.nn.LSTM that handles masked inputs."""
def __init__(self, dim_in: int, hidden_dim: int, dropout: float=0.0, bidirectional: bool=False):
"""Args: dim_in (int): input feature dimension hidden_dim (int): hidden dimesion of lstm layer dropout (float): dropout r... | stack_v2_sparse_classes_75kplus_train_007098 | 13,032 | permissive | [
{
"docstring": "Args: dim_in (int): input feature dimension hidden_dim (int): hidden dimesion of lstm layer dropout (float): dropout rate - 0.0 if no dropout bidirectional (bool): bidirectional or forward only",
"name": "__init__",
"signature": "def __init__(self, dim_in: int, hidden_dim: int, dropout: ... | 2 | stack_v2_sparse_classes_30k_train_038080 | Implement the Python class `LSTM` described below.
Class description:
Wrapper for torch.nn.LSTM that handles masked inputs.
Method signatures and docstrings:
- def __init__(self, dim_in: int, hidden_dim: int, dropout: float=0.0, bidirectional: bool=False): Args: dim_in (int): input feature dimension hidden_dim (int):... | Implement the Python class `LSTM` described below.
Class description:
Wrapper for torch.nn.LSTM that handles masked inputs.
Method signatures and docstrings:
- def __init__(self, dim_in: int, hidden_dim: int, dropout: float=0.0, bidirectional: bool=False): Args: dim_in (int): input feature dimension hidden_dim (int):... | 16f2abf2f8aa174915316007622bbb260215dee8 | <|skeleton|>
class LSTM:
"""Wrapper for torch.nn.LSTM that handles masked inputs."""
def __init__(self, dim_in: int, hidden_dim: int, dropout: float=0.0, bidirectional: bool=False):
"""Args: dim_in (int): input feature dimension hidden_dim (int): hidden dimesion of lstm layer dropout (float): dropout r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LSTM:
"""Wrapper for torch.nn.LSTM that handles masked inputs."""
def __init__(self, dim_in: int, hidden_dim: int, dropout: float=0.0, bidirectional: bool=False):
"""Args: dim_in (int): input feature dimension hidden_dim (int): hidden dimesion of lstm layer dropout (float): dropout rate - 0.0 if ... | the_stack_v2_python_sparse | pytorchvideo/models/masked_multistream.py | xchani/pytorchvideo | train | 0 |
cfc3972a58d46b27bfc5b339490b1086217e69ff | [
"super(GAT, self).__init__()\nself.dropout = dropout\nself.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout, alpha=alpha, device=device, layer=l, concat=True) for _ in range(nheads)]\nfor i, attention in enumerate(self.attentions):\n self.add_module('layer_{}'.format(l) + '_attention_{}'.format(i),... | <|body_start_0|>
super(GAT, self).__init__()
self.dropout = dropout
self.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout, alpha=alpha, device=device, layer=l, concat=True) for _ in range(nheads)]
for i, attention in enumerate(self.attentions):
self.add_module('... | GAT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GAT:
def __init__(self, nfeat, nhid, adj, dropout, alpha, nheads, num_domains, batch_size, k, l, device):
"""Dense version of GAT."""
<|body_0|>
def forward(self, x, adj):
""":param x: tensor with size [(num_domains+1) x batch_size, num_features]. :return:"""
... | stack_v2_sparse_classes_75kplus_train_007099 | 14,327 | no_license | [
{
"docstring": "Dense version of GAT.",
"name": "__init__",
"signature": "def __init__(self, nfeat, nhid, adj, dropout, alpha, nheads, num_domains, batch_size, k, l, device)"
},
{
"docstring": ":param x: tensor with size [(num_domains+1) x batch_size, num_features]. :return:",
"name": "forwa... | 2 | null | Implement the Python class `GAT` described below.
Class description:
Implement the GAT class.
Method signatures and docstrings:
- def __init__(self, nfeat, nhid, adj, dropout, alpha, nheads, num_domains, batch_size, k, l, device): Dense version of GAT.
- def forward(self, x, adj): :param x: tensor with size [(num_dom... | Implement the Python class `GAT` described below.
Class description:
Implement the GAT class.
Method signatures and docstrings:
- def __init__(self, nfeat, nhid, adj, dropout, alpha, nheads, num_domains, batch_size, k, l, device): Dense version of GAT.
- def forward(self, x, adj): :param x: tensor with size [(num_dom... | 58bd98b2795a01a39e54cace005c7a700e86a23a | <|skeleton|>
class GAT:
def __init__(self, nfeat, nhid, adj, dropout, alpha, nheads, num_domains, batch_size, k, l, device):
"""Dense version of GAT."""
<|body_0|>
def forward(self, x, adj):
""":param x: tensor with size [(num_domains+1) x batch_size, num_features]. :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GAT:
def __init__(self, nfeat, nhid, adj, dropout, alpha, nheads, num_domains, batch_size, k, l, device):
"""Dense version of GAT."""
super(GAT, self).__init__()
self.dropout = dropout
self.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout, alpha=alpha, device=devi... | the_stack_v2_python_sparse | amazon/model.py | graph-mdan/graph-mdan | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.