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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
60991d5fdded3f91c26b1af3d77e9c93f1e8baaa | [
"name_to_search_for = self.request.query_params.get('name', None)\nif name_to_search_for:\n matching = ReagentModel.objects.filter(name=name_to_search_for)\n return matching\nreturn ReagentModel.objects.all()",
"try:\n pk = kwargs['pk']\n ReagentModel.objects.filter(pk=pk).delete()\nexcept ProtectedEr... | <|body_start_0|>
name_to_search_for = self.request.query_params.get('name', None)
if name_to_search_for:
matching = ReagentModel.objects.filter(name=name_to_search_for)
return matching
return ReagentModel.objects.all()
<|end_body_0|>
<|body_start_1|>
try:
... | You can specify an optional name-search criteria for the reagent, like this: /api/reagents/?name=Titanium-Taq | ReagentViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReagentViewSet:
"""You can specify an optional name-search criteria for the reagent, like this: /api/reagents/?name=Titanium-Taq"""
def get_queryset(self):
"""Overridden to provide the search functionality."""
<|body_0|>
def destroy(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_068500 | 10,752 | permissive | [
{
"docstring": "Overridden to provide the search functionality.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Overridden to handle issues with foreign key constraints",
"name": "destroy",
"signature": "def destroy(self, request, *args, **kwargs)"
}
... | 2 | stack_v2_sparse_classes_30k_train_019478 | Implement the Python class `ReagentViewSet` described below.
Class description:
You can specify an optional name-search criteria for the reagent, like this: /api/reagents/?name=Titanium-Taq
Method signatures and docstrings:
- def get_queryset(self): Overridden to provide the search functionality.
- def destroy(self, ... | Implement the Python class `ReagentViewSet` described below.
Class description:
You can specify an optional name-search criteria for the reagent, like this: /api/reagents/?name=Titanium-Taq
Method signatures and docstrings:
- def get_queryset(self): Overridden to provide the search functionality.
- def destroy(self, ... | b67f65694fe058dbdb7001f7b30f3cdbc08c686f | <|skeleton|>
class ReagentViewSet:
"""You can specify an optional name-search criteria for the reagent, like this: /api/reagents/?name=Titanium-Taq"""
def get_queryset(self):
"""Overridden to provide the search functionality."""
<|body_0|>
def destroy(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReagentViewSet:
"""You can specify an optional name-search criteria for the reagent, like this: /api/reagents/?name=Titanium-Taq"""
def get_queryset(self):
"""Overridden to provide the search functionality."""
name_to_search_for = self.request.query_params.get('name', None)
if nam... | the_stack_v2_python_sparse | app/views.py | pete-dnae/assay-screening-proj | train | 1 |
9fb0ad4056fe4a027572ba5765a31132a27a9875 | [
"super(Model_Encoder, self).__init__()\nself.num_conv = num_conv\nself.num_blocks = num_blocks\nself.kernel_size = kernel_size\nself.hidden_size = hidden_size\nself.num_heads = num_heads\nself.survival_prob = survival_prob\nself.total_depth = num_blocks * (num_conv + 2) - 1\nself.enc = nn.ModuleList([Encoder_Block(... | <|body_start_0|>
super(Model_Encoder, self).__init__()
self.num_conv = num_conv
self.num_blocks = num_blocks
self.kernel_size = kernel_size
self.hidden_size = hidden_size
self.num_heads = num_heads
self.survival_prob = survival_prob
self.total_depth = num_... | Model_Encoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model_Encoder:
def __init__(self, num_blocks, num_conv, kernel_size, hidden_size, num_heads, survival_prob):
"""QAnet model encoder https://arxiv.org/pdf/1804.09541.pdf Args: @param num_blocks: number of encoder blocks @param num_conv: number of convolutional layers per encoder block @pa... | stack_v2_sparse_classes_75kplus_train_068501 | 22,434 | permissive | [
{
"docstring": "QAnet model encoder https://arxiv.org/pdf/1804.09541.pdf Args: @param num_blocks: number of encoder blocks @param num_conv: number of convolutional layers per encoder block @param kernel_size: kernel size of depthwise seperable convolution @param hidden_size: hidden dimension of QAnet model @par... | 2 | null | Implement the Python class `Model_Encoder` described below.
Class description:
Implement the Model_Encoder class.
Method signatures and docstrings:
- def __init__(self, num_blocks, num_conv, kernel_size, hidden_size, num_heads, survival_prob): QAnet model encoder https://arxiv.org/pdf/1804.09541.pdf Args: @param num_... | Implement the Python class `Model_Encoder` described below.
Class description:
Implement the Model_Encoder class.
Method signatures and docstrings:
- def __init__(self, num_blocks, num_conv, kernel_size, hidden_size, num_heads, survival_prob): QAnet model encoder https://arxiv.org/pdf/1804.09541.pdf Args: @param num_... | da653de190a733b51428737dee8508d8768dfcc9 | <|skeleton|>
class Model_Encoder:
def __init__(self, num_blocks, num_conv, kernel_size, hidden_size, num_heads, survival_prob):
"""QAnet model encoder https://arxiv.org/pdf/1804.09541.pdf Args: @param num_blocks: number of encoder blocks @param num_conv: number of convolutional layers per encoder block @pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Model_Encoder:
def __init__(self, num_blocks, num_conv, kernel_size, hidden_size, num_heads, survival_prob):
"""QAnet model encoder https://arxiv.org/pdf/1804.09541.pdf Args: @param num_blocks: number of encoder blocks @param num_conv: number of convolutional layers per encoder block @param kernel_siz... | the_stack_v2_python_sparse | FinalProject/QANet/QANet_Example/QANet_layers_temp.py | hy2632/cs224n | train | 1 | |
e55e1a6a833d0a43377390a29e50a422f8727509 | [
"task_result_detail = NodeApi.get_subscription_task_detail({'subscription_id': subscription_id, 'instance_id': instance_id})\nlog_gby_sub_host_index = defaultdict(list)\nfor step in task_result_detail.get('steps', []):\n for index, target_host_result_detail in enumerate(step.get('target_hosts', [])):\n lo... | <|body_start_0|>
task_result_detail = NodeApi.get_subscription_task_detail({'subscription_id': subscription_id, 'instance_id': instance_id})
log_gby_sub_host_index = defaultdict(list)
for step in task_result_detail.get('steps', []):
for index, target_host_result_detail in enumerate(s... | Debug处理器 | DebugHandler | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DebugHandler:
"""Debug处理器"""
def get_log(subscription_id: int, instance_id: str) -> Dict[str, List[Dict]]:
"""根据订阅任务ID,实例ID,获取日志 :param subscription_id: 订阅任务ID :param instance_id: 实例ID :return: 日志列表"""
<|body_0|>
def task_details(self, subscription_id, task_id) -> List[D... | stack_v2_sparse_classes_75kplus_train_068502 | 7,021 | permissive | [
{
"docstring": "根据订阅任务ID,实例ID,获取日志 :param subscription_id: 订阅任务ID :param instance_id: 实例ID :return: 日志列表",
"name": "get_log",
"signature": "def get_log(subscription_id: int, instance_id: str) -> Dict[str, List[Dict]]"
},
{
"docstring": "获得任务执行详情 :param subscription_id: 订阅任务ID :param task_id: 任务I... | 5 | null | Implement the Python class `DebugHandler` described below.
Class description:
Debug处理器
Method signatures and docstrings:
- def get_log(subscription_id: int, instance_id: str) -> Dict[str, List[Dict]]: 根据订阅任务ID,实例ID,获取日志 :param subscription_id: 订阅任务ID :param instance_id: 实例ID :return: 日志列表
- def task_details(self, sub... | Implement the Python class `DebugHandler` described below.
Class description:
Debug处理器
Method signatures and docstrings:
- def get_log(subscription_id: int, instance_id: str) -> Dict[str, List[Dict]]: 根据订阅任务ID,实例ID,获取日志 :param subscription_id: 订阅任务ID :param instance_id: 实例ID :return: 日志列表
- def task_details(self, sub... | 72d2104783443bff26c752c5bd934a013b302b6d | <|skeleton|>
class DebugHandler:
"""Debug处理器"""
def get_log(subscription_id: int, instance_id: str) -> Dict[str, List[Dict]]:
"""根据订阅任务ID,实例ID,获取日志 :param subscription_id: 订阅任务ID :param instance_id: 实例ID :return: 日志列表"""
<|body_0|>
def task_details(self, subscription_id, task_id) -> List[D... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DebugHandler:
"""Debug处理器"""
def get_log(subscription_id: int, instance_id: str) -> Dict[str, List[Dict]]:
"""根据订阅任务ID,实例ID,获取日志 :param subscription_id: 订阅任务ID :param instance_id: 实例ID :return: 日志列表"""
task_result_detail = NodeApi.get_subscription_task_detail({'subscription_id': subscript... | the_stack_v2_python_sparse | apps/node_man/handlers/debug.py | TencentBlueKing/bk-nodeman | train | 54 |
4982f4aff17a94f65f753fb1ec1b6a2656bd97ea | [
"message = (tag, ':', text_string)\nif global_step is not None:\n message = ('Global step', global_step, ',') + message\nprint(*message)\nreturn super().add_text(tag, text_string, global_step, walltime)",
"message = (tag, ':', scalar_value)\nif global_step:\n message = ('Global step', global_step, ',') + me... | <|body_start_0|>
message = (tag, ':', text_string)
if global_step is not None:
message = ('Global step', global_step, ',') + message
print(*message)
return super().add_text(tag, text_string, global_step, walltime)
<|end_body_0|>
<|body_start_1|>
message = (tag, ':', ... | SummaryWriter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SummaryWriter:
def add_text(self, tag, text_string, global_step=None, walltime=None):
"""Prints to console before running tensorboardX.SummaryWriter.add_text()"""
<|body_0|>
def add_scalar(self, tag, scalar_value, global_step=None, walltime=None):
"""Prints to consol... | stack_v2_sparse_classes_75kplus_train_068503 | 5,926 | no_license | [
{
"docstring": "Prints to console before running tensorboardX.SummaryWriter.add_text()",
"name": "add_text",
"signature": "def add_text(self, tag, text_string, global_step=None, walltime=None)"
},
{
"docstring": "Prints to console before running tensorboardX.SummaryWriter.add_scalar()",
"nam... | 2 | stack_v2_sparse_classes_30k_train_010378 | Implement the Python class `SummaryWriter` described below.
Class description:
Implement the SummaryWriter class.
Method signatures and docstrings:
- def add_text(self, tag, text_string, global_step=None, walltime=None): Prints to console before running tensorboardX.SummaryWriter.add_text()
- def add_scalar(self, tag... | Implement the Python class `SummaryWriter` described below.
Class description:
Implement the SummaryWriter class.
Method signatures and docstrings:
- def add_text(self, tag, text_string, global_step=None, walltime=None): Prints to console before running tensorboardX.SummaryWriter.add_text()
- def add_scalar(self, tag... | e0f6183e6b669c078793b326839665f69b3f324e | <|skeleton|>
class SummaryWriter:
def add_text(self, tag, text_string, global_step=None, walltime=None):
"""Prints to console before running tensorboardX.SummaryWriter.add_text()"""
<|body_0|>
def add_scalar(self, tag, scalar_value, global_step=None, walltime=None):
"""Prints to consol... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SummaryWriter:
def add_text(self, tag, text_string, global_step=None, walltime=None):
"""Prints to console before running tensorboardX.SummaryWriter.add_text()"""
message = (tag, ':', text_string)
if global_step is not None:
message = ('Global step', global_step, ',') + mes... | the_stack_v2_python_sparse | experiments/base.py | ctrl-q/pass-the-torch | train | 0 | |
ee849f3fd15a2326387f9be0dbb3d00b43825a75 | [
"batch, channel, height, width = fmap.shape\nfmap = CenterNetDecoder.pseudo_nms(fmap)\nscores, index, clses, ys, xs = CenterNetDecoder.topk_score(fmap, K=K)\nif reg is not None:\n reg = gather_feature(reg, index, use_transform=True)\n reg = reg.reshape(batch, K, 2)\n xs = xs.view(batch, K, 1) + reg[:, :, 0... | <|body_start_0|>
batch, channel, height, width = fmap.shape
fmap = CenterNetDecoder.pseudo_nms(fmap)
scores, index, clses, ys, xs = CenterNetDecoder.topk_score(fmap, K=K)
if reg is not None:
reg = gather_feature(reg, index, use_transform=True)
reg = reg.reshape(ba... | CenterNetDecoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CenterNetDecoder:
def decode(fmap, wh, reg=None, cat_spec_wh=False, K=100):
"""decode feature maps, width height, regression to detections results. Args: fmap (Tensor): input feature map. wh (Tensor): tensor represents (width, height). reg (Tensor): tensor represents regression. cat_spec... | stack_v2_sparse_classes_75kplus_train_068504 | 21,641 | permissive | [
{
"docstring": "decode feature maps, width height, regression to detections results. Args: fmap (Tensor): input feature map. wh (Tensor): tensor represents (width, height). reg (Tensor): tensor represents regression. cat_spec_wh (bool): whether reshape wh tensor. K (int): top k value in score map.",
"name":... | 4 | stack_v2_sparse_classes_30k_val_002561 | Implement the Python class `CenterNetDecoder` described below.
Class description:
Implement the CenterNetDecoder class.
Method signatures and docstrings:
- def decode(fmap, wh, reg=None, cat_spec_wh=False, K=100): decode feature maps, width height, regression to detections results. Args: fmap (Tensor): input feature ... | Implement the Python class `CenterNetDecoder` described below.
Class description:
Implement the CenterNetDecoder class.
Method signatures and docstrings:
- def decode(fmap, wh, reg=None, cat_spec_wh=False, K=100): decode feature maps, width height, regression to detections results. Args: fmap (Tensor): input feature ... | 2deea5dc659371318c8a570c644201d913a83027 | <|skeleton|>
class CenterNetDecoder:
def decode(fmap, wh, reg=None, cat_spec_wh=False, K=100):
"""decode feature maps, width height, regression to detections results. Args: fmap (Tensor): input feature map. wh (Tensor): tensor represents (width, height). reg (Tensor): tensor represents regression. cat_spec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CenterNetDecoder:
def decode(fmap, wh, reg=None, cat_spec_wh=False, K=100):
"""decode feature maps, width height, regression to detections results. Args: fmap (Tensor): input feature map. wh (Tensor): tensor represents (width, height). reg (Tensor): tensor represents regression. cat_spec_wh (bool): wh... | the_stack_v2_python_sparse | cvpods/modeling/meta_arch/centernet.py | Megvii-BaseDetection/cvpods | train | 659 | |
c2d03f549c0607a6a8053fa0c9bbc3e925862869 | [
"self.copy_run_targets = copy_run_targets\nself.run_now_parameters = run_now_parameters\nself.run_type = run_type\nself.source_ids = source_ids\nself.use_policy_defaults = use_policy_defaults",
"if dictionary is None:\n return None\ncopy_run_targets = None\nif dictionary.get('copyRunTargets') != None:\n cop... | <|body_start_0|>
self.copy_run_targets = copy_run_targets
self.run_now_parameters = run_now_parameters
self.run_type = run_type
self.source_ids = source_ids
self.use_policy_defaults = use_policy_defaults
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'RunProtectionJobParam' model. Specify the parameters to run a protection job. Attributes: copy_run_targets (list of RunJobSnapshotTarget): Optional parameter to be set if you want specific replication or archival associated with the policy to run. run_now_parameters (list of RunNowParameters): Op... | RunProtectionJobParam | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunProtectionJobParam:
"""Implementation of the 'RunProtectionJobParam' model. Specify the parameters to run a protection job. Attributes: copy_run_targets (list of RunJobSnapshotTarget): Optional parameter to be set if you want specific replication or archival associated with the policy to run. ... | stack_v2_sparse_classes_75kplus_train_068505 | 4,597 | permissive | [
{
"docstring": "Constructor for the RunProtectionJobParam class",
"name": "__init__",
"signature": "def __init__(self, copy_run_targets=None, run_now_parameters=None, run_type=None, source_ids=None, use_policy_defaults=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary... | 2 | null | Implement the Python class `RunProtectionJobParam` described below.
Class description:
Implementation of the 'RunProtectionJobParam' model. Specify the parameters to run a protection job. Attributes: copy_run_targets (list of RunJobSnapshotTarget): Optional parameter to be set if you want specific replication or archi... | Implement the Python class `RunProtectionJobParam` described below.
Class description:
Implementation of the 'RunProtectionJobParam' model. Specify the parameters to run a protection job. Attributes: copy_run_targets (list of RunJobSnapshotTarget): Optional parameter to be set if you want specific replication or archi... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RunProtectionJobParam:
"""Implementation of the 'RunProtectionJobParam' model. Specify the parameters to run a protection job. Attributes: copy_run_targets (list of RunJobSnapshotTarget): Optional parameter to be set if you want specific replication or archival associated with the policy to run. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RunProtectionJobParam:
"""Implementation of the 'RunProtectionJobParam' model. Specify the parameters to run a protection job. Attributes: copy_run_targets (list of RunJobSnapshotTarget): Optional parameter to be set if you want specific replication or archival associated with the policy to run. run_now_param... | the_stack_v2_python_sparse | cohesity_management_sdk/models/run_protection_job_param.py | cohesity/management-sdk-python | train | 24 |
df7041f5b63176c0218a04ce9a7307e8ed35e0f9 | [
"num_classes = self.task_config.model.num_classes\ninput_size = self.task_config.model.input_size\nif params.tfds_name:\n decoder = cli.Decoder()\nelse:\n decoder = classification_input.Decoder()\nparser = classification_input.Parser(output_size=input_size[:2], num_classes=num_classes, dtype=params.dtype)\nre... | <|body_start_0|>
num_classes = self.task_config.model.num_classes
input_size = self.task_config.model.input_size
if params.tfds_name:
decoder = cli.Decoder()
else:
decoder = classification_input.Decoder()
parser = classification_input.Parser(output_size=in... | A task for image classification. | ImageClassificationTask | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageClassificationTask:
"""A task for image classification."""
def build_inputs(self, params, input_context=None):
"""Builds classification input."""
<|body_0|>
def train_step(self, inputs, model, optimizer, metrics=None):
"""Does forward and backward. Args: inp... | stack_v2_sparse_classes_75kplus_train_068506 | 4,431 | permissive | [
{
"docstring": "Builds classification input.",
"name": "build_inputs",
"signature": "def build_inputs(self, params, input_context=None)"
},
{
"docstring": "Does forward and backward. Args: inputs: a dictionary of input tensors. model: the model, forward pass definition. optimizer: the optimizer ... | 2 | stack_v2_sparse_classes_30k_train_038103 | Implement the Python class `ImageClassificationTask` described below.
Class description:
A task for image classification.
Method signatures and docstrings:
- def build_inputs(self, params, input_context=None): Builds classification input.
- def train_step(self, inputs, model, optimizer, metrics=None): Does forward an... | Implement the Python class `ImageClassificationTask` described below.
Class description:
A task for image classification.
Method signatures and docstrings:
- def build_inputs(self, params, input_context=None): Builds classification input.
- def train_step(self, inputs, model, optimizer, metrics=None): Does forward an... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class ImageClassificationTask:
"""A task for image classification."""
def build_inputs(self, params, input_context=None):
"""Builds classification input."""
<|body_0|>
def train_step(self, inputs, model, optimizer, metrics=None):
"""Does forward and backward. Args: inp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageClassificationTask:
"""A task for image classification."""
def build_inputs(self, params, input_context=None):
"""Builds classification input."""
num_classes = self.task_config.model.num_classes
input_size = self.task_config.model.input_size
if params.tfds_name:
... | the_stack_v2_python_sparse | models/official/vision/beta/projects/yolo/tasks/image_classification.py | aboerzel/German_License_Plate_Recognition | train | 34 |
19111e86fc220b98edc29cb708fb416c5482a2aa | [
"super().__init__(cost_multiplier=cost_multiplier)\nself.control_weights = control_weights\nself.controls_size = control_eval_count * control_count\nself.max_control_norms = max_control_norms",
"if self.max_control_norms is not None:\n controls = controls / self.max_control_norms\nif self.control_weights is no... | <|body_start_0|>
super().__init__(cost_multiplier=cost_multiplier)
self.control_weights = control_weights
self.controls_size = control_eval_count * control_count
self.max_control_norms = max_control_norms
<|end_body_0|>
<|body_start_1|>
if self.max_control_norms is not None:
... | This cost penalizes the value of the norm of the control parameters. Fields: control_weights :: ndarray (control_eval_count x control_count) - These weights, each of which should be no greater than 1, represent the factor by which each control's magnitude is penalized. If no weights are specified, each control's magnit... | ControlNorm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControlNorm:
"""This cost penalizes the value of the norm of the control parameters. Fields: control_weights :: ndarray (control_eval_count x control_count) - These weights, each of which should be no greater than 1, represent the factor by which each control's magnitude is penalized. If no weigh... | stack_v2_sparse_classes_75kplus_train_068507 | 2,163 | permissive | [
{
"docstring": "See class fields for arguments not listed here. Arguments: control_count control_eval_count",
"name": "__init__",
"signature": "def __init__(self, control_count, control_eval_count, control_weights=None, cost_multiplier=1.0, max_control_norms=None)"
},
{
"docstring": "Compute the... | 2 | stack_v2_sparse_classes_30k_train_011006 | Implement the Python class `ControlNorm` described below.
Class description:
This cost penalizes the value of the norm of the control parameters. Fields: control_weights :: ndarray (control_eval_count x control_count) - These weights, each of which should be no greater than 1, represent the factor by which each contro... | Implement the Python class `ControlNorm` described below.
Class description:
This cost penalizes the value of the norm of the control parameters. Fields: control_weights :: ndarray (control_eval_count x control_count) - These weights, each of which should be no greater than 1, represent the factor by which each contro... | 36d615170effc1b705d4543d92f979e511edfec2 | <|skeleton|>
class ControlNorm:
"""This cost penalizes the value of the norm of the control parameters. Fields: control_weights :: ndarray (control_eval_count x control_count) - These weights, each of which should be no greater than 1, represent the factor by which each control's magnitude is penalized. If no weigh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ControlNorm:
"""This cost penalizes the value of the norm of the control parameters. Fields: control_weights :: ndarray (control_eval_count x control_count) - These weights, each of which should be no greater than 1, represent the factor by which each control's magnitude is penalized. If no weights are specif... | the_stack_v2_python_sparse | qoc/standard/costs/controlnorm.py | SchusterLab/qoc | train | 12 |
6abd1c9d9b11089b2e678fdd6854fe573b050152 | [
"ptr1 = ptr2 = head\nwhile ptr1 and ptr1.next:\n ptr1 = ptr1.next.next\n ptr2 = ptr2.next\nif ptr1 and (not ptr1.next):\n ptr2 = ptr2.next\nhead2 = self.reverse(ptr2)\nwhile head2:\n if head.val != head2.val:\n return False\n head = head.next\n head2 = head2.next\nreturn True",
"if not he... | <|body_start_0|>
ptr1 = ptr2 = head
while ptr1 and ptr1.next:
ptr1 = ptr1.next.next
ptr2 = ptr2.next
if ptr1 and (not ptr1.next):
ptr2 = ptr2.next
head2 = self.reverse(ptr2)
while head2:
if head.val != head2.val:
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
"""O(1) space complexity, O(N) time complexity :param head: :return:"""
<|body_0|>
def reverse(self, head_node) -> Optional[ListNode]:
"""reverse linked list (non-recursive) :param head_node: :return... | stack_v2_sparse_classes_75kplus_train_068508 | 2,164 | no_license | [
{
"docstring": "O(1) space complexity, O(N) time complexity :param head: :return:",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head: Optional[ListNode]) -> bool"
},
{
"docstring": "reverse linked list (non-recursive) :param head_node: :return:",
"name": "reverse",
"sign... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head: Optional[ListNode]) -> bool: O(1) space complexity, O(N) time complexity :param head: :return:
- def reverse(self, head_node) -> Optional[ListNode]: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head: Optional[ListNode]) -> bool: O(1) space complexity, O(N) time complexity :param head: :return:
- def reverse(self, head_node) -> Optional[ListNode]: ... | 46bd8d1b44cb19aa773cc072cc9be97e9a0e348d | <|skeleton|>
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
"""O(1) space complexity, O(N) time complexity :param head: :return:"""
<|body_0|>
def reverse(self, head_node) -> Optional[ListNode]:
"""reverse linked list (non-recursive) :param head_node: :return... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
"""O(1) space complexity, O(N) time complexity :param head: :return:"""
ptr1 = ptr2 = head
while ptr1 and ptr1.next:
ptr1 = ptr1.next.next
ptr2 = ptr2.next
if ptr1 and (not ptr1.next):
... | the_stack_v2_python_sparse | src/python/data_structure/linked_list/234_palindrome_list.py | alannesta/algo4 | train | 0 | |
569f7f3de153c48bbabff79523091c2d12c1c6ff | [
"self.ps = PastaSauce()\nself.desired_capabilities['name'] = self.id()\nif not LOCAL_RUN:\n self.student = Student(use_env_vars=True, pasta_user=self.ps, capabilities=self.desired_capabilities)\nelse:\n self.student = Student(use_env_vars=True)\nself.student.login()",
"if not LOCAL_RUN:\n self.ps.update_... | <|body_start_0|>
self.ps = PastaSauce()
self.desired_capabilities['name'] = self.id()
if not LOCAL_RUN:
self.student = Student(use_env_vars=True, pasta_user=self.ps, capabilities=self.desired_capabilities)
else:
self.student = Student(use_env_vars=True)
se... | Student - Navigation Shortcuts. | TestViewTheListDashboard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestViewTheListDashboard:
"""Student - Navigation Shortcuts."""
def setUp(self):
"""Pretest settings."""
<|body_0|>
def tearDown(self):
"""Test destructor."""
<|body_1|>
def test_student_select_a_course_162194(self):
"""#STEPS Go to https://t... | stack_v2_sparse_classes_75kplus_train_068509 | 4,121 | no_license | [
{
"docstring": "Pretest settings.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test destructor.",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "#STEPS Go to https://tutor-qa.openstax.org/ Click on the 'Login' button Enter the stu... | 3 | stack_v2_sparse_classes_30k_train_020325 | Implement the Python class `TestViewTheListDashboard` described below.
Class description:
Student - Navigation Shortcuts.
Method signatures and docstrings:
- def setUp(self): Pretest settings.
- def tearDown(self): Test destructor.
- def test_student_select_a_course_162194(self): #STEPS Go to https://tutor-qa.opensta... | Implement the Python class `TestViewTheListDashboard` described below.
Class description:
Student - Navigation Shortcuts.
Method signatures and docstrings:
- def setUp(self): Pretest settings.
- def tearDown(self): Test destructor.
- def test_student_select_a_course_162194(self): #STEPS Go to https://tutor-qa.opensta... | 39751799858ac30df90760b8bb753d338e8edc46 | <|skeleton|>
class TestViewTheListDashboard:
"""Student - Navigation Shortcuts."""
def setUp(self):
"""Pretest settings."""
<|body_0|>
def tearDown(self):
"""Test destructor."""
<|body_1|>
def test_student_select_a_course_162194(self):
"""#STEPS Go to https://t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestViewTheListDashboard:
"""Student - Navigation Shortcuts."""
def setUp(self):
"""Pretest settings."""
self.ps = PastaSauce()
self.desired_capabilities['name'] = self.id()
if not LOCAL_RUN:
self.student = Student(use_env_vars=True, pasta_user=self.ps, capabil... | the_stack_v2_python_sparse | tutor/TestRewrite/Tutor/Dashboard/test_student_tutor_navigation_shortcuts.py | openstax/test-automation | train | 4 |
b8f7b6633430512ff60337ce3a4275c3d76f5ddd | [
"nums.sort()\nprint(nums)\nprint(nums[len(nums) - k])\nreturn nums[len(nums) - k]",
"pivot = nums[0]\nleft = [l for l in nums if l < pivot]\nequal = [e for e in nums if e == pivot]\nright = [r for r in nums if r > pivot]\nif k <= len(right):\n return self.findKthLargest2(right, k)\nelif k - len(right) <= len(e... | <|body_start_0|>
nums.sort()
print(nums)
print(nums[len(nums) - k])
return nums[len(nums) - k]
<|end_body_0|>
<|body_start_1|>
pivot = nums[0]
left = [l for l in nums if l < pivot]
equal = [e for e in nums if e == pivot]
right = [r for r in nums if r > pi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findKthLargest2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.s... | stack_v2_sparse_classes_75kplus_train_068510 | 780 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findKthLargest",
"signature": "def findKthLargest(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findKthLargest2",
"signature": "def findKthLargest2(self, nums, k)"
}... | 2 | stack_v2_sparse_classes_30k_train_029390 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findKthLargest2(self, nums, k): :type nums: List[int] :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findKthLargest2(self, nums, k): :type nums: List[int] :type k: int :rtype: int
<|skeleton... | eb5f6488c875c107743f84a44cbbf55ff7ed3296 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findKthLargest2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
nums.sort()
print(nums)
print(nums[len(nums) - k])
return nums[len(nums) - k]
def findKthLargest2(self, nums, k):
""":type nums: List[int] :type k: int :rtype:... | the_stack_v2_python_sparse | 215__Kth Largest Element.py | chengcheng8632/lovely-nuts | train | 0 | |
179059de3a08256bcbca884f8cb24c47066e7ea0 | [
"from GoogleDrive import drives_list_command\nwith open('test_data/drives_list_response.json', encoding='utf-8') as data:\n mock_response = json.load(data)\nmocker_http_request.return_value = mock_response\nargs = {'use_domain_admin_access': True}\nresult = drives_list_command(gsuite_client, args)\nassert 'Googl... | <|body_start_0|>
from GoogleDrive import drives_list_command
with open('test_data/drives_list_response.json', encoding='utf-8') as data:
mock_response = json.load(data)
mocker_http_request.return_value = mock_response
args = {'use_domain_admin_access': True}
result = ... | TestDriveMethods | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDriveMethods:
def test_drives_list_command_success(self, mocker_http_request, gsuite_client):
"""Scenario: For google-drive-drives-list command successful run. Given: - Command args. When: - Calling google-drive-drives-list command with the parameters provided. Then: - Ensure command... | stack_v2_sparse_classes_75kplus_train_068511 | 33,071 | permissive | [
{
"docstring": "Scenario: For google-drive-drives-list command successful run. Given: - Command args. When: - Calling google-drive-drives-list command with the parameters provided. Then: - Ensure command's raw_response, outputs should be as expected.",
"name": "test_drives_list_command_success",
"signat... | 4 | stack_v2_sparse_classes_30k_test_002949 | Implement the Python class `TestDriveMethods` described below.
Class description:
Implement the TestDriveMethods class.
Method signatures and docstrings:
- def test_drives_list_command_success(self, mocker_http_request, gsuite_client): Scenario: For google-drive-drives-list command successful run. Given: - Command ar... | Implement the Python class `TestDriveMethods` described below.
Class description:
Implement the TestDriveMethods class.
Method signatures and docstrings:
- def test_drives_list_command_success(self, mocker_http_request, gsuite_client): Scenario: For google-drive-drives-list command successful run. Given: - Command ar... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestDriveMethods:
def test_drives_list_command_success(self, mocker_http_request, gsuite_client):
"""Scenario: For google-drive-drives-list command successful run. Given: - Command args. When: - Calling google-drive-drives-list command with the parameters provided. Then: - Ensure command... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDriveMethods:
def test_drives_list_command_success(self, mocker_http_request, gsuite_client):
"""Scenario: For google-drive-drives-list command successful run. Given: - Command args. When: - Calling google-drive-drives-list command with the parameters provided. Then: - Ensure command's raw_respons... | the_stack_v2_python_sparse | Packs/GoogleDrive/Integrations/GoogleDrive/GoogleDrive_test.py | demisto/content | train | 1,023 | |
5ba373ddc47ab472f5b2a9506a1a945bdc0f5612 | [
"self.color_array = color_array / 255.0\nself.n = len(self.color_array)\nself.base = np.arange(0, self.n)",
"cx = np.clip(xs * self.n, 0, self.n)\nr = np.interp(cx, self.base, self.color_array[:, 0])\ng = np.interp(cx, self.base, self.color_array[:, 1])\nb = np.interp(cx, self.base, self.color_array[:, 2])\nretur... | <|body_start_0|>
self.color_array = color_array / 255.0
self.n = len(self.color_array)
self.base = np.arange(0, self.n)
<|end_body_0|>
<|body_start_1|>
cx = np.clip(xs * self.n, 0, self.n)
r = np.interp(cx, self.base, self.color_array[:, 0])
g = np.interp(cx, self.base, ... | ColorGradient | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorGradient:
def __init__(self, color_array):
"""Create a color gradient from an array of RGB integer tuples"""
<|body_0|>
def __call__(self, xs):
"""Given a floating point value in [0,1], return the RGB color as an floating point triple."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_068512 | 6,408 | permissive | [
{
"docstring": "Create a color gradient from an array of RGB integer tuples",
"name": "__init__",
"signature": "def __init__(self, color_array)"
},
{
"docstring": "Given a floating point value in [0,1], return the RGB color as an floating point triple.",
"name": "__call__",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_044793 | Implement the Python class `ColorGradient` described below.
Class description:
Implement the ColorGradient class.
Method signatures and docstrings:
- def __init__(self, color_array): Create a color gradient from an array of RGB integer tuples
- def __call__(self, xs): Given a floating point value in [0,1], return the... | Implement the Python class `ColorGradient` described below.
Class description:
Implement the ColorGradient class.
Method signatures and docstrings:
- def __init__(self, color_array): Create a color gradient from an array of RGB integer tuples
- def __call__(self, xs): Given a floating point value in [0,1], return the... | 5925d156c4ab41157884ec656fea21f4894df45a | <|skeleton|>
class ColorGradient:
def __init__(self, color_array):
"""Create a color gradient from an array of RGB integer tuples"""
<|body_0|>
def __call__(self, xs):
"""Given a floating point value in [0,1], return the RGB color as an floating point triple."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ColorGradient:
def __init__(self, color_array):
"""Create a color gradient from an array of RGB integer tuples"""
self.color_array = color_array / 255.0
self.n = len(self.color_array)
self.base = np.arange(0, self.n)
def __call__(self, xs):
"""Given a floating poin... | the_stack_v2_python_sparse | pyspheregl/utils/graphics_utils.py | johnhw/pyspheregl | train | 1 | |
bb26aae63085c8b70ddf60b64f341462e2644d8b | [
"self.not_full.acquire()\ntry:\n if self.maxsize > 0:\n if not block:\n if self._qsize() == self.maxsize:\n raise Full\n elif timeout is None:\n while self._qsize() == self.maxsize:\n self.not_full.wait()\n elif timeout < 0:\n ra... | <|body_start_0|>
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout is None:
while self._qsize() == self.maxsize:
... | TestQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestQueue:
def putall(self, list, block=True, timeout=None):
"""Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds ... | stack_v2_sparse_classes_75kplus_train_068513 | 3,081 | no_license | [
{
"docstring": "Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available within that ... | 2 | null | Implement the Python class `TestQueue` described below.
Class description:
Implement the TestQueue class.
Method signatures and docstrings:
- def putall(self, list, block=True, timeout=None): Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a f... | Implement the Python class `TestQueue` described below.
Class description:
Implement the TestQueue class.
Method signatures and docstrings:
- def putall(self, list, block=True, timeout=None): Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a f... | 3c897e5d6ee453d0a2f3b371b5eda5af954b8d1a | <|skeleton|>
class TestQueue:
def putall(self, list, block=True, timeout=None):
"""Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestQueue:
def putall(self, list, block=True, timeout=None):
"""Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the... | the_stack_v2_python_sparse | utils/TestQueue.py | qianyc1020/server | train | 1 | |
4cdd7c6c199267a8a759f5326c7af36d514e07b7 | [
"self.get_swift_stat()\ncontainer_name = self.create_container()\nobj_name, obj_data = self.upload_object_to_container(container_name)\nself.list_and_check_container_objects(container_name, present_obj=[obj_name])\nself.download_and_verify(container_name, obj_name, obj_data)\nself.delete_object(container_name, obj_... | <|body_start_0|>
self.get_swift_stat()
container_name = self.create_container()
obj_name, obj_data = self.upload_object_to_container(container_name)
self.list_and_check_container_objects(container_name, present_obj=[obj_name])
self.download_and_verify(container_name, obj_name, ob... | TestObjectStorageBasicOps | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestObjectStorageBasicOps:
def test_swift_basic_ops(self):
"""Test swift basic ops. * get swift stat. * create container. * upload a file to the created container. * list container's objects and assure that the uploaded file is present. * download the object and check the content * delet... | stack_v2_sparse_classes_75kplus_train_068514 | 3,389 | permissive | [
{
"docstring": "Test swift basic ops. * get swift stat. * create container. * upload a file to the created container. * list container's objects and assure that the uploaded file is present. * download the object and check the content * delete object from container. * list container's objects and assure that th... | 2 | stack_v2_sparse_classes_30k_train_005300 | Implement the Python class `TestObjectStorageBasicOps` described below.
Class description:
Implement the TestObjectStorageBasicOps class.
Method signatures and docstrings:
- def test_swift_basic_ops(self): Test swift basic ops. * get swift stat. * create container. * upload a file to the created container. * list con... | Implement the Python class `TestObjectStorageBasicOps` described below.
Class description:
Implement the TestObjectStorageBasicOps class.
Method signatures and docstrings:
- def test_swift_basic_ops(self): Test swift basic ops. * get swift stat. * create container. * upload a file to the created container. * list con... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class TestObjectStorageBasicOps:
def test_swift_basic_ops(self):
"""Test swift basic ops. * get swift stat. * create container. * upload a file to the created container. * list container's objects and assure that the uploaded file is present. * download the object and check the content * delet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestObjectStorageBasicOps:
def test_swift_basic_ops(self):
"""Test swift basic ops. * get swift stat. * create container. * upload a file to the created container. * list container's objects and assure that the uploaded file is present. * download the object and check the content * delete object from ... | the_stack_v2_python_sparse | tempest/scenario/test_object_storage_basic_ops.py | openstack/tempest | train | 270 | |
ff6604f3379ee9b54442c94e92daf70696be45fd | [
"super(LayerNorm, self).__init__()\nself.a_2 = nn.Parameter(torch.ones(d_model))\nself.b_2 = nn.Parameter(torch.zeros(d_model))\nself.eps = eps",
"mean = x.mean(-1, keepdim=True)\nstd = x.std(-1, keepdim=True)\nreturn self.a_2 * (x - mean) / (std + self.eps) + self.b_2"
] | <|body_start_0|>
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(d_model))
self.b_2 = nn.Parameter(torch.zeros(d_model))
self.eps = eps
<|end_body_0|>
<|body_start_1|>
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.... | Construct a layernorm module (See citation for details) | LayerNorm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerNorm:
"""Construct a layernorm module (See citation for details)"""
def __init__(self, d_model: int, eps=1e-16):
"""self.a_2 and self.b_2 are weights and biases which will apply across the embedding dimension (d_model)"""
<|body_0|>
def forward(self, x):
"""... | stack_v2_sparse_classes_75kplus_train_068515 | 2,452 | no_license | [
{
"docstring": "self.a_2 and self.b_2 are weights and biases which will apply across the embedding dimension (d_model)",
"name": "__init__",
"signature": "def __init__(self, d_model: int, eps=1e-16)"
},
{
"docstring": "Takes the mean and the standard deviation on the last dimension (d_model embe... | 2 | stack_v2_sparse_classes_30k_train_012182 | Implement the Python class `LayerNorm` described below.
Class description:
Construct a layernorm module (See citation for details)
Method signatures and docstrings:
- def __init__(self, d_model: int, eps=1e-16): self.a_2 and self.b_2 are weights and biases which will apply across the embedding dimension (d_model)
- d... | Implement the Python class `LayerNorm` described below.
Class description:
Construct a layernorm module (See citation for details)
Method signatures and docstrings:
- def __init__(self, d_model: int, eps=1e-16): self.a_2 and self.b_2 are weights and biases which will apply across the embedding dimension (d_model)
- d... | 4a0a6c13838987f6a66c79dd71c6f49943548b1d | <|skeleton|>
class LayerNorm:
"""Construct a layernorm module (See citation for details)"""
def __init__(self, d_model: int, eps=1e-16):
"""self.a_2 and self.b_2 are weights and biases which will apply across the embedding dimension (d_model)"""
<|body_0|>
def forward(self, x):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LayerNorm:
"""Construct a layernorm module (See citation for details)"""
def __init__(self, d_model: int, eps=1e-16):
"""self.a_2 and self.b_2 are weights and biases which will apply across the embedding dimension (d_model)"""
super(LayerNorm, self).__init__()
self.a_2 = nn.Parame... | the_stack_v2_python_sparse | model/common.py | aixiaomao/transformer | train | 0 |
1083f3c34af81b21cb30b74e19554dfffbad791f | [
"old_password = 'old_password' in data and data['old_password']\npassword = 'password' in data and data['password']\nconfirm_password = 'confirm_password' in data and data['confirm_password']\nerrors = {}\nif not old_password:\n errors['old_password'] = ['Old password was not provided']\nif not password:\n er... | <|body_start_0|>
old_password = 'old_password' in data and data['old_password']
password = 'password' in data and data['password']
confirm_password = 'confirm_password' in data and data['confirm_password']
errors = {}
if not old_password:
errors['old_password'] = ['Ol... | Serializers for update password | PasswordSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordSerializer:
"""Serializers for update password"""
def validate(self, data):
"""This method validates the password value is equal to confirm_password value"""
<|body_0|>
def validate_old_password(self, value):
"""This method validates the old_password"""
... | stack_v2_sparse_classes_75kplus_train_068516 | 2,033 | permissive | [
{
"docstring": "This method validates the password value is equal to confirm_password value",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "This method validates the old_password",
"name": "validate_old_password",
"signature": "def validate_old_password(s... | 3 | stack_v2_sparse_classes_30k_val_001074 | Implement the Python class `PasswordSerializer` described below.
Class description:
Serializers for update password
Method signatures and docstrings:
- def validate(self, data): This method validates the password value is equal to confirm_password value
- def validate_old_password(self, value): This method validates ... | Implement the Python class `PasswordSerializer` described below.
Class description:
Serializers for update password
Method signatures and docstrings:
- def validate(self, data): This method validates the password value is equal to confirm_password value
- def validate_old_password(self, value): This method validates ... | ba93610cdb5ad04fd93effbb0249139b351bc226 | <|skeleton|>
class PasswordSerializer:
"""Serializers for update password"""
def validate(self, data):
"""This method validates the password value is equal to confirm_password value"""
<|body_0|>
def validate_old_password(self, value):
"""This method validates the old_password"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PasswordSerializer:
"""Serializers for update password"""
def validate(self, data):
"""This method validates the password value is equal to confirm_password value"""
old_password = 'old_password' in data and data['old_password']
password = 'password' in data and data['password']
... | the_stack_v2_python_sparse | project/db/serializers/password_serializer.py | AdejokeOgunyinka/cinch-API | train | 0 |
fded211e5b91ce2dd6024f3934dfdc3c1c394c51 | [
"row = set()\ncolumn = set()\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == 0:\n row.add(i)\n column.add(j)\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if i in row or j in column:\n matrix[i][j] = 0",
... | <|body_start_0|>
row = set()
column = set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
row.add(i)
column.add(j)
for i in range(len(matrix)):
for j in range(len(matrix[0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead. O(m+n) space and O(mn) time"""
<|body_0|>
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-plac... | stack_v2_sparse_classes_75kplus_train_068517 | 1,492 | no_license | [
{
"docstring": "Do not return anything, modify matrix in-place instead. O(m+n) space and O(mn) time",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix: List[List[int]]) -> None"
},
{
"docstring": "Do not return anything, modify matrix in-place instead. O(1) space O(mn) time, is_col ... | 2 | stack_v2_sparse_classes_30k_val_002135 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead. O(m+n) space and O(mn) time
- def setZeroes(self, matrix: List[List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead. O(m+n) space and O(mn) time
- def setZeroes(self, matrix: List[List[... | 237985eea9853a658f811355e8c75d6b141e40b2 | <|skeleton|>
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead. O(m+n) space and O(mn) time"""
<|body_0|>
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-plac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead. O(m+n) space and O(mn) time"""
row = set()
column = set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matri... | the_stack_v2_python_sparse | 73. Set Matrix Zeroes.py | Eustaceyi/Leetcode | train | 0 | |
d12fb067aae083131233f7b5f9dd25f1d0c7a58c | [
"cls.componentsFilePath.append(file_path)\nparser = ET.XMLParser(remove_blank_text=True)\ntree = ET.parse(file_path, parser)\ntree = ChangeDefinition.changedefinition(tree)\nroot = tree.getroot()\nfor element in root:\n if element.tag == '{http://jboss.org/schema/seam/components}component':\n if element.g... | <|body_start_0|>
cls.componentsFilePath.append(file_path)
parser = ET.XMLParser(remove_blank_text=True)
tree = ET.parse(file_path, parser)
tree = ChangeDefinition.changedefinition(tree)
root = tree.getroot()
for element in root:
if element.tag == '{http://jbos... | component.xml migration | ComponentsMigration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComponentsMigration:
"""component.xml migration"""
def parse_xml(cls, file_path):
"""parse the xml change core init tag"""
<|body_0|>
def add_components(cls, project_path):
"""build and deploy project and give the log to Search4Ejb"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_068518 | 2,671 | no_license | [
{
"docstring": "parse the xml change core init tag",
"name": "parse_xml",
"signature": "def parse_xml(cls, file_path)"
},
{
"docstring": "build and deploy project and give the log to Search4Ejb",
"name": "add_components",
"signature": "def add_components(cls, project_path)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024426 | Implement the Python class `ComponentsMigration` described below.
Class description:
component.xml migration
Method signatures and docstrings:
- def parse_xml(cls, file_path): parse the xml change core init tag
- def add_components(cls, project_path): build and deploy project and give the log to Search4Ejb | Implement the Python class `ComponentsMigration` described below.
Class description:
component.xml migration
Method signatures and docstrings:
- def parse_xml(cls, file_path): parse the xml change core init tag
- def add_components(cls, project_path): build and deploy project and give the log to Search4Ejb
<|skeleto... | f7de5a8ea6704402c82cb156b6a26ccf803caa05 | <|skeleton|>
class ComponentsMigration:
"""component.xml migration"""
def parse_xml(cls, file_path):
"""parse the xml change core init tag"""
<|body_0|>
def add_components(cls, project_path):
"""build and deploy project and give the log to Search4Ejb"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComponentsMigration:
"""component.xml migration"""
def parse_xml(cls, file_path):
"""parse the xml change core init tag"""
cls.componentsFilePath.append(file_path)
parser = ET.XMLParser(remove_blank_text=True)
tree = ET.parse(file_path, parser)
tree = ChangeDefinit... | the_stack_v2_python_sparse | migration/components/action/script_component.py | yassinekarim/Script | train | 0 |
bb976bf58a7164c41d78134633e883e8b8bc9bf1 | [
"value = {'fw_version': fw_version, 'on_schedule': on_time}\nid = self.client.api.create_changeset(JOB_FOTA_NAME, value, devices)\nreturn id",
"status = self.client.api.get_current_device_status(device_id)\nmstatus = [self.prepare_model(s) for s in status]\nfor s in mstatus:\n if s.name == JOB_FOTA_NAME:\n ... | <|body_start_0|>
value = {'fw_version': fw_version, 'on_schedule': on_time}
id = self.client.api.create_changeset(JOB_FOTA_NAME, value, devices)
return id
<|end_body_0|>
<|body_start_1|>
status = self.client.api.get_current_device_status(device_id)
mstatus = [self.prepare_model(... | FotaCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FotaCollection:
def schedule(self, fw_version, devices, on_time=''):
"""Schedule a FOTA. Args: fw_version (str): Firmware version. devices (list of str): Targets devices. on_time (datetime): When to schedule the fota. Returns: A :py:class:`FotaModel` object. Raises: :py:class:`adm.errors... | stack_v2_sparse_classes_75kplus_train_068519 | 2,177 | no_license | [
{
"docstring": "Schedule a FOTA. Args: fw_version (str): Firmware version. devices (list of str): Targets devices. on_time (datetime): When to schedule the fota. Returns: A :py:class:`FotaModel` object. Raises: :py:class:`adm.errors.APIError` If the server returns an error.",
"name": "schedule",
"signat... | 3 | stack_v2_sparse_classes_30k_train_048265 | Implement the Python class `FotaCollection` described below.
Class description:
Implement the FotaCollection class.
Method signatures and docstrings:
- def schedule(self, fw_version, devices, on_time=''): Schedule a FOTA. Args: fw_version (str): Firmware version. devices (list of str): Targets devices. on_time (datet... | Implement the Python class `FotaCollection` described below.
Class description:
Implement the FotaCollection class.
Method signatures and docstrings:
- def schedule(self, fw_version, devices, on_time=''): Schedule a FOTA. Args: fw_version (str): Firmware version. devices (list of str): Targets devices. on_time (datet... | d27b0d6ee47b9c4f320f518705074f1032fedf8a | <|skeleton|>
class FotaCollection:
def schedule(self, fw_version, devices, on_time=''):
"""Schedule a FOTA. Args: fw_version (str): Firmware version. devices (list of str): Targets devices. on_time (datetime): When to schedule the fota. Returns: A :py:class:`FotaModel` object. Raises: :py:class:`adm.errors... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FotaCollection:
def schedule(self, fw_version, devices, on_time=''):
"""Schedule a FOTA. Args: fw_version (str): Firmware version. devices (list of str): Targets devices. on_time (datetime): When to schedule the fota. Returns: A :py:class:`FotaModel` object. Raises: :py:class:`adm.errors.APIError` If ... | the_stack_v2_python_sparse | zdevicemanager/client/models/fota.py | zerynth/core-zerynth-toolchain | train | 0 | |
06cea535324be19810f4eeecc9d3704458e4ebb9 | [
"sentences = get_raw_sentences_from_payload(req)\nmethod = req.params.get('method', 'union')\nlimit = int(req.params.get('limit', '10'))\nsentence_encoder = self.sentence_encoder\ncorpus_index = self.corpus_index\ndb_session = self.db_session\ntry:\n resp.status = falcon.HTTP_200\n resp.media = self.similar_k... | <|body_start_0|>
sentences = get_raw_sentences_from_payload(req)
method = req.params.get('method', 'union')
limit = int(req.params.get('limit', '10'))
sentence_encoder = self.sentence_encoder
corpus_index = self.corpus_index
db_session = self.db_session
try:
... | Corpus Semantic Search. { 'results': [ { 'dist': 0.7293307781219482, 'id': 2021055, 'label': ['business_commentary_neg'], 'nearest': -388907830, 'text': 'However, if you were to exclude the Hilton ' 'Waikoloa Village resort, which was negatively ' 'impacted by Hurricane Lane and the Klauea ' 'volcano eruption, RevPAR p... | CovidSimilarityResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CovidSimilarityResource:
"""Corpus Semantic Search. { 'results': [ { 'dist': 0.7293307781219482, 'id': 2021055, 'label': ['business_commentary_neg'], 'nearest': -388907830, 'text': 'However, if you were to exclude the Hilton ' 'Waikoloa Village resort, which was negatively ' 'impacted by Hurrican... | stack_v2_sparse_classes_75kplus_train_068520 | 9,348 | permissive | [
{
"docstring": "Handle POST request.",
"name": "on_post",
"signature": "def on_post(self, req, resp)"
},
{
"docstring": "Find similar sentences. Args: input_sentences (str/list[str]): one or more input sentences. sentence_encoder : encoder limit (int): limit result set size to ``limit``. corpus_... | 2 | stack_v2_sparse_classes_30k_val_000618 | Implement the Python class `CovidSimilarityResource` described below.
Class description:
Corpus Semantic Search. { 'results': [ { 'dist': 0.7293307781219482, 'id': 2021055, 'label': ['business_commentary_neg'], 'nearest': -388907830, 'text': 'However, if you were to exclude the Hilton ' 'Waikoloa Village resort, which... | Implement the Python class `CovidSimilarityResource` described below.
Class description:
Corpus Semantic Search. { 'results': [ { 'dist': 0.7293307781219482, 'id': 2021055, 'label': ['business_commentary_neg'], 'nearest': -388907830, 'text': 'However, if you were to exclude the Hilton ' 'Waikoloa Village resort, which... | b917bcfebc0f81fd3ba0207b09809ecd07fa9016 | <|skeleton|>
class CovidSimilarityResource:
"""Corpus Semantic Search. { 'results': [ { 'dist': 0.7293307781219482, 'id': 2021055, 'label': ['business_commentary_neg'], 'nearest': -388907830, 'text': 'However, if you were to exclude the Hilton ' 'Waikoloa Village resort, which was negatively ' 'impacted by Hurrican... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CovidSimilarityResource:
"""Corpus Semantic Search. { 'results': [ { 'dist': 0.7293307781219482, 'id': 2021055, 'label': ['business_commentary_neg'], 'nearest': -388907830, 'text': 'However, if you were to exclude the Hilton ' 'Waikoloa Village resort, which was negatively ' 'impacted by Hurricane Lane and th... | the_stack_v2_python_sparse | src/resources/similarity.py | sarahJune1/covid19 | train | 0 |
16c58f3166cf8f5e6f19fe0d6fafcf27d3e534d0 | [
"for feature_arch in feature_nets.NAMES:\n sub_test = trySubTest(self, feature_arch=feature_arch)\n with sub_test:\n feature_fn = feature_nets.BY_NAME[feature_arch]\n with tf.Graph().as_default():\n image = tf.placeholder(tf.float32, (None, None, None, 32), name='image')\n ... | <|body_start_0|>
for feature_arch in feature_nets.NAMES:
sub_test = trySubTest(self, feature_arch=feature_arch)
with sub_test:
feature_fn = feature_nets.BY_NAME[feature_arch]
with tf.Graph().as_default():
image = tf.placeholder(tf.float... | TestFeatureNets | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFeatureNets:
def test_unknown_size(self):
"""Instantiates the network with unknown spatial dimensions."""
<|body_0|>
def test_desired_output_size_from_receptive_field(self):
"""Uses the receptive field to get the input size for desired output size."""
<|b... | stack_v2_sparse_classes_75kplus_train_068521 | 7,655 | no_license | [
{
"docstring": "Instantiates the network with unknown spatial dimensions.",
"name": "test_unknown_size",
"signature": "def test_unknown_size(self)"
},
{
"docstring": "Uses the receptive field to get the input size for desired output size.",
"name": "test_desired_output_size_from_receptive_fi... | 5 | stack_v2_sparse_classes_30k_train_011825 | Implement the Python class `TestFeatureNets` described below.
Class description:
Implement the TestFeatureNets class.
Method signatures and docstrings:
- def test_unknown_size(self): Instantiates the network with unknown spatial dimensions.
- def test_desired_output_size_from_receptive_field(self): Uses the receptive... | Implement the Python class `TestFeatureNets` described below.
Class description:
Implement the TestFeatureNets class.
Method signatures and docstrings:
- def test_unknown_size(self): Instantiates the network with unknown spatial dimensions.
- def test_desired_output_size_from_receptive_field(self): Uses the receptive... | 6e0c70647aa58581ed749a79bfa75baca5754ac0 | <|skeleton|>
class TestFeatureNets:
def test_unknown_size(self):
"""Instantiates the network with unknown spatial dimensions."""
<|body_0|>
def test_desired_output_size_from_receptive_field(self):
"""Uses the receptive field to get the input size for desired output size."""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestFeatureNets:
def test_unknown_size(self):
"""Instantiates the network with unknown spatial dimensions."""
for feature_arch in feature_nets.NAMES:
sub_test = trySubTest(self, feature_arch=feature_arch)
with sub_test:
feature_fn = feature_nets.BY_NAME[... | the_stack_v2_python_sparse | python/seqtrack/models/test_feature_nets.py | torrvision/seqtrack | train | 1 | |
48362a21ec5120d0cc3ce65915d39dd9d28fa82d | [
"Movable.__init__(self, canvas, cx, cy, 0.0, colorstr)\nself.pixelradius = int(pixelradius)\nself.localCoords = [(0, 0)]\nself.updateGlobalCoords()\nself.createObjects()",
"p = list(map(self.canvas.tfm.transform, self.globalCoords))\nr = self.pixelradius\nself.canvas.coords(self.itemid, p[0][0] - r, p[0][1] - r, ... | <|body_start_0|>
Movable.__init__(self, canvas, cx, cy, 0.0, colorstr)
self.pixelradius = int(pixelradius)
self.localCoords = [(0, 0)]
self.updateGlobalCoords()
self.createObjects()
<|end_body_0|>
<|body_start_1|>
p = list(map(self.canvas.tfm.transform, self.globalCoords... | MovablePoint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovablePoint:
def __init__(self, canvas, cx=0.0, cy=0.0, colorstr='black', pixelradius=2):
"""the MovablePoint constructor"""
<|body_0|>
def updatePixelCoords(self):
"""redraws the object it represents on the canvas"""
<|body_1|>
def createObjects(self):... | stack_v2_sparse_classes_75kplus_train_068522 | 40,655 | no_license | [
{
"docstring": "the MovablePoint constructor",
"name": "__init__",
"signature": "def __init__(self, canvas, cx=0.0, cy=0.0, colorstr='black', pixelradius=2)"
},
{
"docstring": "redraws the object it represents on the canvas",
"name": "updatePixelCoords",
"signature": "def updatePixelCoor... | 3 | stack_v2_sparse_classes_30k_val_000688 | Implement the Python class `MovablePoint` described below.
Class description:
Implement the MovablePoint class.
Method signatures and docstrings:
- def __init__(self, canvas, cx=0.0, cy=0.0, colorstr='black', pixelradius=2): the MovablePoint constructor
- def updatePixelCoords(self): redraws the object it represents ... | Implement the Python class `MovablePoint` described below.
Class description:
Implement the MovablePoint class.
Method signatures and docstrings:
- def __init__(self, canvas, cx=0.0, cy=0.0, colorstr='black', pixelradius=2): the MovablePoint constructor
- def updatePixelCoords(self): redraws the object it represents ... | eced0cc854c7165f688ce55b573331492b370e7e | <|skeleton|>
class MovablePoint:
def __init__(self, canvas, cx=0.0, cy=0.0, colorstr='black', pixelradius=2):
"""the MovablePoint constructor"""
<|body_0|>
def updatePixelCoords(self):
"""redraws the object it represents on the canvas"""
<|body_1|>
def createObjects(self):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovablePoint:
def __init__(self, canvas, cx=0.0, cy=0.0, colorstr='black', pixelradius=2):
"""the MovablePoint constructor"""
Movable.__init__(self, canvas, cx, cy, 0.0, colorstr)
self.pixelradius = int(pixelradius)
self.localCoords = [(0, 0)]
self.updateGlobalCoords()
... | the_stack_v2_python_sparse | Robotics/RobotCanvas.py | divir94/Python-Projects | train | 0 | |
7e7eb86610c4a74bff9a5b54f128fdd1eccff4ea | [
"super(ModelTableAlbumsABS, self).__init__(parent, self.A_COLNAME, *args)\nself.parent = parent\nself.SortFilterProxy = ProxyModelAlbums(self)\nself.SortFilterProxy.setDynamicSortFilter(True)\nself.SortFilterProxy.setSourceModel(self)",
"if not index.isValid():\n return QVariant()\nelif role == Qt.TextColorRol... | <|body_start_0|>
super(ModelTableAlbumsABS, self).__init__(parent, self.A_COLNAME, *args)
self.parent = parent
self.SortFilterProxy = ProxyModelAlbums(self)
self.SortFilterProxy.setDynamicSortFilter(True)
self.SortFilterProxy.setSourceModel(self)
<|end_body_0|>
<|body_start_1|>
... | ModelTableAlbumsABS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelTableAlbumsABS:
def __init__(self, parent, *args):
"""Init model."""
<|body_0|>
def data(self, index, role=Qt.DisplayRole):
"""Sum and display data."""
<|body_1|>
def builListThunbnails(self, new=True, deb=0, fin=100):
"""Build list Thunbnai... | stack_v2_sparse_classes_75kplus_train_068523 | 16,594 | no_license | [
{
"docstring": "Init model.",
"name": "__init__",
"signature": "def __init__(self, parent, *args)"
},
{
"docstring": "Sum and display data.",
"name": "data",
"signature": "def data(self, index, role=Qt.DisplayRole)"
},
{
"docstring": "Build list Thunbnails",
"name": "builList... | 4 | stack_v2_sparse_classes_30k_train_035190 | Implement the Python class `ModelTableAlbumsABS` described below.
Class description:
Implement the ModelTableAlbumsABS class.
Method signatures and docstrings:
- def __init__(self, parent, *args): Init model.
- def data(self, index, role=Qt.DisplayRole): Sum and display data.
- def builListThunbnails(self, new=True, ... | Implement the Python class `ModelTableAlbumsABS` described below.
Class description:
Implement the ModelTableAlbumsABS class.
Method signatures and docstrings:
- def __init__(self, parent, *args): Init model.
- def data(self, index, role=Qt.DisplayRole): Sum and display data.
- def builListThunbnails(self, new=True, ... | b8d5cbc2a7a323824a21b5155d2466fb3e3cbe54 | <|skeleton|>
class ModelTableAlbumsABS:
def __init__(self, parent, *args):
"""Init model."""
<|body_0|>
def data(self, index, role=Qt.DisplayRole):
"""Sum and display data."""
<|body_1|>
def builListThunbnails(self, new=True, deb=0, fin=100):
"""Build list Thunbnai... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelTableAlbumsABS:
def __init__(self, parent, *args):
"""Init model."""
super(ModelTableAlbumsABS, self).__init__(parent, self.A_COLNAME, *args)
self.parent = parent
self.SortFilterProxy = ProxyModelAlbums(self)
self.SortFilterProxy.setDynamicSortFilter(True)
... | the_stack_v2_python_sparse | DBModelAbs.py | doubsman/DBAlbums | train | 0 | |
27e9d3687d5f947d09e9ed1c87f109ee57fbbbc7 | [
"l = len(indexes)\na = []\nfor i in range(l):\n a.append([indexes[i], sources[i], targets[i]])\na = sorted(a, key=lambda a: a[0])\nans = ''\nstart = 0\nfor key in a:\n ans += S[start:key[0]]\n start = key[0]\n longth = len(key[1])\n s = S[start:start + longth]\n if s == key[1]:\n ans += key... | <|body_start_0|>
l = len(indexes)
a = []
for i in range(l):
a.append([indexes[i], sources[i], targets[i]])
a = sorted(a, key=lambda a: a[0])
ans = ''
start = 0
for key in a:
ans += S[start:key[0]]
start = key[0]
long... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findReplaceString(self, S, indexes, sources, targets):
""":type S: str :type indexes: List[int] :type sources: List[str] :type targets: List[str] :rtype: str 36 ms"""
<|body_0|>
def findReplaceString_1(self, S, indexes, sources, targets):
"""40ms :param... | stack_v2_sparse_classes_75kplus_train_068524 | 3,244 | no_license | [
{
"docstring": ":type S: str :type indexes: List[int] :type sources: List[str] :type targets: List[str] :rtype: str 36 ms",
"name": "findReplaceString",
"signature": "def findReplaceString(self, S, indexes, sources, targets)"
},
{
"docstring": "40ms :param S: :param indexes: :param sources: :par... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findReplaceString(self, S, indexes, sources, targets): :type S: str :type indexes: List[int] :type sources: List[str] :type targets: List[str] :rtype: str 36 ms
- def findRep... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findReplaceString(self, S, indexes, sources, targets): :type S: str :type indexes: List[int] :type sources: List[str] :type targets: List[str] :rtype: str 36 ms
- def findRep... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def findReplaceString(self, S, indexes, sources, targets):
""":type S: str :type indexes: List[int] :type sources: List[str] :type targets: List[str] :rtype: str 36 ms"""
<|body_0|>
def findReplaceString_1(self, S, indexes, sources, targets):
"""40ms :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findReplaceString(self, S, indexes, sources, targets):
""":type S: str :type indexes: List[int] :type sources: List[str] :type targets: List[str] :rtype: str 36 ms"""
l = len(indexes)
a = []
for i in range(l):
a.append([indexes[i], sources[i], targets[... | the_stack_v2_python_sparse | FindAndReplaceInString_MID_833.py | 953250587/leetcode-python | train | 2 | |
385c85b30f077e306483865e191bf651e255111a | [
"print('hotmap', hotmap)\nif str(hotmap) == '[1, 2, 3]':\n pass\nelif str(hotmap) == '[1, 3, 2]':\n pass\nelif str(hotmap) == '[2, 1, 3]':\n pass\nelif str(hotmap) == '[3, 1, 2]':\n pass\nelif str(hotmap) == '[3, 2, 1]':\n pass\nelif str(hotmap) == '[2, 3, 1]':\n pass\nelif str(hotmap) == '[2, 1, ... | <|body_start_0|>
print('hotmap', hotmap)
if str(hotmap) == '[1, 2, 3]':
pass
elif str(hotmap) == '[1, 3, 2]':
pass
elif str(hotmap) == '[2, 1, 3]':
pass
elif str(hotmap) == '[3, 1, 2]':
pass
elif str(hotmap) == '[3, 2, 1]':
... | DisclosureGadgetMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisclosureGadgetMixin:
def decide_disclosure_landing_site(self, prologue_signature, hotmap, sub_gadget_entry):
"""TODO: heurisitic to decide disclosure landing site, would be useful to speed up the osok :param prologue_signature: :param hotmap: :param sub_gadget_entry: :return:"""
... | stack_v2_sparse_classes_75kplus_train_068525 | 4,057 | permissive | [
{
"docstring": "TODO: heurisitic to decide disclosure landing site, would be useful to speed up the osok :param prologue_signature: :param hotmap: :param sub_gadget_entry: :return:",
"name": "decide_disclosure_landing_site",
"signature": "def decide_disclosure_landing_site(self, prologue_signature, hotm... | 3 | stack_v2_sparse_classes_30k_train_050867 | Implement the Python class `DisclosureGadgetMixin` described below.
Class description:
Implement the DisclosureGadgetMixin class.
Method signatures and docstrings:
- def decide_disclosure_landing_site(self, prologue_signature, hotmap, sub_gadget_entry): TODO: heurisitic to decide disclosure landing site, would be use... | Implement the Python class `DisclosureGadgetMixin` described below.
Class description:
Implement the DisclosureGadgetMixin class.
Method signatures and docstrings:
- def decide_disclosure_landing_site(self, prologue_signature, hotmap, sub_gadget_entry): TODO: heurisitic to decide disclosure landing site, would be use... | e530583fa96a99c53a043f6fd5cd67c63509731d | <|skeleton|>
class DisclosureGadgetMixin:
def decide_disclosure_landing_site(self, prologue_signature, hotmap, sub_gadget_entry):
"""TODO: heurisitic to decide disclosure landing site, would be useful to speed up the osok :param prologue_signature: :param hotmap: :param sub_gadget_entry: :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DisclosureGadgetMixin:
def decide_disclosure_landing_site(self, prologue_signature, hotmap, sub_gadget_entry):
"""TODO: heurisitic to decide disclosure landing site, would be useful to speed up the osok :param prologue_signature: :param hotmap: :param sub_gadget_entry: :return:"""
print('hotma... | the_stack_v2_python_sparse | src/osok/osok/_disclosure_gadget.py | yifengchen-cc/kepler-cfhp | train | 0 | |
2ed8f673cb00541414cc276099fbf36196ddae00 | [
"self._feature_columns = tuple(feature_columns or [])\nassert self._feature_columns\nchief_hook = None\nif isinstance(optimizer, sdca_optimizer.SDCAOptimizer) and enable_centered_bias:\n enable_centered_bias = False\n logging.warning('centered_bias is not supported with SDCA, please disable it explicitly.')\n... | <|body_start_0|>
self._feature_columns = tuple(feature_columns or [])
assert self._feature_columns
chief_hook = None
if isinstance(optimizer, sdca_optimizer.SDCAOptimizer) and enable_centered_bias:
enable_centered_bias = False
logging.warning('centered_bias is not... | Linear regressor model. Train a linear regression model to predict label value given observation of feature values. Example: ```python sparse_column_a = sparse_column_with_hash_bucket(...) sparse_column_b = sparse_column_with_hash_bucket(...) sparse_feature_a_x_sparse_feature_b = crossed_column(...) estimator = LinearR... | LinearRegressor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearRegressor:
"""Linear regressor model. Train a linear regression model to predict label value given observation of feature values. Example: ```python sparse_column_a = sparse_column_with_hash_bucket(...) sparse_column_b = sparse_column_with_hash_bucket(...) sparse_feature_a_x_sparse_feature_... | stack_v2_sparse_classes_75kplus_train_068526 | 38,403 | permissive | [
{
"docstring": "Construct a `LinearRegressor` estimator object. Args: feature_columns: An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `FeatureColumn`. model_dir: Directory to save model parameters, graph, etc. This can also be u... | 4 | stack_v2_sparse_classes_30k_test_000579 | Implement the Python class `LinearRegressor` described below.
Class description:
Linear regressor model. Train a linear regression model to predict label value given observation of feature values. Example: ```python sparse_column_a = sparse_column_with_hash_bucket(...) sparse_column_b = sparse_column_with_hash_bucket(... | Implement the Python class `LinearRegressor` described below.
Class description:
Linear regressor model. Train a linear regression model to predict label value given observation of feature values. Example: ```python sparse_column_a = sparse_column_with_hash_bucket(...) sparse_column_b = sparse_column_with_hash_bucket(... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class LinearRegressor:
"""Linear regressor model. Train a linear regression model to predict label value given observation of feature values. Example: ```python sparse_column_a = sparse_column_with_hash_bucket(...) sparse_column_b = sparse_column_with_hash_bucket(...) sparse_feature_a_x_sparse_feature_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinearRegressor:
"""Linear regressor model. Train a linear regression model to predict label value given observation of feature values. Example: ```python sparse_column_a = sparse_column_with_hash_bucket(...) sparse_column_b = sparse_column_with_hash_bucket(...) sparse_feature_a_x_sparse_feature_b = crossed_c... | the_stack_v2_python_sparse | Tensorflow_OpenCV_Nightly/source/tensorflow/contrib/learn/python/learn/estimators/linear.py | ryfeus/lambda-packs | train | 1,283 |
b64230374fdfce31d865f7b4cd7f4174290aa56f | [
"super(ManualTrader, self).__init__(parent)\nself.omEngine = omEngine\nself.mainEngine = omEngine.mainEngine\nself.eventEngine = omEngine.eventEngine\nself.initUi()",
"self.setWindowTitle(u'手动交易')\nposMonitor = PositionMonitor(self.mainEngine, self.eventEngine)\nfor i in range(posMonitor.columnCount()):\n posM... | <|body_start_0|>
super(ManualTrader, self).__init__(parent)
self.omEngine = omEngine
self.mainEngine = omEngine.mainEngine
self.eventEngine = omEngine.eventEngine
self.initUi()
<|end_body_0|>
<|body_start_1|>
self.setWindowTitle(u'手动交易')
posMonitor = PositionMoni... | 手动交易组件 | ManualTrader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManualTrader:
"""手动交易组件"""
def __init__(self, omEngine, parent=None):
"""Constructor"""
<|body_0|>
def initUi(self):
"""初始化界面"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ManualTrader, self).__init__(parent)
self.omEngine = omEn... | stack_v2_sparse_classes_75kplus_train_068527 | 16,989 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, omEngine, parent=None)"
},
{
"docstring": "初始化界面",
"name": "initUi",
"signature": "def initUi(self)"
}
] | 2 | null | Implement the Python class `ManualTrader` described below.
Class description:
手动交易组件
Method signatures and docstrings:
- def __init__(self, omEngine, parent=None): Constructor
- def initUi(self): 初始化界面 | Implement the Python class `ManualTrader` described below.
Class description:
手动交易组件
Method signatures and docstrings:
- def __init__(self, omEngine, parent=None): Constructor
- def initUi(self): 初始化界面
<|skeleton|>
class ManualTrader:
"""手动交易组件"""
def __init__(self, omEngine, parent=None):
"""Constr... | 75f95a00e7eb569cb7cc530ea55d6646ba4595c1 | <|skeleton|>
class ManualTrader:
"""手动交易组件"""
def __init__(self, omEngine, parent=None):
"""Constructor"""
<|body_0|>
def initUi(self):
"""初始化界面"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ManualTrader:
"""手动交易组件"""
def __init__(self, omEngine, parent=None):
"""Constructor"""
super(ManualTrader, self).__init__(parent)
self.omEngine = omEngine
self.mainEngine = omEngine.mainEngine
self.eventEngine = omEngine.eventEngine
self.initUi()
def ... | the_stack_v2_python_sparse | vnpy/trader/app/optionMaster/uiOmManualTrader.py | KilimanjaroFreeman/vnpy | train | 3 |
04d8ddf0fb90a186a39de039f5e10f424d4a3140 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn WorkbookChart()",
"from .entity import Entity\nfrom .workbook_chart_area_format import WorkbookChartAreaFormat\nfrom .workbook_chart_axes import WorkbookChartAxes\nfrom .workbook_chart_data_labels import WorkbookChartDataLabels\nfrom .... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return WorkbookChart()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .workbook_chart_area_format import WorkbookChartAreaFormat
from .workbook_chart_axes import Workbo... | WorkbookChart | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkbookChart:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookChart:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_75kplus_train_068528 | 6,269 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: WorkbookChart",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | stack_v2_sparse_classes_30k_train_026197 | Implement the Python class `WorkbookChart` described below.
Class description:
Implement the WorkbookChart class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookChart: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `WorkbookChart` described below.
Class description:
Implement the WorkbookChart class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookChart: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class WorkbookChart:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookChart:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkbookChart:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookChart:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: WorkbookChar... | the_stack_v2_python_sparse | msgraph/generated/models/workbook_chart.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
ccdee3933fb98956da71b90e2392e83f52566f1e | [
"if isinstance(parameterRule, (basestring, unicode)):\n self.__parameterRules = json.loads(parameterRule)\nelse:\n self.__parameterRules = parameterRule",
"if isinstance(f, basestring):\n f = codecs.open(f, 'r', 'utf-8')\nparameters = json.load(f)\nfor paramName, rule in self.__parameterRules.iteritems()... | <|body_start_0|>
if isinstance(parameterRule, (basestring, unicode)):
self.__parameterRules = json.loads(parameterRule)
else:
self.__parameterRules = parameterRule
<|end_body_0|>
<|body_start_1|>
if isinstance(f, basestring):
f = codecs.open(f, 'r', 'utf-8')
... | JsonArgParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonArgParser:
def __init__(self, parameterRule):
""":type parameterRule: basestring :param parameterRule: Its a json string which contains description and default values of some parameters. Besides that, it's possible specific if a parameter is required or not. If nothing is stipulate, ... | stack_v2_sparse_classes_75kplus_train_068529 | 1,980 | no_license | [
{
"docstring": ":type parameterRule: basestring :param parameterRule: Its a json string which contains description and default values of some parameters. Besides that, it's possible specific if a parameter is required or not. If nothing is stipulate, so the parameter will be consider not required. Below is show... | 2 | null | Implement the Python class `JsonArgParser` described below.
Class description:
Implement the JsonArgParser class.
Method signatures and docstrings:
- def __init__(self, parameterRule): :type parameterRule: basestring :param parameterRule: Its a json string which contains description and default values of some paramet... | Implement the Python class `JsonArgParser` described below.
Class description:
Implement the JsonArgParser class.
Method signatures and docstrings:
- def __init__(self, parameterRule): :type parameterRule: basestring :param parameterRule: Its a json string which contains description and default values of some paramet... | c2b6d502790fb1b15eee41b32636bd0a55ab3de2 | <|skeleton|>
class JsonArgParser:
def __init__(self, parameterRule):
""":type parameterRule: basestring :param parameterRule: Its a json string which contains description and default values of some parameters. Besides that, it's possible specific if a parameter is required or not. If nothing is stipulate, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JsonArgParser:
def __init__(self, parameterRule):
""":type parameterRule: basestring :param parameterRule: Its a json string which contains description and default values of some parameters. Besides that, it's possible specific if a parameter is required or not. If nothing is stipulate, so the paramet... | the_stack_v2_python_sparse | args/JsonArgParser.py | eraldoluis/lia-pln-deeplearning | train | 5 | |
ba38a2f65c3802efcbda9d5b727ca3b97add63bf | [
"super(CrossValidationJointFusionWorkflow, self).__init__(name=name, **kwargs)\nself.csv_file = File(value=os.path.abspath(csv_file), exists=True)\nself.hasHeader = traits.Bool(hasHeader)\nself.sample_size = traits.Int(size)\nself.config['execution'] = {'remove_unnecessary_outputs': 'true'}",
"csvReader = CSVRead... | <|body_start_0|>
super(CrossValidationJointFusionWorkflow, self).__init__(name=name, **kwargs)
self.csv_file = File(value=os.path.abspath(csv_file), exists=True)
self.hasHeader = traits.Bool(hasHeader)
self.sample_size = traits.Int(size)
self.config['execution'] = {'remove_unnece... | Nipype workflow for Multi-Label Atlas Fusion cross-validation experiment :param Workflow: | CrossValidationJointFusionWorkflow | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossValidationJointFusionWorkflow:
"""Nipype workflow for Multi-Label Atlas Fusion cross-validation experiment :param Workflow:"""
def __init__(self, csv_file=None, size=0, hasHeader=False, name='CrossValidationJointFusionWorkflow', **kwargs):
"""This function... :param self: :param... | stack_v2_sparse_classes_75kplus_train_068530 | 18,518 | permissive | [
{
"docstring": "This function... :param self: :param csv_file: :param size: :param hasHeader: :param name: :param **kwargs: :return:",
"name": "__init__",
"signature": "def __init__(self, csv_file=None, size=0, hasHeader=False, name='CrossValidationJointFusionWorkflow', **kwargs)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_048163 | Implement the Python class `CrossValidationJointFusionWorkflow` described below.
Class description:
Nipype workflow for Multi-Label Atlas Fusion cross-validation experiment :param Workflow:
Method signatures and docstrings:
- def __init__(self, csv_file=None, size=0, hasHeader=False, name='CrossValidationJointFusionW... | Implement the Python class `CrossValidationJointFusionWorkflow` described below.
Class description:
Nipype workflow for Multi-Label Atlas Fusion cross-validation experiment :param Workflow:
Method signatures and docstrings:
- def __init__(self, csv_file=None, size=0, hasHeader=False, name='CrossValidationJointFusionW... | 64bb590918a188b660225e44ae54c1072f3a8056 | <|skeleton|>
class CrossValidationJointFusionWorkflow:
"""Nipype workflow for Multi-Label Atlas Fusion cross-validation experiment :param Workflow:"""
def __init__(self, csv_file=None, size=0, hasHeader=False, name='CrossValidationJointFusionWorkflow', **kwargs):
"""This function... :param self: :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CrossValidationJointFusionWorkflow:
"""Nipype workflow for Multi-Label Atlas Fusion cross-validation experiment :param Workflow:"""
def __init__(self, csv_file=None, size=0, hasHeader=False, name='CrossValidationJointFusionWorkflow', **kwargs):
"""This function... :param self: :param csv_file: :p... | the_stack_v2_python_sparse | AutoWorkup/BAW/workflows/crossValidate.py | BRAINSia/BRAINSTools | train | 101 |
114be6a63b7532b7a4dd36acd74b34a8c05c3549 | [
"assert len(master_key) in AES.rounds_by_key_size\nself.n_rounds = AES.rounds_by_key_size[len(master_key)]\nself._key_matrices = self._expand_key(master_key)",
"key_columns = bytes2matrix(master_key)\niteration_size = len(master_key) // 4\ni = 1\nwhile len(key_columns) < (self.n_rounds + 1) * 4:\n word = list(... | <|body_start_0|>
assert len(master_key) in AES.rounds_by_key_size
self.n_rounds = AES.rounds_by_key_size[len(master_key)]
self._key_matrices = self._expand_key(master_key)
<|end_body_0|>
<|body_start_1|>
key_columns = bytes2matrix(master_key)
iteration_size = len(master_key) // ... | AES | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AES:
def __init__(self, master_key):
"""Initializes the object with a given key."""
<|body_0|>
def _expand_key(self, master_key):
"""Expands and returns a list of key matrices for the given master_key."""
<|body_1|>
def encrypt_block(self, plaintext):
... | stack_v2_sparse_classes_75kplus_train_068531 | 4,275 | permissive | [
{
"docstring": "Initializes the object with a given key.",
"name": "__init__",
"signature": "def __init__(self, master_key)"
},
{
"docstring": "Expands and returns a list of key matrices for the given master_key.",
"name": "_expand_key",
"signature": "def _expand_key(self, master_key)"
... | 3 | stack_v2_sparse_classes_30k_train_012597 | Implement the Python class `AES` described below.
Class description:
Implement the AES class.
Method signatures and docstrings:
- def __init__(self, master_key): Initializes the object with a given key.
- def _expand_key(self, master_key): Expands and returns a list of key matrices for the given master_key.
- def enc... | Implement the Python class `AES` described below.
Class description:
Implement the AES class.
Method signatures and docstrings:
- def __init__(self, master_key): Initializes the object with a given key.
- def _expand_key(self, master_key): Expands and returns a list of key matrices for the given master_key.
- def enc... | cda0db4888322cce759a7362de88fff5cc79f599 | <|skeleton|>
class AES:
def __init__(self, master_key):
"""Initializes the object with a given key."""
<|body_0|>
def _expand_key(self, master_key):
"""Expands and returns a list of key matrices for the given master_key."""
<|body_1|>
def encrypt_block(self, plaintext):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AES:
def __init__(self, master_key):
"""Initializes the object with a given key."""
assert len(master_key) in AES.rounds_by_key_size
self.n_rounds = AES.rounds_by_key_size[len(master_key)]
self._key_matrices = self._expand_key(master_key)
def _expand_key(self, master_key):... | the_stack_v2_python_sparse | Codegate/2022 Finals/aesmaster/aes.py | Qwaz/solved-hacking-problem | train | 100 | |
c5f5c59398d604fa682f78c658934329c6d45927 | [
"super().__init__()\nself._fixed_length_left = fixed_length_left\nself._fixed_length_right = fixed_length_right\nself._left_fixedlength_unit = units.FixedLength(self._fixed_length_left, pad_mode='post')\nself._right_fixedlength_unit = units.FixedLength(self._fixed_length_right, pad_mode='post')\nself._filter_unit =... | <|body_start_0|>
super().__init__()
self._fixed_length_left = fixed_length_left
self._fixed_length_right = fixed_length_right
self._left_fixedlength_unit = units.FixedLength(self._fixed_length_left, pad_mode='post')
self._right_fixedlength_unit = units.FixedLength(self._fixed_len... | Baisc preprocessor helper. :param fixed_length_left: Integer, maximize length of :attr:`left` in the data_pack. :param fixed_length_right: Integer, maximize length of :attr:`right` in the data_pack. :param filter_mode: String, mode used by :class:`FrequenceFilterUnit`, Can be 'df', 'cf', and 'idf'. :param filter_low_fr... | BasicPreprocessor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicPreprocessor:
"""Baisc preprocessor helper. :param fixed_length_left: Integer, maximize length of :attr:`left` in the data_pack. :param fixed_length_right: Integer, maximize length of :attr:`right` in the data_pack. :param filter_mode: String, mode used by :class:`FrequenceFilterUnit`, Can b... | stack_v2_sparse_classes_75kplus_train_068532 | 6,226 | permissive | [
{
"docstring": "Initialization.",
"name": "__init__",
"signature": "def __init__(self, fixed_length_left: int=30, fixed_length_right: int=30, filter_mode: str='df', filter_low_freq: float=2, filter_high_freq: float=float('inf'), remove_stop_words: bool=False)"
},
{
"docstring": "Fit pre-processi... | 3 | stack_v2_sparse_classes_30k_train_047060 | Implement the Python class `BasicPreprocessor` described below.
Class description:
Baisc preprocessor helper. :param fixed_length_left: Integer, maximize length of :attr:`left` in the data_pack. :param fixed_length_right: Integer, maximize length of :attr:`right` in the data_pack. :param filter_mode: String, mode used... | Implement the Python class `BasicPreprocessor` described below.
Class description:
Baisc preprocessor helper. :param fixed_length_left: Integer, maximize length of :attr:`left` in the data_pack. :param fixed_length_right: Integer, maximize length of :attr:`right` in the data_pack. :param filter_mode: String, mode used... | db101beed691a0e399f9b0b19fb59c7dc8b16760 | <|skeleton|>
class BasicPreprocessor:
"""Baisc preprocessor helper. :param fixed_length_left: Integer, maximize length of :attr:`left` in the data_pack. :param fixed_length_right: Integer, maximize length of :attr:`right` in the data_pack. :param filter_mode: String, mode used by :class:`FrequenceFilterUnit`, Can b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicPreprocessor:
"""Baisc preprocessor helper. :param fixed_length_left: Integer, maximize length of :attr:`left` in the data_pack. :param fixed_length_right: Integer, maximize length of :attr:`right` in the data_pack. :param filter_mode: String, mode used by :class:`FrequenceFilterUnit`, Can be 'df', 'cf',... | the_stack_v2_python_sparse | matchzoo/preprocessors/basic_preprocessor.py | nguyenvo09/LearningFromFactCheckers | train | 11 |
6281b021f5be795b747541769e3578cadb0e7933 | [
"conf = configparser.ConfigParser()\nconf.read(file_name, encoding='UTF-8')\nself.go = conf.get('EMAIL', 'go')\nself.to = conf.get('EMAIL', 'to')\nself.code = conf.get('EMAIL', 'code')\nself.themo = conf.get('EMAIL', 'theme')\nself.text = conf.get('EMAIL', 'text')",
"msg = MIMEMultipart()\nmsg['Subject'] = self.t... | <|body_start_0|>
conf = configparser.ConfigParser()
conf.read(file_name, encoding='UTF-8')
self.go = conf.get('EMAIL', 'go')
self.to = conf.get('EMAIL', 'to')
self.code = conf.get('EMAIL', 'code')
self.themo = conf.get('EMAIL', 'theme')
self.text = conf.get('EMAIL... | Email | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Email:
def __init__(self, file_name=project_path.email_conf_path):
"""读取配置文件参数 :param file_name:配置文件的路径 :return:"""
<|body_0|>
def email_to(self, fp):
"""发送邮件的参数 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
conf = configparser.ConfigPars... | stack_v2_sparse_classes_75kplus_train_068533 | 2,178 | no_license | [
{
"docstring": "读取配置文件参数 :param file_name:配置文件的路径 :return:",
"name": "__init__",
"signature": "def __init__(self, file_name=project_path.email_conf_path)"
},
{
"docstring": "发送邮件的参数 :return:",
"name": "email_to",
"signature": "def email_to(self, fp)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017208 | Implement the Python class `Email` described below.
Class description:
Implement the Email class.
Method signatures and docstrings:
- def __init__(self, file_name=project_path.email_conf_path): 读取配置文件参数 :param file_name:配置文件的路径 :return:
- def email_to(self, fp): 发送邮件的参数 :return: | Implement the Python class `Email` described below.
Class description:
Implement the Email class.
Method signatures and docstrings:
- def __init__(self, file_name=project_path.email_conf_path): 读取配置文件参数 :param file_name:配置文件的路径 :return:
- def email_to(self, fp): 发送邮件的参数 :return:
<|skeleton|>
class Email:
def __... | c41cc58668f3d6d8d6bd1b6b4119c7daa4fdb595 | <|skeleton|>
class Email:
def __init__(self, file_name=project_path.email_conf_path):
"""读取配置文件参数 :param file_name:配置文件的路径 :return:"""
<|body_0|>
def email_to(self, fp):
"""发送邮件的参数 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Email:
def __init__(self, file_name=project_path.email_conf_path):
"""读取配置文件参数 :param file_name:配置文件的路径 :return:"""
conf = configparser.ConfigParser()
conf.read(file_name, encoding='UTF-8')
self.go = conf.get('EMAIL', 'go')
self.to = conf.get('EMAIL', 'to')
self... | the_stack_v2_python_sparse | api_dm_pytest/Common/to_email.py | yang0422/test | train | 1 | |
33f01f6a41f63f4a22c9c3457d71ed2d44853e5e | [
"super(StopVehicle, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._control = carla.VehicleControl()\nself._actor = actor\nself._brake_value = brake_value\nself._control.steering = 0",
"new_status = py_trees.common.Status.RUNNING\nif CarlaDataProvider.get_velocity(self._a... | <|body_start_0|>
super(StopVehicle, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._control = carla.VehicleControl()
self._actor = actor
self._brake_value = brake_value
self._control.steering = 0
<|end_body_0|>
<|body_start_1|>
... | This class contains an atomic stopping behavior. The controlled traffic participant will decelerate with _bake_value_ until reaching a full stop. | StopVehicle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StopVehicle:
"""This class contains an atomic stopping behavior. The controlled traffic participant will decelerate with _bake_value_ until reaching a full stop."""
def __init__(self, actor, brake_value, name='Stopping'):
"""Setup _actor and maximum braking value"""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_068534 | 25,380 | permissive | [
{
"docstring": "Setup _actor and maximum braking value",
"name": "__init__",
"signature": "def __init__(self, actor, brake_value, name='Stopping')"
},
{
"docstring": "Set brake to brake_value until reaching full stop",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040645 | Implement the Python class `StopVehicle` described below.
Class description:
This class contains an atomic stopping behavior. The controlled traffic participant will decelerate with _bake_value_ until reaching a full stop.
Method signatures and docstrings:
- def __init__(self, actor, brake_value, name='Stopping'): Se... | Implement the Python class `StopVehicle` described below.
Class description:
This class contains an atomic stopping behavior. The controlled traffic participant will decelerate with _bake_value_ until reaching a full stop.
Method signatures and docstrings:
- def __init__(self, actor, brake_value, name='Stopping'): Se... | 1d3e8339f8e60f7bdcaefeff49ec238b1746b047 | <|skeleton|>
class StopVehicle:
"""This class contains an atomic stopping behavior. The controlled traffic participant will decelerate with _bake_value_ until reaching a full stop."""
def __init__(self, actor, brake_value, name='Stopping'):
"""Setup _actor and maximum braking value"""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StopVehicle:
"""This class contains an atomic stopping behavior. The controlled traffic participant will decelerate with _bake_value_ until reaching a full stop."""
def __init__(self, actor, brake_value, name='Stopping'):
"""Setup _actor and maximum braking value"""
super(StopVehicle, sel... | the_stack_v2_python_sparse | srunner/scenariomanager/atomic_scenario_behavior.py | chauvinSimon/scenario_runner | train | 2 |
d94a0e634d12443f1b23772a1a6335742fcc536a | [
"is_logits = True\nlogit = np.array([[1, 2, -3.0], [-1, 1, 0]])\nlabels = np.array([1, 2])\nstat = amia.calculate_statistic(logit, labels, None, is_logits, 'conf with prob')\nnp.testing.assert_allclose(stat, np.array([0.72747516, 0.24472847]))\nstat = amia.calculate_statistic(logit, labels, None, is_logits, 'xe')\n... | <|body_start_0|>
is_logits = True
logit = np.array([[1, 2, -3.0], [-1, 1, 0]])
labels = np.array([1, 2])
stat = amia.calculate_statistic(logit, labels, None, is_logits, 'conf with prob')
np.testing.assert_allclose(stat, np.array([0.72747516, 0.24472847]))
stat = amia.calc... | Test calculate_statistic. | TestCalculateStatistic | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCalculateStatistic:
"""Test calculate_statistic."""
def test_calculate_statistic_logit(self):
"""Test calculate_statistic with input as logit."""
<|body_0|>
def test_calculate_statistic_prob(self):
"""Test calculate_statistic with input as probability vector.... | stack_v2_sparse_classes_75kplus_train_068535 | 11,625 | permissive | [
{
"docstring": "Test calculate_statistic with input as logit.",
"name": "test_calculate_statistic_logit",
"signature": "def test_calculate_statistic_logit(self)"
},
{
"docstring": "Test calculate_statistic with input as probability vector.",
"name": "test_calculate_statistic_prob",
"sign... | 4 | stack_v2_sparse_classes_30k_val_001906 | Implement the Python class `TestCalculateStatistic` described below.
Class description:
Test calculate_statistic.
Method signatures and docstrings:
- def test_calculate_statistic_logit(self): Test calculate_statistic with input as logit.
- def test_calculate_statistic_prob(self): Test calculate_statistic with input a... | Implement the Python class `TestCalculateStatistic` described below.
Class description:
Test calculate_statistic.
Method signatures and docstrings:
- def test_calculate_statistic_logit(self): Test calculate_statistic with input as logit.
- def test_calculate_statistic_prob(self): Test calculate_statistic with input a... | c92610e37aa340932ed2d963813e0890035a22bc | <|skeleton|>
class TestCalculateStatistic:
"""Test calculate_statistic."""
def test_calculate_statistic_logit(self):
"""Test calculate_statistic with input as logit."""
<|body_0|>
def test_calculate_statistic_prob(self):
"""Test calculate_statistic with input as probability vector.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCalculateStatistic:
"""Test calculate_statistic."""
def test_calculate_statistic_logit(self):
"""Test calculate_statistic with input as logit."""
is_logits = True
logit = np.array([[1, 2, -3.0], [-1, 1, 0]])
labels = np.array([1, 2])
stat = amia.calculate_stati... | the_stack_v2_python_sparse | tensorflow_privacy/privacy/privacy_tests/membership_inference_attack/advanced_mia_test.py | tensorflow/privacy | train | 1,881 |
e18d6c4730bd47eca27f26d46fce5b070e19c36e | [
"nimages = self.getNImages(config, base, file_num, logger=logger)\nreq = {'nimages': int}\nignore += ['file_name', 'dir', 'nfiles']\nCheckAllParams(config, ignore=ignore, req=req)\nreturn BuildImages(nimages, base, image_num, obj_num, logger=logger)",
"if 'nimages' not in config and ('image' not in base or 'type'... | <|body_start_0|>
nimages = self.getNImages(config, base, file_num, logger=logger)
req = {'nimages': int}
ignore += ['file_name', 'dir', 'nfiles']
CheckAllParams(config, ignore=ignore, req=req)
return BuildImages(nimages, base, image_num, obj_num, logger=logger)
<|end_body_0|>
<|... | Builder class for constructing and writing MultiFits output types. | MultiFitsBuilder | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiFitsBuilder:
"""Builder class for constructing and writing MultiFits output types."""
def buildImages(self, config, base, file_num, image_num, obj_num, ignore, logger):
"""Build the images Parameters: config: The configuration dict for the output field. base: The base configurat... | stack_v2_sparse_classes_75kplus_train_068536 | 3,475 | permissive | [
{
"docstring": "Build the images Parameters: config: The configuration dict for the output field. base: The base configuration dict. file_num: The current file_num. image_num: The current image_num. obj_num: The current obj_num. ignore: A list of parameters that are allowed to be in config that we can ignore he... | 2 | null | Implement the Python class `MultiFitsBuilder` described below.
Class description:
Builder class for constructing and writing MultiFits output types.
Method signatures and docstrings:
- def buildImages(self, config, base, file_num, image_num, obj_num, ignore, logger): Build the images Parameters: config: The configura... | Implement the Python class `MultiFitsBuilder` described below.
Class description:
Builder class for constructing and writing MultiFits output types.
Method signatures and docstrings:
- def buildImages(self, config, base, file_num, image_num, obj_num, ignore, logger): Build the images Parameters: config: The configura... | f1c0319600cc713373f1cea7459171fbf388848e | <|skeleton|>
class MultiFitsBuilder:
"""Builder class for constructing and writing MultiFits output types."""
def buildImages(self, config, base, file_num, image_num, obj_num, ignore, logger):
"""Build the images Parameters: config: The configuration dict for the output field. base: The base configurat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiFitsBuilder:
"""Builder class for constructing and writing MultiFits output types."""
def buildImages(self, config, base, file_num, image_num, obj_num, ignore, logger):
"""Build the images Parameters: config: The configuration dict for the output field. base: The base configuration dict. fil... | the_stack_v2_python_sparse | galsim/config/output_multifits.py | GalSim-developers/GalSim | train | 194 |
89fda9895a6eca166b978d46ec7ff15cc158b24b | [
"self.shards = shards\nself.id_col = schema['id_col']\nself.dt_col = schema['dt_col']\nself.feature_col = schema['feature_col'].copy()\nself.target_col = schema['target_col'].copy()\nself.numpy_shards = None\nself._id_list = list(shards[self.id_col].unique())",
"_check_type(shards, 'shards', SparkXShards)\ntarget... | <|body_start_0|>
self.shards = shards
self.id_col = schema['id_col']
self.dt_col = schema['dt_col']
self.feature_col = schema['feature_col'].copy()
self.target_col = schema['target_col'].copy()
self.numpy_shards = None
self._id_list = list(shards[self.id_col].uniq... | XShardsTSDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XShardsTSDataset:
def __init__(self, shards, **schema):
"""XShardTSDataset is an abstract of time series dataset with distributed fashion. Cascade call is supported for most of the transform methods. XShardTSDataset will partition the dataset by id_col, which is experimental."""
... | stack_v2_sparse_classes_75kplus_train_068537 | 8,833 | permissive | [
{
"docstring": "XShardTSDataset is an abstract of time series dataset with distributed fashion. Cascade call is supported for most of the transform methods. XShardTSDataset will partition the dataset by id_col, which is experimental.",
"name": "__init__",
"signature": "def __init__(self, shards, **schem... | 4 | stack_v2_sparse_classes_30k_train_039131 | Implement the Python class `XShardsTSDataset` described below.
Class description:
Implement the XShardsTSDataset class.
Method signatures and docstrings:
- def __init__(self, shards, **schema): XShardTSDataset is an abstract of time series dataset with distributed fashion. Cascade call is supported for most of the tr... | Implement the Python class `XShardsTSDataset` described below.
Class description:
Implement the XShardsTSDataset class.
Method signatures and docstrings:
- def __init__(self, shards, **schema): XShardTSDataset is an abstract of time series dataset with distributed fashion. Cascade call is supported for most of the tr... | 7cc3e2849057d6429d03b1af0db13caae57960a5 | <|skeleton|>
class XShardsTSDataset:
def __init__(self, shards, **schema):
"""XShardTSDataset is an abstract of time series dataset with distributed fashion. Cascade call is supported for most of the transform methods. XShardTSDataset will partition the dataset by id_col, which is experimental."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XShardsTSDataset:
def __init__(self, shards, **schema):
"""XShardTSDataset is an abstract of time series dataset with distributed fashion. Cascade call is supported for most of the transform methods. XShardTSDataset will partition the dataset by id_col, which is experimental."""
self.shards = ... | the_stack_v2_python_sparse | pyzoo/zoo/chronos/data/experimental/xshards_tsdataset.py | intel-analytics/analytics-zoo | train | 3,104 | |
b3309162925e9c6938c0c8d94c1e71c1b0c0c0d0 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | SimulatorServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulatorServicer:
"""Missing associated documentation comment in .proto file."""
def startDeviceSimulation(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def stopDeviceSimulation(self, request, context):
"""Mis... | stack_v2_sparse_classes_75kplus_train_068538 | 6,706 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "startDeviceSimulation",
"signature": "def startDeviceSimulation(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "stopDeviceSimulation",
"sign... | 3 | stack_v2_sparse_classes_30k_train_015807 | Implement the Python class `SimulatorServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def startDeviceSimulation(self, request, context): Missing associated documentation comment in .proto file.
- def stopDeviceSimulation(self, r... | Implement the Python class `SimulatorServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def startDeviceSimulation(self, request, context): Missing associated documentation comment in .proto file.
- def stopDeviceSimulation(self, r... | eb1cd0d0ee5eb02f27f76967679c29068b277a2e | <|skeleton|>
class SimulatorServicer:
"""Missing associated documentation comment in .proto file."""
def startDeviceSimulation(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def stopDeviceSimulation(self, request, context):
"""Mis... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimulatorServicer:
"""Missing associated documentation comment in .proto file."""
def startDeviceSimulation(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not imple... | the_stack_v2_python_sparse | src/gateway/protocol_buffers/generated_files/simulator_services_pb2_grpc.py | andru1236/mock-backend | train | 3 |
d68e6b31bd0e0f28ec1e35ab9a6228fce5830519 | [
"resultatheat = []\ncursor = db.resultatheat_collection.find()\nfor document in await cursor.to_list(length=2000):\n if str(document['Nr']).isnumeric() and int(document['Nr']) > 0:\n resultatheat.append(document)\n logging.debug(document)\nreturn resultatheat",
"resultatheat = []\ncursor = db.resulta... | <|body_start_0|>
resultatheat = []
cursor = db.resultatheat_collection.find()
for document in await cursor.to_list(length=2000):
if str(document['Nr']).isnumeric() and int(document['Nr']) > 0:
resultatheat.append(document)
logging.debug(document)
r... | Class representing resultatheat service. | ResultatHeatService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResultatHeatService:
"""Class representing resultatheat service."""
async def get_all_resultatheat(self, db: Any) -> List:
"""Get all resultatheat function."""
<|body_0|>
async def get_resultatheat_by_klasse(self, db: Any, klasse: str) -> List:
"""Get all resulta... | stack_v2_sparse_classes_75kplus_train_068539 | 3,809 | permissive | [
{
"docstring": "Get all resultatheat function.",
"name": "get_all_resultatheat",
"signature": "async def get_all_resultatheat(self, db: Any) -> List"
},
{
"docstring": "Get all resultatheat function.",
"name": "get_resultatheat_by_klasse",
"signature": "async def get_resultatheat_by_klas... | 6 | null | Implement the Python class `ResultatHeatService` described below.
Class description:
Class representing resultatheat service.
Method signatures and docstrings:
- async def get_all_resultatheat(self, db: Any) -> List: Get all resultatheat function.
- async def get_resultatheat_by_klasse(self, db: Any, klasse: str) -> ... | Implement the Python class `ResultatHeatService` described below.
Class description:
Class representing resultatheat service.
Method signatures and docstrings:
- async def get_all_resultatheat(self, db: Any) -> List: Get all resultatheat function.
- async def get_resultatheat_by_klasse(self, db: Any, klasse: str) -> ... | 065a96d102a6658e5422ea6a0be5abde4b6558e1 | <|skeleton|>
class ResultatHeatService:
"""Class representing resultatheat service."""
async def get_all_resultatheat(self, db: Any) -> List:
"""Get all resultatheat function."""
<|body_0|>
async def get_resultatheat_by_klasse(self, db: Any, klasse: str) -> List:
"""Get all resulta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResultatHeatService:
"""Class representing resultatheat service."""
async def get_all_resultatheat(self, db: Any) -> List:
"""Get all resultatheat function."""
resultatheat = []
cursor = db.resultatheat_collection.find()
for document in await cursor.to_list(length=2000):
... | the_stack_v2_python_sparse | src/sprint_webserver/services/resultat_heat_service.py | langrenn-sprint/sprint-webserver | train | 0 |
599471fca4ccb4ca24191a09dc5ffa6db27b94f2 | [
"super().__init__(validate)\nself._discriminator = discriminators\nself._n_circs = 0\nself._n_shots = 0\nself._n_slots = 0\nself._n_iq = 0",
"self._n_shots = 0\ntry:\n self._n_circs, self._n_shots, self._n_slots, self._n_iq = data.shape\nexcept ValueError as ex:\n raise DataProcessorError(f'The data given t... | <|body_start_0|>
super().__init__(validate)
self._discriminator = discriminators
self._n_circs = 0
self._n_shots = 0
self._n_slots = 0
self._n_iq = 0
<|end_body_0|>
<|body_start_1|>
self._n_shots = 0
try:
self._n_circs, self._n_shots, self._n_... | A class to discriminate kerneled data, e.g., IQ data, to produce counts. This node integrates into the data processing chain a serializable :class:`.BaseDiscriminator` subclass instance which must have a :meth:`~.BaseDiscriminator.predict` method that takes as input a list of lists and returns a list of labels. Crucial... | DiscriminatorNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscriminatorNode:
"""A class to discriminate kerneled data, e.g., IQ data, to produce counts. This node integrates into the data processing chain a serializable :class:`.BaseDiscriminator` subclass instance which must have a :meth:`~.BaseDiscriminator.predict` method that takes as input a list o... | stack_v2_sparse_classes_75kplus_train_068540 | 42,185 | permissive | [
{
"docstring": "Initialize the node with an object that can discriminate. Args: discriminators: The entity that will perform the discrimination. This needs to be a :class:`.BaseDiscriminator` or a list thereof that takes as input a list of lists and returns a list of labels. If a list of discriminators is given... | 3 | stack_v2_sparse_classes_30k_train_037347 | Implement the Python class `DiscriminatorNode` described below.
Class description:
A class to discriminate kerneled data, e.g., IQ data, to produce counts. This node integrates into the data processing chain a serializable :class:`.BaseDiscriminator` subclass instance which must have a :meth:`~.BaseDiscriminator.predi... | Implement the Python class `DiscriminatorNode` described below.
Class description:
A class to discriminate kerneled data, e.g., IQ data, to produce counts. This node integrates into the data processing chain a serializable :class:`.BaseDiscriminator` subclass instance which must have a :meth:`~.BaseDiscriminator.predi... | a387675a3fe817cef05b968bbf3e05799a09aaae | <|skeleton|>
class DiscriminatorNode:
"""A class to discriminate kerneled data, e.g., IQ data, to produce counts. This node integrates into the data processing chain a serializable :class:`.BaseDiscriminator` subclass instance which must have a :meth:`~.BaseDiscriminator.predict` method that takes as input a list o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiscriminatorNode:
"""A class to discriminate kerneled data, e.g., IQ data, to produce counts. This node integrates into the data processing chain a serializable :class:`.BaseDiscriminator` subclass instance which must have a :meth:`~.BaseDiscriminator.predict` method that takes as input a list of lists and r... | the_stack_v2_python_sparse | qiskit_experiments/data_processing/nodes.py | oliverdial/qiskit-experiments | train | 0 |
2e43a9fa7e132404c998a175158efd67a9733dbf | [
"hashmap = [-1 for _ in range(len(nums))]\nfor n in nums:\n if hashmap[n] != -1:\n return n\n else:\n hashmap[n] = 1",
"if len(nums) <= 0:\n return -1\nfor num in nums:\n if num < 0 or num > len(nums) - 1:\n return -1\nfor i in range(len(nums)):\n while nums[i] != i:\n i... | <|body_start_0|>
hashmap = [-1 for _ in range(len(nums))]
for n in nums:
if hashmap[n] != -1:
return n
else:
hashmap[n] = 1
<|end_body_0|>
<|body_start_1|>
if len(nums) <= 0:
return -1
for num in nums:
if nu... | Solution | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
"""This time and space complexity are O(n) and O(n) respectively."""
<|body_0|>
def findRepeatNumber_v2(self, nums: List[int]) -> int:
"""We note the nums in the array range from 0~n-1. If there is no dupl... | stack_v2_sparse_classes_75kplus_train_068541 | 1,913 | permissive | [
{
"docstring": "This time and space complexity are O(n) and O(n) respectively.",
"name": "findRepeatNumber",
"signature": "def findRepeatNumber(self, nums: List[int]) -> int"
},
{
"docstring": "We note the nums in the array range from 0~n-1. If there is no duplication, the number i will be arran... | 2 | stack_v2_sparse_classes_30k_train_052742 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRepeatNumber(self, nums: List[int]) -> int: This time and space complexity are O(n) and O(n) respectively.
- def findRepeatNumber_v2(self, nums: List[int]) -> int: We not... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRepeatNumber(self, nums: List[int]) -> int: This time and space complexity are O(n) and O(n) respectively.
- def findRepeatNumber_v2(self, nums: List[int]) -> int: We not... | 226cecde136531341ce23cdf88529345be1912fc | <|skeleton|>
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
"""This time and space complexity are O(n) and O(n) respectively."""
<|body_0|>
def findRepeatNumber_v2(self, nums: List[int]) -> int:
"""We note the nums in the array range from 0~n-1. If there is no dupl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
"""This time and space complexity are O(n) and O(n) respectively."""
hashmap = [-1 for _ in range(len(nums))]
for n in nums:
if hashmap[n] != -1:
return n
else:
hashmap... | the_stack_v2_python_sparse | Leetcode/Coding Interviews/03_01_Duplication_in_Array.py | ZR-Huang/AlgorithmsPractices | train | 1 | |
f70d219eca7edaa297f246e9478972dde97aa05d | [
"self.input_size = input_size\nself.output_size = output_size\nself.hidden_size = hidden_size\nnp.random.seed(41)\ntf.random.set_seed(42)\nself.initialize_weights(weights_initializer, bias_initializer)\nself.optimizer = optimizer(**optimizer_kwargs)",
"wshapes = [[self.input_size, self.hidden_size[0]]]\nlayer_ind... | <|body_start_0|>
self.input_size = input_size
self.output_size = output_size
self.hidden_size = hidden_size
np.random.seed(41)
tf.random.set_seed(42)
self.initialize_weights(weights_initializer, bias_initializer)
self.optimizer = optimizer(**optimizer_kwargs)
<|en... | Q-function approximator. | Network | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Network:
"""Q-function approximator."""
def __init__(self, input_size, output_size, hidden_size=[16, 8], weights_initializer=tf.initializers.glorot_uniform(), bias_initializer=tf.initializers.zeros(), optimizer=tf.optimizers.Adam, **optimizer_kwargs):
"""Initialize weights and hyperp... | stack_v2_sparse_classes_75kplus_train_068542 | 13,305 | no_license | [
{
"docstring": "Initialize weights and hyperparameters.",
"name": "__init__",
"signature": "def __init__(self, input_size, output_size, hidden_size=[16, 8], weights_initializer=tf.initializers.glorot_uniform(), bias_initializer=tf.initializers.zeros(), optimizer=tf.optimizers.Adam, **optimizer_kwargs)"
... | 4 | stack_v2_sparse_classes_30k_train_050921 | Implement the Python class `Network` described below.
Class description:
Q-function approximator.
Method signatures and docstrings:
- def __init__(self, input_size, output_size, hidden_size=[16, 8], weights_initializer=tf.initializers.glorot_uniform(), bias_initializer=tf.initializers.zeros(), optimizer=tf.optimizers... | Implement the Python class `Network` described below.
Class description:
Q-function approximator.
Method signatures and docstrings:
- def __init__(self, input_size, output_size, hidden_size=[16, 8], weights_initializer=tf.initializers.glorot_uniform(), bias_initializer=tf.initializers.zeros(), optimizer=tf.optimizers... | 602cdbf1b33c532c482c2dbd92ecffab3f0fa111 | <|skeleton|>
class Network:
"""Q-function approximator."""
def __init__(self, input_size, output_size, hidden_size=[16, 8], weights_initializer=tf.initializers.glorot_uniform(), bias_initializer=tf.initializers.zeros(), optimizer=tf.optimizers.Adam, **optimizer_kwargs):
"""Initialize weights and hyperp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Network:
"""Q-function approximator."""
def __init__(self, input_size, output_size, hidden_size=[16, 8], weights_initializer=tf.initializers.glorot_uniform(), bias_initializer=tf.initializers.zeros(), optimizer=tf.optimizers.Adam, **optimizer_kwargs):
"""Initialize weights and hyperparameters."""... | the_stack_v2_python_sparse | Algorithms/deep_q_learning.py | Healthy-AI/TreatmentExploration | train | 1 |
7864e7082fab121fb5b76a0849f78e8dc3f9be71 | [
"if not self._fixture_manager:\n self._fixture_manager = [f for f in gc.get_objects() if isinstance(f, FixtureManager)][0]\nif not self._fixture_manager:\n raise Exception('Attempted to use FixtureManager outside of pytest session.')\nreturn self._fixture_manager",
"if (fixture := self.fixture_manager._arg2... | <|body_start_0|>
if not self._fixture_manager:
self._fixture_manager = [f for f in gc.get_objects() if isinstance(f, FixtureManager)][0]
if not self._fixture_manager:
raise Exception('Attempted to use FixtureManager outside of pytest session.')
return self._fixture_manage... | FixtureFinder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixtureFinder:
def fixture_manager(self):
"""Find references to pytest's FixtureManager or raise and exception"""
<|body_0|>
def find_fixture_val(self, fixture_name):
"""Find the value for an already resolved fixture"""
<|body_1|>
def resolve_fixtures(se... | stack_v2_sparse_classes_75kplus_train_068543 | 1,723 | permissive | [
{
"docstring": "Find references to pytest's FixtureManager or raise and exception",
"name": "fixture_manager",
"signature": "def fixture_manager(self)"
},
{
"docstring": "Find the value for an already resolved fixture",
"name": "find_fixture_val",
"signature": "def find_fixture_val(self,... | 4 | stack_v2_sparse_classes_30k_train_021356 | Implement the Python class `FixtureFinder` described below.
Class description:
Implement the FixtureFinder class.
Method signatures and docstrings:
- def fixture_manager(self): Find references to pytest's FixtureManager or raise and exception
- def find_fixture_val(self, fixture_name): Find the value for an already r... | Implement the Python class `FixtureFinder` described below.
Class description:
Implement the FixtureFinder class.
Method signatures and docstrings:
- def fixture_manager(self): Find references to pytest's FixtureManager or raise and exception
- def find_fixture_val(self, fixture_name): Find the value for an already r... | 52873adc007a22386ec22f96ccd1a8eab21c2274 | <|skeleton|>
class FixtureFinder:
def fixture_manager(self):
"""Find references to pytest's FixtureManager or raise and exception"""
<|body_0|>
def find_fixture_val(self, fixture_name):
"""Find the value for an already resolved fixture"""
<|body_1|>
def resolve_fixtures(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FixtureFinder:
def fixture_manager(self):
"""Find references to pytest's FixtureManager or raise and exception"""
if not self._fixture_manager:
self._fixture_manager = [f for f in gc.get_objects() if isinstance(f, FixtureManager)][0]
if not self._fixture_manager:
... | the_stack_v2_python_sparse | Python/halloween_special/my_app/ssshhh.py | JacobCallahan/Understanding | train | 11 | |
4e5aaf07f9a99c88cddd7d8ef47b6689526a119b | [
"length = 0\nnode = head\nwhile node:\n length += 1\n node = node.next\ndummy = ListNode(0)\ndummy.next = head\ni = 0\nprev = dummy\nwhile i < length - n:\n i += 1\n prev = prev.next\nprev.next = prev.next.next\nreturn dummy.next",
"dummy = ListNode(0)\ndummy.next = head\nfront = dummy\nback = dummy\n... | <|body_start_0|>
length = 0
node = head
while node:
length += 1
node = node.next
dummy = ListNode(0)
dummy.next = head
i = 0
prev = dummy
while i < length - n:
i += 1
prev = prev.next
prev.next = prev... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode:
"""1. 扫描两遍"""
<|body_0|>
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""KEY: 2. 双指针"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = 0
no... | stack_v2_sparse_classes_75kplus_train_068544 | 2,002 | no_license | [
{
"docstring": "1. 扫描两遍",
"name": "removeNthFromEnd_1",
"signature": "def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode"
},
{
"docstring": "KEY: 2. 双指针",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_027292 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode: 1. 扫描两遍
- def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: KEY: 2. 双指针 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode: 1. 扫描两遍
- def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: KEY: 2. 双指针
<|skeleton|>
class Soluti... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode:
"""1. 扫描两遍"""
<|body_0|>
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""KEY: 2. 双指针"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode:
"""1. 扫描两遍"""
length = 0
node = head
while node:
length += 1
node = node.next
dummy = ListNode(0)
dummy.next = head
i = 0
prev = dummy
whi... | the_stack_v2_python_sparse | .leetcode/19.删除链表的倒数第n个节点.py | xiaoruijiang/algorithm | train | 0 | |
fd07364b1590a2ca32e76c5871c8f70410c7c633 | [
"self.total = 0\nself.size = size\nself.queue = []",
"if len(self.queue) >= self.size:\n out = self.queue.pop(0)\n self.total -= out\nself.queue.append(val)\nself.total += val\nreturn self.total / len(self.queue)"
] | <|body_start_0|>
self.total = 0
self.size = size
self.queue = []
<|end_body_0|>
<|body_start_1|>
if len(self.queue) >= self.size:
out = self.queue.pop(0)
self.total -= out
self.queue.append(val)
self.total += val
return self.total / len(se... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size: int):
"""Initialize your data structure here."""
<|body_0|>
def next(self, val: int) -> float:
"""如果当前的size超过了初始size, 即弹出第一个数字 queue.pop(0), 这样queue总保持初始size-1的大小。 保持一个窗口里,因此total要减去pop出来的数字,此操作为O(1) 再把当前数字val 放到queue里,并且加入到tot... | stack_v2_sparse_classes_75kplus_train_068545 | 1,545 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self, size: int)"
},
{
"docstring": "如果当前的size超过了初始size, 即弹出第一个数字 queue.pop(0), 这样queue总保持初始size-1的大小。 保持一个窗口里,因此total要减去pop出来的数字,此操作为O(1) 再把当前数字val 放到queue里,并且加入到total, 除以当前size即使平均数",
"nam... | 2 | stack_v2_sparse_classes_30k_train_002688 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size: int): Initialize your data structure here.
- def next(self, val: int) -> float: 如果当前的size超过了初始size, 即弹出第一个数字 queue.pop(0), 这样queue总保持初始size-1的大... | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size: int): Initialize your data structure here.
- def next(self, val: int) -> float: 如果当前的size超过了初始size, 即弹出第一个数字 queue.pop(0), 这样queue总保持初始size-1的大... | 034efcefe9940267abcf4c9cab655b2344e3e901 | <|skeleton|>
class MovingAverage:
def __init__(self, size: int):
"""Initialize your data structure here."""
<|body_0|>
def next(self, val: int) -> float:
"""如果当前的size超过了初始size, 即弹出第一个数字 queue.pop(0), 这样queue总保持初始size-1的大小。 保持一个窗口里,因此total要减去pop出来的数字,此操作为O(1) 再把当前数字val 放到queue里,并且加入到tot... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovingAverage:
def __init__(self, size: int):
"""Initialize your data structure here."""
self.total = 0
self.size = size
self.queue = []
def next(self, val: int) -> float:
"""如果当前的size超过了初始size, 即弹出第一个数字 queue.pop(0), 这样queue总保持初始size-1的大小。 保持一个窗口里,因此total要减去pop出来的... | the_stack_v2_python_sparse | 346_moving_average_from_data_stream.py | HongsenHe/algo2018 | train | 0 | |
f0189dba76963edfcdf1f5cb63f36423adc2ab9e | [
"super(DropStripes, self).__init__()\nassert dim in [2, 3]\nself.dim = dim\nself.drop_width = drop_width\nself.stripes_num = stripes_num",
"assert input.ndimension() == 4\nif self.training is False and (not test):\n return input\nelse:\n batch_size = input.shape[0]\n total_width = input.shape[self.dim]\n... | <|body_start_0|>
super(DropStripes, self).__init__()
assert dim in [2, 3]
self.dim = dim
self.drop_width = drop_width
self.stripes_num = stripes_num
<|end_body_0|>
<|body_start_1|>
assert input.ndimension() == 4
if self.training is False and (not test):
... | DropStripes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DropStripes:
def __init__(self, dim, drop_width, stripes_num):
"""Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop"""
<|body_0|>
def forward(self, input, test=False):
... | stack_v2_sparse_classes_75kplus_train_068546 | 9,371 | no_license | [
{
"docstring": "Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop",
"name": "__init__",
"signature": "def __init__(self, dim, drop_width, stripes_num)"
},
{
"docstring": "input: (batch_size, ch... | 3 | stack_v2_sparse_classes_30k_train_011690 | Implement the Python class `DropStripes` described below.
Class description:
Implement the DropStripes class.
Method signatures and docstrings:
- def __init__(self, dim, drop_width, stripes_num): Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num:... | Implement the Python class `DropStripes` described below.
Class description:
Implement the DropStripes class.
Method signatures and docstrings:
- def __init__(self, dim, drop_width, stripes_num): Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num:... | 369321993ef2a5358170a2593d9f1f2631886036 | <|skeleton|>
class DropStripes:
def __init__(self, dim, drop_width, stripes_num):
"""Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop"""
<|body_0|>
def forward(self, input, test=False):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DropStripes:
def __init__(self, dim, drop_width, stripes_num):
"""Drop stripes. Args: dim: int, dimension along which to drop drop_width: int, maximum width of stripes to drop stripes_num: int, how many stripes to drop"""
super(DropStripes, self).__init__()
assert dim in [2, 3]
... | the_stack_v2_python_sparse | utils/generic_utils.py | Edresson/SPIRA-ComParE2021 | train | 1 | |
5ed1acc307474ea9490bd0ea235a3d568a2c60c4 | [
"if n <= 0:\n return False\nreturn n & n - 1 == 0",
"if n == 1 or n == 2:\n return True\nelif n == 0:\n return False\nleft = n % 2\nif left:\n return False\nn = n / 2\nwhile n:\n if n == 2:\n return True\n left = n % 2\n if left:\n return False\n n = n / 2\nreturn True"
] | <|body_start_0|>
if n <= 0:
return False
return n & n - 1 == 0
<|end_body_0|>
<|body_start_1|>
if n == 1 or n == 2:
return True
elif n == 0:
return False
left = n % 2
if left:
return False
n = n / 2
while n:... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def _isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n <= 0:
return False
return n & n - 1 == ... | stack_v2_sparse_classes_75kplus_train_068547 | 1,163 | permissive | [
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOfTwo",
"signature": "def isPowerOfTwo(self, n)"
},
{
"docstring": ":type n: int :rtype: bool",
"name": "_isPowerOfTwo",
"signature": "def _isPowerOfTwo(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052286 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo(self, n): :type n: int :rtype: bool
- def _isPowerOfTwo(self, n): :type n: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo(self, n): :type n: int :rtype: bool
- def _isPowerOfTwo(self, n): :type n: int :rtype: bool
<|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def _isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
if n <= 0:
return False
return n & n - 1 == 0
def _isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
if n == 1 or n == 2:
return True
elif n == 0:
... | the_stack_v2_python_sparse | 231.power-of-two.py | windard/leeeeee | train | 0 | |
a05a1e920347ac67689a99be3428ea9dc63ffd1c | [
"super(OUIIndexParser, self).__init__()\nif hasattr(ieee_file, 'readline') and hasattr(ieee_file, 'tell'):\n self.fh = ieee_file\nelse:\n self.fh = open(ieee_file, 'rb')",
"skip_header = True\nrecord = None\nsize = 0\nmarker = _bytes_type('(hex)')\nhyphen = _bytes_type('-')\nempty_string = _bytes_type('')\n... | <|body_start_0|>
super(OUIIndexParser, self).__init__()
if hasattr(ieee_file, 'readline') and hasattr(ieee_file, 'tell'):
self.fh = ieee_file
else:
self.fh = open(ieee_file, 'rb')
<|end_body_0|>
<|body_start_1|>
skip_header = True
record = None
si... | A concrete Publisher that parses OUI (Organisationally Unique Identifier) records from IEEE text-based registration files It notifies registered Subscribers as each record is encountered, passing on the record's position relative to the start of the file (offset) and the size of the record (in bytes). The file processe... | OUIIndexParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OUIIndexParser:
"""A concrete Publisher that parses OUI (Organisationally Unique Identifier) records from IEEE text-based registration files It notifies registered Subscribers as each record is encountered, passing on the record's position relative to the start of the file (offset) and the size o... | stack_v2_sparse_classes_75kplus_train_068548 | 9,500 | permissive | [
{
"docstring": "Constructor. :param ieee_file: a file-like object or name of file containing OUI records. When using a file-like object always open it in binary mode otherwise offsets will probably misbehave.",
"name": "__init__",
"signature": "def __init__(self, ieee_file)"
},
{
"docstring": "S... | 2 | stack_v2_sparse_classes_30k_train_031467 | Implement the Python class `OUIIndexParser` described below.
Class description:
A concrete Publisher that parses OUI (Organisationally Unique Identifier) records from IEEE text-based registration files It notifies registered Subscribers as each record is encountered, passing on the record's position relative to the st... | Implement the Python class `OUIIndexParser` described below.
Class description:
A concrete Publisher that parses OUI (Organisationally Unique Identifier) records from IEEE text-based registration files It notifies registered Subscribers as each record is encountered, passing on the record's position relative to the st... | 750da5eaef33cede9f3ef532453d63e507f34a2c | <|skeleton|>
class OUIIndexParser:
"""A concrete Publisher that parses OUI (Organisationally Unique Identifier) records from IEEE text-based registration files It notifies registered Subscribers as each record is encountered, passing on the record's position relative to the start of the file (offset) and the size o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OUIIndexParser:
"""A concrete Publisher that parses OUI (Organisationally Unique Identifier) records from IEEE text-based registration files It notifies registered Subscribers as each record is encountered, passing on the record's position relative to the start of the file (offset) and the size of the record ... | the_stack_v2_python_sparse | venv/Lib/site-packages/netaddr/eui/ieee.py | natemellendorf/configpy | train | 4 |
0c05df8cc914f912d6693fd7caee7f7698d7e809 | [
"child = subprocess.Popen(self.IDENTIFY + [file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nstdout, stderr = child.communicate()\nstatus = child.wait()\nmatch = re.search(' (\\\\d+)x(\\\\d+) ', stdout)\nif status or not match:\n raise ImageException(stdout)\nreturn (int(match.group(1)), int(match.gro... | <|body_start_0|>
child = subprocess.Popen(self.IDENTIFY + [file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = child.communicate()
status = child.wait()
match = re.search(' (\\d+)x(\\d+) ', stdout)
if status or not match:
raise ImageException(... | Simple interface to ImageMagick. Why ImageMagick? PIL's thumbnailing is very buggy, and I'm tired of working around those bugs. The most severe problems with PIL for me have been: - Lack of support for interlaced PNGs, buggy (or just confusing?) support for transparent GIFs. - A fraction of a pixel is cut off of the ri... | ImageMagick | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageMagick:
"""Simple interface to ImageMagick. Why ImageMagick? PIL's thumbnailing is very buggy, and I'm tired of working around those bugs. The most severe problems with PIL for me have been: - Lack of support for interlaced PNGs, buggy (or just confusing?) support for transparent GIFs. - A f... | stack_v2_sparse_classes_75kplus_train_068549 | 10,975 | no_license | [
{
"docstring": "Probe the size of an on-disk image, returning a (width, height) tuple.",
"name": "get_image_size",
"signature": "def get_image_size(self, file_path)"
},
{
"docstring": "Return a new path to a temporary file, using the provided filename as a hint for the temporary file's extension... | 4 | stack_v2_sparse_classes_30k_train_023332 | Implement the Python class `ImageMagick` described below.
Class description:
Simple interface to ImageMagick. Why ImageMagick? PIL's thumbnailing is very buggy, and I'm tired of working around those bugs. The most severe problems with PIL for me have been: - Lack of support for interlaced PNGs, buggy (or just confusin... | Implement the Python class `ImageMagick` described below.
Class description:
Simple interface to ImageMagick. Why ImageMagick? PIL's thumbnailing is very buggy, and I'm tired of working around those bugs. The most severe problems with PIL for me have been: - Lack of support for interlaced PNGs, buggy (or just confusin... | fd505c3badbe3d13dd1d339b719f849a3e24f864 | <|skeleton|>
class ImageMagick:
"""Simple interface to ImageMagick. Why ImageMagick? PIL's thumbnailing is very buggy, and I'm tired of working around those bugs. The most severe problems with PIL for me have been: - Lack of support for interlaced PNGs, buggy (or just confusing?) support for transparent GIFs. - A f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageMagick:
"""Simple interface to ImageMagick. Why ImageMagick? PIL's thumbnailing is very buggy, and I'm tired of working around those bugs. The most severe problems with PIL for me have been: - Lack of support for interlaced PNGs, buggy (or just confusing?) support for transparent GIFs. - A fraction of a ... | the_stack_v2_python_sparse | cia/apps/images/models.py | Justasic/cia-vc | train | 6 |
8500f3587a8d45b631baef7f37bd72fcb98be3db | [
"delay_factor = self.select_delay_factor(delay_factor=0)\ntime.sleep(1 * delay_factor)\nself.set_base_prompt()\nself.enable()\nself.disable_paging(command='no paging')",
"if not pattern:\n pattern = self.base_prompt[:16]\nreturn super(ArubaSSH, self).check_config_mode(check_string=check_string, pattern=pattern... | <|body_start_0|>
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.set_base_prompt()
self.enable()
self.disable_paging(command='no paging')
<|end_body_0|>
<|body_start_1|>
if not pattern:
pattern = self.base_prompt[:16]... | Aruba OS support | ArubaSSH | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArubaSSH:
"""Aruba OS support"""
def session_preparation(self):
"""Aruba OS requires enable mode to disable paging."""
<|body_0|>
def check_config_mode(self, check_string='(config) #', pattern=''):
"""Checks if the device is in configuration mode or not. Aruba us... | stack_v2_sparse_classes_75kplus_train_068550 | 901 | permissive | [
{
"docstring": "Aruba OS requires enable mode to disable paging.",
"name": "session_preparation",
"signature": "def session_preparation(self)"
},
{
"docstring": "Checks if the device is in configuration mode or not. Aruba uses \"(<controller name>) (config) #\" as config prompt",
"name": "ch... | 2 | stack_v2_sparse_classes_30k_train_033444 | Implement the Python class `ArubaSSH` described below.
Class description:
Aruba OS support
Method signatures and docstrings:
- def session_preparation(self): Aruba OS requires enable mode to disable paging.
- def check_config_mode(self, check_string='(config) #', pattern=''): Checks if the device is in configuration ... | Implement the Python class `ArubaSSH` described below.
Class description:
Aruba OS support
Method signatures and docstrings:
- def session_preparation(self): Aruba OS requires enable mode to disable paging.
- def check_config_mode(self, check_string='(config) #', pattern=''): Checks if the device is in configuration ... | f7ff5e6278acaecff7583518cc97bd945fceddc3 | <|skeleton|>
class ArubaSSH:
"""Aruba OS support"""
def session_preparation(self):
"""Aruba OS requires enable mode to disable paging."""
<|body_0|>
def check_config_mode(self, check_string='(config) #', pattern=''):
"""Checks if the device is in configuration mode or not. Aruba us... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArubaSSH:
"""Aruba OS support"""
def session_preparation(self):
"""Aruba OS requires enable mode to disable paging."""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.set_base_prompt()
self.enable()
self.disable_pag... | the_stack_v2_python_sparse | netmiko/aruba/aruba_ssh.py | hellt/netmiko | train | 2 |
39d06fdee411c634ee53e07a1ceda24cefca13b4 | [
"super().__init__()\nself.downsampler = nn.AvgPool1d(4, stride=2, padding=1, count_include_pad=False)\nself.discriminators = nn.ModuleDict()\nfor idx in range(discriminator_number):\n self.discriminators[f'disc_{idx}'] = DiscriminatorBlock(downsampling_factor=downsampling_factor)",
"output = []\nfor name, desc... | <|body_start_0|>
super().__init__()
self.downsampler = nn.AvgPool1d(4, stride=2, padding=1, count_include_pad=False)
self.discriminators = nn.ModuleDict()
for idx in range(discriminator_number):
self.discriminators[f'disc_{idx}'] = DiscriminatorBlock(downsampling_factor=downs... | Discriminator model for MelGAN | Discriminator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Discriminator:
"""Discriminator model for MelGAN"""
def __init__(self, discriminator_number: int=3, downsampling_factor: int=4):
"""Discriminator model for MelGAN Consists of several discriminators with various downsampling factors. Base discriminator consists only of convolutional l... | stack_v2_sparse_classes_75kplus_train_068551 | 4,148 | no_license | [
{
"docstring": "Discriminator model for MelGAN Consists of several discriminators with various downsampling factors. Base discriminator consists only of convolutional layers. Args: discriminator_number: number of discriminator blocks downsampling_factor: downsampling factor for every discriminator block.",
... | 2 | stack_v2_sparse_classes_30k_train_052279 | Implement the Python class `Discriminator` described below.
Class description:
Discriminator model for MelGAN
Method signatures and docstrings:
- def __init__(self, discriminator_number: int=3, downsampling_factor: int=4): Discriminator model for MelGAN Consists of several discriminators with various downsampling fac... | Implement the Python class `Discriminator` described below.
Class description:
Discriminator model for MelGAN
Method signatures and docstrings:
- def __init__(self, discriminator_number: int=3, downsampling_factor: int=4): Discriminator model for MelGAN Consists of several discriminators with various downsampling fac... | d5eac1cfb7d382c26d9e1961e443941410e1c1ba | <|skeleton|>
class Discriminator:
"""Discriminator model for MelGAN"""
def __init__(self, discriminator_number: int=3, downsampling_factor: int=4):
"""Discriminator model for MelGAN Consists of several discriminators with various downsampling factors. Base discriminator consists only of convolutional l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Discriminator:
"""Discriminator model for MelGAN"""
def __init__(self, discriminator_number: int=3, downsampling_factor: int=4):
"""Discriminator model for MelGAN Consists of several discriminators with various downsampling factors. Base discriminator consists only of convolutional layers. Args: ... | the_stack_v2_python_sparse | src/models/discriminator.py | elephantmipt/MelGAN | train | 6 |
697fcf79cf933bfd168ad4d73eca2915173bffc4 | [
"if not name:\n raise ValueError(u'用户必须提供用户名称')\nuser = self.model(name=name)\nif nick_name:\n user.nick_name = nick_name\nelse:\n user.nick_name = name\nuser.user_group = UserGroup.objects.get_or_create_default_ug()\nuser.is_admin = is_admin\nuser.reg_ip = reg_ip\nuser.gender = gender\nuser.set_password(p... | <|body_start_0|>
if not name:
raise ValueError(u'用户必须提供用户名称')
user = self.model(name=name)
if nick_name:
user.nick_name = nick_name
else:
user.nick_name = name
user.user_group = UserGroup.objects.get_or_create_default_ug()
user.is_admin... | MyUserManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, name, password=None, nick_name=None, gender=None, reg_ip='', is_admin=False):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, name, password):
"""Creates and s... | stack_v2_sparse_classes_75kplus_train_068552 | 8,392 | permissive | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, name, password=None, nick_name=None, gender=None, reg_ip='', is_admin=False)"
},
{
"docstring": "Creates and saves a superuser with the given em... | 2 | stack_v2_sparse_classes_30k_train_012130 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, name, password=None, nick_name=None, gender=None, reg_ip='', is_admin=False): Creates and saves a User with the given email, date of birth and pas... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, name, password=None, nick_name=None, gender=None, reg_ip='', is_admin=False): Creates and saves a User with the given email, date of birth and pas... | cef6408e533bd0b0f57c3e2f5da4e93ea07c4331 | <|skeleton|>
class MyUserManager:
def create_user(self, name, password=None, nick_name=None, gender=None, reg_ip='', is_admin=False):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, name, password):
"""Creates and s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyUserManager:
def create_user(self, name, password=None, nick_name=None, gender=None, reg_ip='', is_admin=False):
"""Creates and saves a User with the given email, date of birth and password."""
if not name:
raise ValueError(u'用户必须提供用户名称')
user = self.model(name=name)
... | the_stack_v2_python_sparse | account/models.py | shmilyoo/ggxxBBS | train | 0 | |
ee9012b5425fbfc37174aa31a034c84409da5ac2 | [
"D = self._dimension\nbas = self._basis_shapes[component]\nbs = self._basis_sizes[component]\nif isinstance(grid, Grid):\n nn = grid.get_number_nodes(overall=True)\n nodes = grid.get_nodes()\nelse:\n nn = prod(grid.shape[1:])\n nodes = grid\nphi = zeros((bs, nn), dtype=complexfloating)\nphi0 = self._eva... | <|body_start_0|>
D = self._dimension
bas = self._basis_shapes[component]
bs = self._basis_sizes[component]
if isinstance(grid, Grid):
nn = grid.get_number_nodes(overall=True)
nodes = grid.get_nodes()
else:
nn = prod(grid.shape[1:])
... | This class represents homogeneous vector valued Hagedorn wavepackets :math:`\\Psi` with :math:`N` components in :math:`D` space dimensions. | HagedornWavepacketCpp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HagedornWavepacketCpp:
"""This class represents homogeneous vector valued Hagedorn wavepackets :math:`\\Psi` with :math:`N` components in :math:`D` space dimensions."""
def evaluate_basis_at(self, grid, component, prefactor=False):
"""Evaluate the basis functions :math:`\\phi_k` recu... | stack_v2_sparse_classes_75kplus_train_068553 | 4,661 | no_license | [
{
"docstring": "Evaluate the basis functions :math:`\\\\phi_k` recursively at the given nodes :math:`\\\\gamma`. :param grid: The grid :math:\\\\Gamma` containing the nodes :math:`\\\\gamma`. :type grid: A class having a :py:method:`get_nodes(...)` method. :param component: The index :math:`i` of a single compo... | 2 | stack_v2_sparse_classes_30k_train_049989 | Implement the Python class `HagedornWavepacketCpp` described below.
Class description:
This class represents homogeneous vector valued Hagedorn wavepackets :math:`\\Psi` with :math:`N` components in :math:`D` space dimensions.
Method signatures and docstrings:
- def evaluate_basis_at(self, grid, component, prefactor=... | Implement the Python class `HagedornWavepacketCpp` described below.
Class description:
This class represents homogeneous vector valued Hagedorn wavepackets :math:`\\Psi` with :math:`N` components in :math:`D` space dimensions.
Method signatures and docstrings:
- def evaluate_basis_at(self, grid, component, prefactor=... | 664896a731058cd7bb1f028e3f2b92043b87950b | <|skeleton|>
class HagedornWavepacketCpp:
"""This class represents homogeneous vector valued Hagedorn wavepackets :math:`\\Psi` with :math:`N` components in :math:`D` space dimensions."""
def evaluate_basis_at(self, grid, component, prefactor=False):
"""Evaluate the basis functions :math:`\\phi_k` recu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HagedornWavepacketCpp:
"""This class represents homogeneous vector valued Hagedorn wavepackets :math:`\\Psi` with :math:`N` components in :math:`D` space dimensions."""
def evaluate_basis_at(self, grid, component, prefactor=False):
"""Evaluate the basis functions :math:`\\phi_k` recursively at th... | the_stack_v2_python_sparse | src/WaveBlocksND/HagedornWavepacketCpp.py | rngantner/WaveBlocksND | train | 0 |
fd4c86be2a5e849567dc6e97254f3970055695d7 | [
"super().__init__()\nself._port = nconfig().get('port', 8091)\nself._certificate = nconfig().get('certificate', 'cert.pem')\nself._private_key = nconfig().get('privatekey', 'priv.pem')\nself._use_ssl = nconfig().get('use_ssl', True)",
"socket_pair = ('', self._port)\nself._httpd = MultithreadedHTTPServer(socket_p... | <|body_start_0|>
super().__init__()
self._port = nconfig().get('port', 8091)
self._certificate = nconfig().get('certificate', 'cert.pem')
self._private_key = nconfig().get('privatekey', 'priv.pem')
self._use_ssl = nconfig().get('use_ssl', True)
<|end_body_0|>
<|body_start_1|>
... | The HTTP web server. | Webserver | [
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Webserver:
"""The HTTP web server."""
def __init__(self) -> None:
"""Constructor."""
<|body_0|>
def run(self) -> None:
"""Starts the HTTP server in the background."""
<|body_1|>
def stop(self) -> None:
"""Stops the HTTP server if it is runnin... | stack_v2_sparse_classes_75kplus_train_068554 | 4,037 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Starts the HTTP server in the background.",
"name": "run",
"signature": "def run(self) -> None"
},
{
"docstring": "Stops the HTTP server if it is running.",
"name":... | 4 | stack_v2_sparse_classes_30k_train_009269 | Implement the Python class `Webserver` described below.
Class description:
The HTTP web server.
Method signatures and docstrings:
- def __init__(self) -> None: Constructor.
- def run(self) -> None: Starts the HTTP server in the background.
- def stop(self) -> None: Stops the HTTP server if it is running.
- def _creat... | Implement the Python class `Webserver` described below.
Class description:
The HTTP web server.
Method signatures and docstrings:
- def __init__(self) -> None: Constructor.
- def run(self) -> None: Starts the HTTP server in the background.
- def stop(self) -> None: Stops the HTTP server if it is running.
- def _creat... | 7f7737923e5d8441bbc65cafedf29db14e750860 | <|skeleton|>
class Webserver:
"""The HTTP web server."""
def __init__(self) -> None:
"""Constructor."""
<|body_0|>
def run(self) -> None:
"""Starts the HTTP server in the background."""
<|body_1|>
def stop(self) -> None:
"""Stops the HTTP server if it is runnin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Webserver:
"""The HTTP web server."""
def __init__(self) -> None:
"""Constructor."""
super().__init__()
self._port = nconfig().get('port', 8091)
self._certificate = nconfig().get('certificate', 'cert.pem')
self._private_key = nconfig().get('privatekey', 'priv.pem')... | the_stack_v2_python_sparse | src/nussschale/webserver.py | RealFloorIsJava/KgF | train | 0 |
9b4d0268df88785661c67641050d93afef2703b7 | [
"self.user_ntype = user_ntype\nself.item_ntype = item_ntype\nself.user_to_item_etype = user_to_item_etype\nself.batch_size = batch_size\nself.timestamp = timestamp",
"graph_slice = full_graph.edge_type_subgraph([self.user_to_item_etype])\nlatest_interactions = dgl.sampling.select_topk(graph_slice, 1, self.timesta... | <|body_start_0|>
self.user_ntype = user_ntype
self.item_ntype = item_ntype
self.user_to_item_etype = user_to_item_etype
self.batch_size = batch_size
self.timestamp = timestamp
<|end_body_0|>
<|body_start_1|>
graph_slice = full_graph.edge_type_subgraph([self.user_to_item_... | LatestNNRecommender class uses given item embeddings to recommend k-nearest neighboring items. | LatestNNRecommender | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LatestNNRecommender:
"""LatestNNRecommender class uses given item embeddings to recommend k-nearest neighboring items."""
def __init__(self, user_ntype, item_ntype, user_to_item_etype, timestamp, batch_size):
"""Constructor of LatestNNRecommender class. Args: user_ntype (str): user n... | stack_v2_sparse_classes_75kplus_train_068555 | 8,505 | no_license | [
{
"docstring": "Constructor of LatestNNRecommender class. Args: user_ntype (str): user node name item_ntype (str): item node name user_to_item_etype (str): user-item edge name timestamp (str): timestamp column name batch_size (int): batch size",
"name": "__init__",
"signature": "def __init__(self, user_... | 2 | stack_v2_sparse_classes_30k_train_007279 | Implement the Python class `LatestNNRecommender` described below.
Class description:
LatestNNRecommender class uses given item embeddings to recommend k-nearest neighboring items.
Method signatures and docstrings:
- def __init__(self, user_ntype, item_ntype, user_to_item_etype, timestamp, batch_size): Constructor of ... | Implement the Python class `LatestNNRecommender` described below.
Class description:
LatestNNRecommender class uses given item embeddings to recommend k-nearest neighboring items.
Method signatures and docstrings:
- def __init__(self, user_ntype, item_ntype, user_to_item_etype, timestamp, batch_size): Constructor of ... | f1c385e46d2d5475b28dec91b57a933ac81c23c5 | <|skeleton|>
class LatestNNRecommender:
"""LatestNNRecommender class uses given item embeddings to recommend k-nearest neighboring items."""
def __init__(self, user_ntype, item_ntype, user_to_item_etype, timestamp, batch_size):
"""Constructor of LatestNNRecommender class. Args: user_ntype (str): user n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LatestNNRecommender:
"""LatestNNRecommender class uses given item embeddings to recommend k-nearest neighboring items."""
def __init__(self, user_ntype, item_ntype, user_to_item_etype, timestamp, batch_size):
"""Constructor of LatestNNRecommender class. Args: user_ntype (str): user node name item... | the_stack_v2_python_sparse | projects/project_19/src/pinsage/evaluation.py | amuamushu/projects-2020-2021 | train | 0 |
8d3024c024307859c217a01028222f57748cbc3c | [
"super(LocalCallbackSensor, self).__init__(query_interval, max_queue)\nself._event_file = event_file\nself._file_handle = None",
"if self._file_handle is None:\n if not os.path.exists(self._event_file):\n return None\n try:\n self._file_handle = open(self._event_file, 'r')\n except IOError:... | <|body_start_0|>
super(LocalCallbackSensor, self).__init__(query_interval, max_queue)
self._event_file = event_file
self._file_handle = None
<|end_body_0|>
<|body_start_1|>
if self._file_handle is None:
if not os.path.exists(self._event_file):
return None
... | 从本地文件中获取事件的感知器。该感知器从指定的本地文件中读取事件,模拟感知外部事件,通常 该感知器仅适用于本地调试和试运行 .. Note:: 在读取文件内容后,进行修改文件名的操作,以避免对同一事件的重复调用(重复读取文件) | LocalCallbackSensor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalCallbackSensor:
"""从本地文件中获取事件的感知器。该感知器从指定的本地文件中读取事件,模拟感知外部事件,通常 该感知器仅适用于本地调试和试运行 .. Note:: 在读取文件内容后,进行修改文件名的操作,以避免对同一事件的重复调用(重复读取文件)"""
def __init__(self, event_file, query_interval=3, max_queue=10):
"""初始化方法 :param str event_file: 存放事件的文件名 :param float query_interval: 查询事件的时间间隔... | stack_v2_sparse_classes_75kplus_train_068556 | 2,138 | permissive | [
{
"docstring": "初始化方法 :param str event_file: 存放事件的文件名 :param float query_interval: 查询事件的时间间隔 :param int max_queue: 最大队列长度",
"name": "__init__",
"signature": "def __init__(self, event_file, query_interval=3, max_queue=10)"
},
{
"docstring": "从文件中获取事件,文件中的每一行都会做为一个事件读入,读取完成后,文件会被改名 :return: 事件 :rt... | 2 | stack_v2_sparse_classes_30k_train_042358 | Implement the Python class `LocalCallbackSensor` described below.
Class description:
从本地文件中获取事件的感知器。该感知器从指定的本地文件中读取事件,模拟感知外部事件,通常 该感知器仅适用于本地调试和试运行 .. Note:: 在读取文件内容后,进行修改文件名的操作,以避免对同一事件的重复调用(重复读取文件)
Method signatures and docstrings:
- def __init__(self, event_file, query_interval=3, max_queue=10): 初始化方法 :param str ev... | Implement the Python class `LocalCallbackSensor` described below.
Class description:
从本地文件中获取事件的感知器。该感知器从指定的本地文件中读取事件,模拟感知外部事件,通常 该感知器仅适用于本地调试和试运行 .. Note:: 在读取文件内容后,进行修改文件名的操作,以避免对同一事件的重复调用(重复读取文件)
Method signatures and docstrings:
- def __init__(self, event_file, query_interval=3, max_queue=10): 初始化方法 :param str ev... | c20e7528f560b941ffbd8f053d120fe581919bba | <|skeleton|>
class LocalCallbackSensor:
"""从本地文件中获取事件的感知器。该感知器从指定的本地文件中读取事件,模拟感知外部事件,通常 该感知器仅适用于本地调试和试运行 .. Note:: 在读取文件内容后,进行修改文件名的操作,以避免对同一事件的重复调用(重复读取文件)"""
def __init__(self, event_file, query_interval=3, max_queue=10):
"""初始化方法 :param str event_file: 存放事件的文件名 :param float query_interval: 查询事件的时间间隔... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LocalCallbackSensor:
"""从本地文件中获取事件的感知器。该感知器从指定的本地文件中读取事件,模拟感知外部事件,通常 该感知器仅适用于本地调试和试运行 .. Note:: 在读取文件内容后,进行修改文件名的操作,以避免对同一事件的重复调用(重复读取文件)"""
def __init__(self, event_file, query_interval=3, max_queue=10):
"""初始化方法 :param str event_file: 存放事件的文件名 :param float query_interval: 查询事件的时间间隔 :param int m... | the_stack_v2_python_sparse | ark/component/local_sensor.py | meetbill/ARK | train | 2 |
ee86d8c83ca5c38868e0a9261883a8958b742bf9 | [
"super(GloveTokenizer, self).__init__()\nself.embeddings = GloVe(name=name, dim=dim, cache=cache)\nself.text_field = None",
"text_field = Field(batch_first=True, fix_length=fix_length, tokenize=tokenize)\ntab_dats = [TabularDataset(i, format=file_format, fields={k: (k, text_field) for k in fields}) for i in token... | <|body_start_0|>
super(GloveTokenizer, self).__init__()
self.embeddings = GloVe(name=name, dim=dim, cache=cache)
self.text_field = None
<|end_body_0|>
<|body_start_1|>
text_field = Field(batch_first=True, fix_length=fix_length, tokenize=tokenize)
tab_dats = [TabularDataset(i, fo... | Implement GloveTokenizer for tokenizing text for Glove Embeddings. Attributes: embeddings (torchtext.vocab.Vectors): Loaded pre-trained embeddings. text_field (torchtext.data.Field): Text_field for vector creation. Methods: __init__(self, name='840B', dim='300', cache='../embeddings/') : Constructor method initialize_v... | GloveTokenizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GloveTokenizer:
"""Implement GloveTokenizer for tokenizing text for Glove Embeddings. Attributes: embeddings (torchtext.vocab.Vectors): Loaded pre-trained embeddings. text_field (torchtext.data.Field): Text_field for vector creation. Methods: __init__(self, name='840B', dim='300', cache='../embed... | stack_v2_sparse_classes_75kplus_train_068557 | 4,076 | no_license | [
{
"docstring": "Construct GloveTokenizer. Args: name (str): Name of the GloVe embedding file dim (str): Dimensions of the Glove embedding file cache (str): Path to the embeddings directory",
"name": "__init__",
"signature": "def __init__(self, name='840B', dim='300', cache='../embeddings/')"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_037087 | Implement the Python class `GloveTokenizer` described below.
Class description:
Implement GloveTokenizer for tokenizing text for Glove Embeddings. Attributes: embeddings (torchtext.vocab.Vectors): Loaded pre-trained embeddings. text_field (torchtext.data.Field): Text_field for vector creation. Methods: __init__(self, ... | Implement the Python class `GloveTokenizer` described below.
Class description:
Implement GloveTokenizer for tokenizing text for Glove Embeddings. Attributes: embeddings (torchtext.vocab.Vectors): Loaded pre-trained embeddings. text_field (torchtext.data.Field): Text_field for vector creation. Methods: __init__(self, ... | 53c44f92e2683052741d3a6c66c8ced15f1464ed | <|skeleton|>
class GloveTokenizer:
"""Implement GloveTokenizer for tokenizing text for Glove Embeddings. Attributes: embeddings (torchtext.vocab.Vectors): Loaded pre-trained embeddings. text_field (torchtext.data.Field): Text_field for vector creation. Methods: __init__(self, name='840B', dim='300', cache='../embed... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GloveTokenizer:
"""Implement GloveTokenizer for tokenizing text for Glove Embeddings. Attributes: embeddings (torchtext.vocab.Vectors): Loaded pre-trained embeddings. text_field (torchtext.data.Field): Text_field for vector creation. Methods: __init__(self, name='840B', dim='300', cache='../embeddings/') : Co... | the_stack_v2_python_sparse | src/modules/tokenizers.py | abheesht17/ReCAM | train | 0 |
822a6c8c261ef8ae3bd7a52939f437475e93b14f | [
"self.cases_rcut = int(box_size / r_cut)\nself.spacing = box_size / self.cases_rcut\nself.neighbours_grid = {(x, y): [] for x in range(self.cases_rcut) for y in range(self.cases_rcut)}\nfor index in range(len(positions)):\n if (np.abs(positions[index]) > box_size).any():\n continue\n self.neighbours_gr... | <|body_start_0|>
self.cases_rcut = int(box_size / r_cut)
self.spacing = box_size / self.cases_rcut
self.neighbours_grid = {(x, y): [] for x in range(self.cases_rcut) for y in range(self.cases_rcut)}
for index in range(len(positions)):
if (np.abs(positions[index]) > box_size).... | Considering a 2D square box, a grid is built by dividing the box in smaller boxes of length at least equal to r_cut. We call neighbours grid the hash table which keys are 2-uples of indexes of the created grid and which values are lists of the indexes of particles contained in the corresponding boxes. Neighbours grids ... | NeighboursGrid | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeighboursGrid:
"""Considering a 2D square box, a grid is built by dividing the box in smaller boxes of length at least equal to r_cut. We call neighbours grid the hash table which keys are 2-uples of indexes of the created grid and which values are lists of the indexes of particles contained in ... | stack_v2_sparse_classes_75kplus_train_068558 | 3,369 | permissive | [
{
"docstring": "Calculates neighbours grid from particle positions, box size and cut-off radius. Parameters ---------- positions : (N, 2) shaped array Positions of the particles. box_size : float Length of the 2D square box. r_cut : float Cut-off radius.",
"name": "__init__",
"signature": "def __init__(... | 2 | null | Implement the Python class `NeighboursGrid` described below.
Class description:
Considering a 2D square box, a grid is built by dividing the box in smaller boxes of length at least equal to r_cut. We call neighbours grid the hash table which keys are 2-uples of indexes of the created grid and which values are lists of... | Implement the Python class `NeighboursGrid` described below.
Class description:
Considering a 2D square box, a grid is built by dividing the box in smaller boxes of length at least equal to r_cut. We call neighbours grid the hash table which keys are 2-uples of indexes of the created grid and which values are lists of... | b065544639a483dda48cda89bcbb11c1772232aa | <|skeleton|>
class NeighboursGrid:
"""Considering a 2D square box, a grid is built by dividing the box in smaller boxes of length at least equal to r_cut. We call neighbours grid the hash table which keys are 2-uples of indexes of the created grid and which values are lists of the indexes of particles contained in ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeighboursGrid:
"""Considering a 2D square box, a grid is built by dividing the box in smaller boxes of length at least equal to r_cut. We call neighbours grid the hash table which keys are 2-uples of indexes of the created grid and which values are lists of the indexes of particles contained in the correspon... | the_stack_v2_python_sparse | analysis/neighbours.py | interesting-codes/active_particles | train | 0 |
76c6f16aa84d897cb725dfded456fc9a9f473b0c | [
"mid = 0\nwhile low < high:\n mid = low + int((high - low) / 2)\n if nums[mid] < target:\n low = mid + 1\n else:\n high = mid\nreturn low",
"res = []\nfor i in range(N):\n if not res or treasures[i] > res[-1]:\n res.append(treasures[i])\n else:\n idx = self.binary_search... | <|body_start_0|>
mid = 0
while low < high:
mid = low + int((high - low) / 2)
if nums[mid] < target:
low = mid + 1
else:
high = mid
return low
<|end_body_0|>
<|body_start_1|>
res = []
for i in range(N):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def binary_search(self, nums, low, high, target):
"""根据指定的数据寻找相应的位置 @param: nums @param: low @param: high @param: target"""
<|body_0|>
def LIS(self, N, treasures):
"""最长上升子序列 @param: N @param: treasures"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_068559 | 2,565 | no_license | [
{
"docstring": "根据指定的数据寻找相应的位置 @param: nums @param: low @param: high @param: target",
"name": "binary_search",
"signature": "def binary_search(self, nums, low, high, target)"
},
{
"docstring": "最长上升子序列 @param: N @param: treasures",
"name": "LIS",
"signature": "def LIS(self, N, treasures)... | 2 | stack_v2_sparse_classes_30k_train_027704 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binary_search(self, nums, low, high, target): 根据指定的数据寻找相应的位置 @param: nums @param: low @param: high @param: target
- def LIS(self, N, treasures): 最长上升子序列 @param: N @param: tre... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binary_search(self, nums, low, high, target): 根据指定的数据寻找相应的位置 @param: nums @param: low @param: high @param: target
- def LIS(self, N, treasures): 最长上升子序列 @param: N @param: tre... | 32941ee052d0985a9569441d314378700ff4d225 | <|skeleton|>
class Solution:
def binary_search(self, nums, low, high, target):
"""根据指定的数据寻找相应的位置 @param: nums @param: low @param: high @param: target"""
<|body_0|>
def LIS(self, N, treasures):
"""最长上升子序列 @param: N @param: treasures"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def binary_search(self, nums, low, high, target):
"""根据指定的数据寻找相应的位置 @param: nums @param: low @param: high @param: target"""
mid = 0
while low < high:
mid = low + int((high - low) / 2)
if nums[mid] < target:
low = mid + 1
els... | the_stack_v2_python_sparse | cecilia-python/company-title/xiaohongshu/ResellingLoot.py | Cecilia520/algorithmic-learning-leetcode | train | 7 | |
03af4e46b6013cb433ce40a6d99b3ae1beaec82e | [
"args = {'media_type': url[0] if url else None, 'keyword': params.get_string('keyword', u'').split(), 'file_filter': params.get_int('file_filter', None), 'keyword_filter': params.get_string('keyword_filter', u'').split(), 'ordering': params.get_int('ordering', 0), 'since': params.get_int('since', None), 'limit': pa... | <|body_start_0|>
args = {'media_type': url[0] if url else None, 'keyword': params.get_string('keyword', u'').split(), 'file_filter': params.get_int('file_filter', None), 'keyword_filter': params.get_string('keyword_filter', u'').split(), 'ordering': params.get_int('ordering', 0), 'since': params.get_int('since'... | SearchModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchModel:
def _parse_args(self, url, params):
"""Common arguments hanlder. [Arguments] url[0] : string. Search type. keyword : string. Search keyword. file_filter : int string. File filter. keyword_filter : string. Keyword filter. ordering : int. Ordering rule. since : int string. Res... | stack_v2_sparse_classes_75kplus_train_068560 | 4,317 | no_license | [
{
"docstring": "Common arguments hanlder. [Arguments] url[0] : string. Search type. keyword : string. Search keyword. file_filter : int string. File filter. keyword_filter : string. Keyword filter. ordering : int. Ordering rule. since : int string. Response data start from. limit : int string. Number of respons... | 4 | stack_v2_sparse_classes_30k_train_016950 | Implement the Python class `SearchModel` described below.
Class description:
Implement the SearchModel class.
Method signatures and docstrings:
- def _parse_args(self, url, params): Common arguments hanlder. [Arguments] url[0] : string. Search type. keyword : string. Search keyword. file_filter : int string. File fil... | Implement the Python class `SearchModel` described below.
Class description:
Implement the SearchModel class.
Method signatures and docstrings:
- def _parse_args(self, url, params): Common arguments hanlder. [Arguments] url[0] : string. Search type. keyword : string. Search keyword. file_filter : int string. File fil... | cde458ff8f51fcd2840292274906b43bab6f197e | <|skeleton|>
class SearchModel:
def _parse_args(self, url, params):
"""Common arguments hanlder. [Arguments] url[0] : string. Search type. keyword : string. Search keyword. file_filter : int string. File filter. keyword_filter : string. Keyword filter. ordering : int. Ordering rule. since : int string. Res... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SearchModel:
def _parse_args(self, url, params):
"""Common arguments hanlder. [Arguments] url[0] : string. Search type. keyword : string. Search keyword. file_filter : int string. File filter. keyword_filter : string. Keyword filter. ordering : int. Ordering rule. since : int string. Response data sta... | the_stack_v2_python_sparse | api/app_src/apps/main_server/resource/search/search_model.py | codeguycool/CEC | train | 0 | |
2895520e72ab70b2b5b438dc036517858b6d8e96 | [
"err_m1 = 'style_image must be a numpy.ndarray with shape (h, w, 3)'\nerr_m2 = 'content_image must be a numpy.ndarray with shape (h, w, 3)'\nif not isinstance(style_image, np.ndarray):\n raise TypeError(err_m1)\nif len(style_image.shape) != 3 or style_image.shape[2] != 3:\n raise TypeError(err_m1)\nif not isi... | <|body_start_0|>
err_m1 = 'style_image must be a numpy.ndarray with shape (h, w, 3)'
err_m2 = 'content_image must be a numpy.ndarray with shape (h, w, 3)'
if not isinstance(style_image, np.ndarray):
raise TypeError(err_m1)
if len(style_image.shape) != 3 or style_image.shape[2... | Performs task for neural style transfer | NST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NST:
"""Performs task for neural style transfer"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta:... | stack_v2_sparse_classes_75kplus_train_068561 | 2,925 | no_license | [
{
"docstring": "constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta: weight for style cost",
"name": "__init__",
"signature": "def __init__(self, style_image, content_image, alpha=10000.0, beta=1)"... | 2 | stack_v2_sparse_classes_30k_train_042587 | Implement the Python class `NST` described below.
Class description:
Performs task for neural style transfer
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): constructor @style_image: image used as style reference, np.ndarray @content_image: image used as cont... | Implement the Python class `NST` described below.
Class description:
Performs task for neural style transfer
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): constructor @style_image: image used as style reference, np.ndarray @content_image: image used as cont... | e20b284d5f1841952104d7d9a0274cff80eb304d | <|skeleton|>
class NST:
"""Performs task for neural style transfer"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NST:
"""Performs task for neural style transfer"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta: weight for s... | the_stack_v2_python_sparse | supervised_learning/0x0C-neural_style_transfer/0-neural_style.py | jgadelugo/holbertonschool-machine_learning | train | 1 |
46bc55732fbf447fb71fee49af9b4f06932c0ea7 | [
"self.inifile = os.path.abspath(inifile)\nconf = appconfig('config:' + self.inifile)\npylons.config = load_environment(conf.global_conf, conf.local_conf)\nself.config = pylons.config\nself.gpg = GnuPG()",
"if 'debexpo.gpg_keyring' not in self.config:\n print('debexpo.gpg_keyring was not configured or is not wr... | <|body_start_0|>
self.inifile = os.path.abspath(inifile)
conf = appconfig('config:' + self.inifile)
pylons.config = load_environment(conf.global_conf, conf.local_conf)
self.config = pylons.config
self.gpg = GnuPG()
<|end_body_0|>
<|body_start_1|>
if 'debexpo.gpg_keyring'... | UpdateKeyring | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateKeyring:
def __init__(self, inifile):
"""This method does nothing in this cronjob"""
<|body_0|>
def invoke(self):
"""Loops through the debexpo.upload.incoming directory and runs the debexpo.importer for each file"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_068562 | 3,802 | permissive | [
{
"docstring": "This method does nothing in this cronjob",
"name": "__init__",
"signature": "def __init__(self, inifile)"
},
{
"docstring": "Loops through the debexpo.upload.incoming directory and runs the debexpo.importer for each file",
"name": "invoke",
"signature": "def invoke(self)"... | 2 | stack_v2_sparse_classes_30k_test_001582 | Implement the Python class `UpdateKeyring` described below.
Class description:
Implement the UpdateKeyring class.
Method signatures and docstrings:
- def __init__(self, inifile): This method does nothing in this cronjob
- def invoke(self): Loops through the debexpo.upload.incoming directory and runs the debexpo.impor... | Implement the Python class `UpdateKeyring` described below.
Class description:
Implement the UpdateKeyring class.
Method signatures and docstrings:
- def __init__(self, inifile): This method does nothing in this cronjob
- def invoke(self): Loops through the debexpo.upload.incoming directory and runs the debexpo.impor... | 866b0e61726b14425f02e10977398444785337be | <|skeleton|>
class UpdateKeyring:
def __init__(self, inifile):
"""This method does nothing in this cronjob"""
<|body_0|>
def invoke(self):
"""Loops through the debexpo.upload.incoming directory and runs the debexpo.importer for each file"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateKeyring:
def __init__(self, inifile):
"""This method does nothing in this cronjob"""
self.inifile = os.path.abspath(inifile)
conf = appconfig('config:' + self.inifile)
pylons.config = load_environment(conf.global_conf, conf.local_conf)
self.config = pylons.config
... | the_stack_v2_python_sparse | old/bin/key_importer.py | debexpo/debexpo | train | 3 | |
765b8253b24a828ec5bb794779e0f5ad74983783 | [
"try:\n show = series.show_by_id(show_id, session=session)\nexcept NoResultFound:\n return ({'status': 'error', 'message': 'Show with ID %s not found' % show_id}, 404)\ntry:\n episode = series.episode_by_id(ep_id, session)\nexcept NoResultFound:\n return ({'status': 'error', 'message': 'Episode with ID ... | <|body_start_0|>
try:
show = series.show_by_id(show_id, session=session)
except NoResultFound:
return ({'status': 'error', 'message': 'Show with ID %s not found' % show_id}, 404)
try:
episode = series.episode_by_id(ep_id, session)
except NoResultFound:... | SeriesReleasesAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeriesReleasesAPI:
def get(self, show_id, ep_id, session):
"""Get all episodes releases by show ID and episode ID"""
<|body_0|>
def delete(self, show_id, ep_id, session):
"""Deletes all episodes releases by show ID and episode ID"""
<|body_1|>
def put(se... | stack_v2_sparse_classes_75kplus_train_068563 | 36,378 | permissive | [
{
"docstring": "Get all episodes releases by show ID and episode ID",
"name": "get",
"signature": "def get(self, show_id, ep_id, session)"
},
{
"docstring": "Deletes all episodes releases by show ID and episode ID",
"name": "delete",
"signature": "def delete(self, show_id, ep_id, session... | 3 | null | Implement the Python class `SeriesReleasesAPI` described below.
Class description:
Implement the SeriesReleasesAPI class.
Method signatures and docstrings:
- def get(self, show_id, ep_id, session): Get all episodes releases by show ID and episode ID
- def delete(self, show_id, ep_id, session): Deletes all episodes re... | Implement the Python class `SeriesReleasesAPI` described below.
Class description:
Implement the SeriesReleasesAPI class.
Method signatures and docstrings:
- def get(self, show_id, ep_id, session): Get all episodes releases by show ID and episode ID
- def delete(self, show_id, ep_id, session): Deletes all episodes re... | 900bd353a70c5a41176eb505af68ed3fc65a796d | <|skeleton|>
class SeriesReleasesAPI:
def get(self, show_id, ep_id, session):
"""Get all episodes releases by show ID and episode ID"""
<|body_0|>
def delete(self, show_id, ep_id, session):
"""Deletes all episodes releases by show ID and episode ID"""
<|body_1|>
def put(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SeriesReleasesAPI:
def get(self, show_id, ep_id, session):
"""Get all episodes releases by show ID and episode ID"""
try:
show = series.show_by_id(show_id, session=session)
except NoResultFound:
return ({'status': 'error', 'message': 'Show with ID %s not found' ... | the_stack_v2_python_sparse | flexget/plugins/api/series.py | ashumkin/Flexget | train | 1 | |
984e51093a614278403bb7ef16f537131e2d68c2 | [
"self.exception_type = exception_type\n'The type of exception that should be raised.'\nself.text = text\n'The snippet or regex that the exception message must match.'\nself.exception = None\n'The exception that was caught.'\nself.assert_exact_type = assert_exact_type\n'\\n Flag saying whether we require an e... | <|body_start_0|>
self.exception_type = exception_type
'The type of exception that should be raised.'
self.text = text
'The snippet or regex that the exception message must match.'
self.exception = None
'The exception that was caught.'
self.assert_exact_type = asse... | Asserts that a certain exception was raised in the suite. You may use a snippet of text that must appear in the exception message or a regex that the exception message must match. Example: with RaiseAssertor(ZeroDivisionError, 'modulo by zero'): 1/0 | RaiseAssertor | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RaiseAssertor:
"""Asserts that a certain exception was raised in the suite. You may use a snippet of text that must appear in the exception message or a regex that the exception message must match. Example: with RaiseAssertor(ZeroDivisionError, 'modulo by zero'): 1/0"""
def __init__(self, ex... | stack_v2_sparse_classes_75kplus_train_068564 | 6,069 | permissive | [
{
"docstring": "Construct the `RaiseAssertor`. `exception_type` is an exception type that the exception must be of; `text` may be either a snippet of text that must appear in the exception's message, or a regex pattern that the exception message must match. Specify `assert_exact_type=False` if you want to asser... | 2 | stack_v2_sparse_classes_30k_train_043178 | Implement the Python class `RaiseAssertor` described below.
Class description:
Asserts that a certain exception was raised in the suite. You may use a snippet of text that must appear in the exception message or a regex that the exception message must match. Example: with RaiseAssertor(ZeroDivisionError, 'modulo by ze... | Implement the Python class `RaiseAssertor` described below.
Class description:
Asserts that a certain exception was raised in the suite. You may use a snippet of text that must appear in the exception message or a regex that the exception message must match. Example: with RaiseAssertor(ZeroDivisionError, 'modulo by ze... | cb9ef64b48f1d03275484d707dc5079b6701ad0c | <|skeleton|>
class RaiseAssertor:
"""Asserts that a certain exception was raised in the suite. You may use a snippet of text that must appear in the exception message or a regex that the exception message must match. Example: with RaiseAssertor(ZeroDivisionError, 'modulo by zero'): 1/0"""
def __init__(self, ex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RaiseAssertor:
"""Asserts that a certain exception was raised in the suite. You may use a snippet of text that must appear in the exception message or a regex that the exception message must match. Example: with RaiseAssertor(ZeroDivisionError, 'modulo by zero'): 1/0"""
def __init__(self, exception_type=... | the_stack_v2_python_sparse | python_toolbox/cute_testing.py | cool-RR/python_toolbox | train | 130 |
929aa653d83a342be327f24bcc2350f5c6d9b74e | [
"try:\n timestamp = self._ReadStructureFromByteStream(registry_value, 0, self._GetDataTypeMap('filetime'))\nexcept (ValueError, errors.ParseError) as exception:\n raise errors.ParseError('Unable to parse timestamp with error: {0!s}'.format(exception))\nreturn timestamp",
"sid_keys = registry_key.GetSubkeys(... | <|body_start_0|>
try:
timestamp = self._ReadStructureFromByteStream(registry_value, 0, self._GetDataTypeMap('filetime'))
except (ValueError, errors.ParseError) as exception:
raise errors.ParseError('Unable to parse timestamp with error: {0!s}'.format(exception))
return ti... | Background Activity Moderator data Windows Registry plugin. | BackgroundActivityModeratorWindowsRegistryPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackgroundActivityModeratorWindowsRegistryPlugin:
"""Background Activity Moderator data Windows Registry plugin."""
def _ParseValue(self, registry_value):
"""Parses the registry value. Args: registry_value (bytes): value data. Returns: int: timestamp. Raises: ParseError: if the value... | stack_v2_sparse_classes_75kplus_train_068565 | 3,373 | permissive | [
{
"docstring": "Parses the registry value. Args: registry_value (bytes): value data. Returns: int: timestamp. Raises: ParseError: if the value data could not be parsed.",
"name": "_ParseValue",
"signature": "def _ParseValue(self, registry_value)"
},
{
"docstring": "Extracts events from a Windows... | 2 | stack_v2_sparse_classes_30k_train_000760 | Implement the Python class `BackgroundActivityModeratorWindowsRegistryPlugin` described below.
Class description:
Background Activity Moderator data Windows Registry plugin.
Method signatures and docstrings:
- def _ParseValue(self, registry_value): Parses the registry value. Args: registry_value (bytes): value data. ... | Implement the Python class `BackgroundActivityModeratorWindowsRegistryPlugin` described below.
Class description:
Background Activity Moderator data Windows Registry plugin.
Method signatures and docstrings:
- def _ParseValue(self, registry_value): Parses the registry value. Args: registry_value (bytes): value data. ... | c69b2952b608cfce47ff8fd0d1409d856be35cb1 | <|skeleton|>
class BackgroundActivityModeratorWindowsRegistryPlugin:
"""Background Activity Moderator data Windows Registry plugin."""
def _ParseValue(self, registry_value):
"""Parses the registry value. Args: registry_value (bytes): value data. Returns: int: timestamp. Raises: ParseError: if the value... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BackgroundActivityModeratorWindowsRegistryPlugin:
"""Background Activity Moderator data Windows Registry plugin."""
def _ParseValue(self, registry_value):
"""Parses the registry value. Args: registry_value (bytes): value data. Returns: int: timestamp. Raises: ParseError: if the value data could n... | the_stack_v2_python_sparse | plaso/parsers/winreg_plugins/bam.py | cyb3rfox/plaso | train | 3 |
1c76306cbac0863ca58f76cdcc76a9c657d3fa4a | [
"super(Layer, self).__init__()\nself.layer = nn.ModuleList([nn.Linear(num_in, num_out)])\nif norm == 'batch':\n self.layer.append(nn.BatchNorm1d(num_out, affine=AFFINE))\nelif norm == 'layer':\n self.layer.append(nn.LayerNorm(num_out, elementwise_affine=AFFINE))\nelif norm == 'weight':\n self.layer = nn.Mo... | <|body_start_0|>
super(Layer, self).__init__()
self.layer = nn.ModuleList([nn.Linear(num_in, num_out)])
if norm == 'batch':
self.layer.append(nn.BatchNorm1d(num_out, affine=AFFINE))
elif norm == 'layer':
self.layer.append(nn.LayerNorm(num_out, elementwise_affine=A... | Layer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Layer:
def __init__(self, num_in, num_out, dropout=None, norm=None):
""":param num_in: scalar number of input weights. :param num_out: scalar number of output weights. :param dropout: scalar dropout rate. :param norm: string type of normalization."""
<|body_0|>
def forward(s... | stack_v2_sparse_classes_75kplus_train_068566 | 5,028 | permissive | [
{
"docstring": ":param num_in: scalar number of input weights. :param num_out: scalar number of output weights. :param dropout: scalar dropout rate. :param norm: string type of normalization.",
"name": "__init__",
"signature": "def __init__(self, num_in, num_out, dropout=None, norm=None)"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_035300 | Implement the Python class `Layer` described below.
Class description:
Implement the Layer class.
Method signatures and docstrings:
- def __init__(self, num_in, num_out, dropout=None, norm=None): :param num_in: scalar number of input weights. :param num_out: scalar number of output weights. :param dropout: scalar dro... | Implement the Python class `Layer` described below.
Class description:
Implement the Layer class.
Method signatures and docstrings:
- def __init__(self, num_in, num_out, dropout=None, norm=None): :param num_in: scalar number of input weights. :param num_out: scalar number of output weights. :param dropout: scalar dro... | b40e9b147186ca04efd384d05b0f5e27ff8bd71a | <|skeleton|>
class Layer:
def __init__(self, num_in, num_out, dropout=None, norm=None):
""":param num_in: scalar number of input weights. :param num_out: scalar number of output weights. :param dropout: scalar dropout rate. :param norm: string type of normalization."""
<|body_0|>
def forward(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Layer:
def __init__(self, num_in, num_out, dropout=None, norm=None):
""":param num_in: scalar number of input weights. :param num_out: scalar number of output weights. :param dropout: scalar dropout rate. :param norm: string type of normalization."""
super(Layer, self).__init__()
self.... | the_stack_v2_python_sparse | nets/util.py | yuwei-cheng/eBay | train | 0 | |
549db5b6fa5f9904e3e95f8d1199386e6f8a64ee | [
"self.__dict__['FILEORHASH'] = {'value': FILEORHASH, 'required': True, 'description': 'File to verify'}\nself.__dict__['APIKEY'] = {'value': APIKEY, 'required': True, 'description': 'VT API key'}\nself.__dict__['REPORT'] = {'value': REPORT, 'required': False, 'description': 'Return report for File or MD5'}\nself.__... | <|body_start_0|>
self.__dict__['FILEORHASH'] = {'value': FILEORHASH, 'required': True, 'description': 'File to verify'}
self.__dict__['APIKEY'] = {'value': APIKEY, 'required': True, 'description': 'VT API key'}
self.__dict__['REPORT'] = {'value': REPORT, 'required': False, 'description': 'Return... | Module Class | Module | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Module:
"""Module Class"""
def __init__(self, FILEORHASH=None, REPORT=False, JSON=False, DOWNLOAD=False, PCAP=False, VERBOSE=False, RESCAN=False, APIKEY=None):
"""__init__(self, FILEORHASH=None, REPORT=False, JSON=False, DOWNLOAD=False, PCAP=False, VERBOSE=False, RESCAN=False,APIKEY=... | stack_v2_sparse_classes_75kplus_train_068567 | 7,816 | no_license | [
{
"docstring": "__init__(self, FILEORHASH=None, REPORT=False, JSON=False, DOWNLOAD=False, PCAP=False, VERBOSE=False, RESCAN=False,APIKEY=None) :param FILEORHASH: :param REPORT: :param JSON: :param DOWNLOAD: :param PCAP: :param VERBOSE: :param RESCAN: :param APIKEY: Initialize the module with the module's desire... | 2 | stack_v2_sparse_classes_30k_test_001707 | Implement the Python class `Module` described below.
Class description:
Module Class
Method signatures and docstrings:
- def __init__(self, FILEORHASH=None, REPORT=False, JSON=False, DOWNLOAD=False, PCAP=False, VERBOSE=False, RESCAN=False, APIKEY=None): __init__(self, FILEORHASH=None, REPORT=False, JSON=False, DOWNLO... | Implement the Python class `Module` described below.
Class description:
Module Class
Method signatures and docstrings:
- def __init__(self, FILEORHASH=None, REPORT=False, JSON=False, DOWNLOAD=False, PCAP=False, VERBOSE=False, RESCAN=False, APIKEY=None): __init__(self, FILEORHASH=None, REPORT=False, JSON=False, DOWNLO... | 99e1d75b3d1af2e44740584be6c2ef1c1601c43c | <|skeleton|>
class Module:
"""Module Class"""
def __init__(self, FILEORHASH=None, REPORT=False, JSON=False, DOWNLOAD=False, PCAP=False, VERBOSE=False, RESCAN=False, APIKEY=None):
"""__init__(self, FILEORHASH=None, REPORT=False, JSON=False, DOWNLOAD=False, PCAP=False, VERBOSE=False, RESCAN=False,APIKEY=... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Module:
"""Module Class"""
def __init__(self, FILEORHASH=None, REPORT=False, JSON=False, DOWNLOAD=False, PCAP=False, VERBOSE=False, RESCAN=False, APIKEY=None):
"""__init__(self, FILEORHASH=None, REPORT=False, JSON=False, DOWNLOAD=False, PCAP=False, VERBOSE=False, RESCAN=False,APIKEY=None) :param ... | the_stack_v2_python_sparse | modules/intel/virus_total.py | h4cklife/intrukit | train | 3 |
4a8d3712c7e70825908a86ad91a77ead39b9b306 | [
"for _ in range(NUM_TESTS):\n start = random.randint(1, sys.maxint - 1)\n end = random.randint(start + 1, sys.maxint)\n spec = 'flag=[%s-%s]' % (start, end)\n test_flag = Flag(spec)\n value = test_flag.GetValue()\n assert start <= value and value < end",
"tests = range(NUM_TESTS)\nfor test in te... | <|body_start_0|>
for _ in range(NUM_TESTS):
start = random.randint(1, sys.maxint - 1)
end = random.randint(start + 1, sys.maxint)
spec = 'flag=[%s-%s]' % (start, end)
test_flag = Flag(spec)
value = test_flag.GetValue()
assert start <= value... | This class tests the Flag class. | FlagTest | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlagTest:
"""This class tests the Flag class."""
def testInit(self):
"""The value generated should fall within start and end of the spec. If the value is not specified, the value generated should fall within start and end of the spec."""
<|body_0|>
def testEqual(self):
... | stack_v2_sparse_classes_75kplus_train_068568 | 5,329 | permissive | [
{
"docstring": "The value generated should fall within start and end of the spec. If the value is not specified, the value generated should fall within start and end of the spec.",
"name": "testInit",
"signature": "def testInit(self)"
},
{
"docstring": "Test the equal operator (==) of the flag. ... | 3 | null | Implement the Python class `FlagTest` described below.
Class description:
This class tests the Flag class.
Method signatures and docstrings:
- def testInit(self): The value generated should fall within start and end of the spec. If the value is not specified, the value generated should fall within start and end of th... | Implement the Python class `FlagTest` described below.
Class description:
This class tests the Flag class.
Method signatures and docstrings:
- def testInit(self): The value generated should fall within start and end of the spec. If the value is not specified, the value generated should fall within start and end of th... | e2745b756317aac3c7a27a4c10bdfe0921a82a1c | <|skeleton|>
class FlagTest:
"""This class tests the Flag class."""
def testInit(self):
"""The value generated should fall within start and end of the spec. If the value is not specified, the value generated should fall within start and end of the spec."""
<|body_0|>
def testEqual(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FlagTest:
"""This class tests the Flag class."""
def testInit(self):
"""The value generated should fall within start and end of the spec. If the value is not specified, the value generated should fall within start and end of the spec."""
for _ in range(NUM_TESTS):
start = rand... | the_stack_v2_python_sparse | app/src/main/java/com/syd/source/aosp/external/toolchain-utils/bestflags/flags_test.py | lz-purple/Source | train | 4 |
f20f0af2f9ca6055ceea9018f6b906a10c7a6fb9 | [
"self.sign_request = sign_request\nself.reminder = reminder\nself.signature_receipt = signature_receipt\nself.final_receipt = final_receipt\nself.canceled_receipt = canceled_receipt\nself.expired_receipt = expired_receipt\nself.additional_properties = additional_properties",
"if dictionary is None:\n return No... | <|body_start_0|>
self.sign_request = sign_request
self.reminder = reminder
self.signature_receipt = signature_receipt
self.final_receipt = final_receipt
self.canceled_receipt = canceled_receipt
self.expired_receipt = expired_receipt
self.additional_properties = ad... | Implementation of the 'Notification' model. Setup your own notification texts, and specify specail settings. Info: you also has to setup notifications on the signers you want to notify. Attributes: sign_request (SignatureSignRequest): Here you can setup email/sms notifications notifying the signer that they have a new ... | Notification | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Notification:
"""Implementation of the 'Notification' model. Setup your own notification texts, and specify specail settings. Info: you also has to setup notifications on the signers you want to notify. Attributes: sign_request (SignatureSignRequest): Here you can setup email/sms notifications no... | stack_v2_sparse_classes_75kplus_train_068569 | 5,007 | permissive | [
{
"docstring": "Constructor for the Notification class",
"name": "__init__",
"signature": "def __init__(self, sign_request=None, reminder=None, signature_receipt=None, final_receipt=None, canceled_receipt=None, expired_receipt=None, additional_properties={})"
},
{
"docstring": "Creates an instan... | 2 | stack_v2_sparse_classes_30k_test_002517 | Implement the Python class `Notification` described below.
Class description:
Implementation of the 'Notification' model. Setup your own notification texts, and specify specail settings. Info: you also has to setup notifications on the signers you want to notify. Attributes: sign_request (SignatureSignRequest): Here y... | Implement the Python class `Notification` described below.
Class description:
Implementation of the 'Notification' model. Setup your own notification texts, and specify specail settings. Info: you also has to setup notifications on the signers you want to notify. Attributes: sign_request (SignatureSignRequest): Here y... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class Notification:
"""Implementation of the 'Notification' model. Setup your own notification texts, and specify specail settings. Info: you also has to setup notifications on the signers you want to notify. Attributes: sign_request (SignatureSignRequest): Here you can setup email/sms notifications no... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Notification:
"""Implementation of the 'Notification' model. Setup your own notification texts, and specify specail settings. Info: you also has to setup notifications on the signers you want to notify. Attributes: sign_request (SignatureSignRequest): Here you can setup email/sms notifications notifying the s... | the_stack_v2_python_sparse | idfy_rest_client/models/notification.py | dealflowteam/Idfy | train | 0 |
1cbaf49c3c24fc4d8f0643b0f314117f4d03fb55 | [
"xmpp.commands.Command_Handler_Prototype.__init__(self, config.jid)\nself.initial = {'execute': self.cmdFirstStage}\nself.userfile = userfile",
"if request.getFrom().getStripped() in config.admins:\n return xmpp.commands.Command_Handler_Prototype._DiscoHandler(self, conn, request, type)\nelse:\n return None... | <|body_start_0|>
xmpp.commands.Command_Handler_Prototype.__init__(self, config.jid)
self.initial = {'execute': self.cmdFirstStage}
self.userfile = userfile
<|end_body_0|>
<|body_start_1|>
if request.getFrom().getStripped() in config.admins:
return xmpp.commands.Command_Handl... | This is the | Connect_Registered_Users_Command | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Connect_Registered_Users_Command:
"""This is the"""
def __init__(self, userfile):
"""Initialise the command object"""
<|body_0|>
def _DiscoHandler(self, conn, request, type):
"""The handler for discovery events"""
<|body_1|>
def cmdFirstStage(self, c... | stack_v2_sparse_classes_75kplus_train_068570 | 3,197 | no_license | [
{
"docstring": "Initialise the command object",
"name": "__init__",
"signature": "def __init__(self, userfile)"
},
{
"docstring": "The handler for discovery events",
"name": "_DiscoHandler",
"signature": "def _DiscoHandler(self, conn, request, type)"
},
{
"docstring": "Build the ... | 3 | stack_v2_sparse_classes_30k_train_010625 | Implement the Python class `Connect_Registered_Users_Command` described below.
Class description:
This is the
Method signatures and docstrings:
- def __init__(self, userfile): Initialise the command object
- def _DiscoHandler(self, conn, request, type): The handler for discovery events
- def cmdFirstStage(self, conn,... | Implement the Python class `Connect_Registered_Users_Command` described below.
Class description:
This is the
Method signatures and docstrings:
- def __init__(self, userfile): Initialise the command object
- def _DiscoHandler(self, conn, request, type): The handler for discovery events
- def cmdFirstStage(self, conn,... | 6ca26a21471df24e017dd91cc1a85297d480ba24 | <|skeleton|>
class Connect_Registered_Users_Command:
"""This is the"""
def __init__(self, userfile):
"""Initialise the command object"""
<|body_0|>
def _DiscoHandler(self, conn, request, type):
"""The handler for discovery events"""
<|body_1|>
def cmdFirstStage(self, c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Connect_Registered_Users_Command:
"""This is the"""
def __init__(self, userfile):
"""Initialise the command object"""
xmpp.commands.Command_Handler_Prototype.__init__(self, config.jid)
self.initial = {'execute': self.cmdFirstStage}
self.userfile = userfile
def _DiscoH... | the_stack_v2_python_sparse | transports/yahoo-transport-0.4/adhoc.py | jtolio/yakalope | train | 0 |
a2f98dda3e61d5801a54a1d1039c77a5c4bdf45e | [
"self.screen = screen\nself.menuNode = pokemonMenuNode\nself.party = party\nself.currentPoke = startPoke\nself.currentPage = 0\nself.loadPokemon()\nself.loadPage()\nself.busy = True",
"self.poke = self.party[self.currentPoke]\nspeciesNode = self.poke.speciesNode\nmainNode = data.getChild(self.menuNode, 'main')\nf... | <|body_start_0|>
self.screen = screen
self.menuNode = pokemonMenuNode
self.party = party
self.currentPoke = startPoke
self.currentPage = 0
self.loadPokemon()
self.loadPage()
self.busy = True
<|end_body_0|>
<|body_start_1|>
self.poke = self.party[s... | The pokemon summary screen object. | PokemonScreen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PokemonScreen:
"""The pokemon summary screen object."""
def __init__(self, screen, pokemonMenuNode, party, startPoke):
"""Create the summary screen, starting on the info page of the requested pokemon. screen - the surface to blit to. pokemonMenuNode - the <pokemon> menu node. party -... | stack_v2_sparse_classes_75kplus_train_068571 | 8,997 | no_license | [
{
"docstring": "Create the summary screen, starting on the info page of the requested pokemon. screen - the surface to blit to. pokemonMenuNode - the <pokemon> menu node. party - the party to summarize. currentPoke - the index of the pokemon to show first.",
"name": "__init__",
"signature": "def __init_... | 5 | stack_v2_sparse_classes_30k_train_003784 | Implement the Python class `PokemonScreen` described below.
Class description:
The pokemon summary screen object.
Method signatures and docstrings:
- def __init__(self, screen, pokemonMenuNode, party, startPoke): Create the summary screen, starting on the info page of the requested pokemon. screen - the surface to bl... | Implement the Python class `PokemonScreen` described below.
Class description:
The pokemon summary screen object.
Method signatures and docstrings:
- def __init__(self, screen, pokemonMenuNode, party, startPoke): Create the summary screen, starting on the info page of the requested pokemon. screen - the surface to bl... | 35f58b9c931bd2bef7fd2002cadd468523ffbb5d | <|skeleton|>
class PokemonScreen:
"""The pokemon summary screen object."""
def __init__(self, screen, pokemonMenuNode, party, startPoke):
"""Create the summary screen, starting on the info page of the requested pokemon. screen - the surface to blit to. pokemonMenuNode - the <pokemon> menu node. party -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PokemonScreen:
"""The pokemon summary screen object."""
def __init__(self, screen, pokemonMenuNode, party, startPoke):
"""Create the summary screen, starting on the info page of the requested pokemon. screen - the surface to blit to. pokemonMenuNode - the <pokemon> menu node. party - the party to... | the_stack_v2_python_sparse | pokemon_screen.py | wollywatson/DittoEngine | train | 0 |
79db15fcb03d1cebf77527ffe82555650ef1df3b | [
"if not update:\n self.reset_vectors(sv, total_sentences)\nelse:\n self.update_vectors(sv, total_sentences)",
"logger.info(f'initializing sentence vectors for {total_sentences} sentences')\nif sv.mapfile_path:\n sv.vectors = np_memmap(str(sv.mapfile_path) + '.vectors', dtype=REAL, mode='w+', shape=(total... | <|body_start_0|>
if not update:
self.reset_vectors(sv, total_sentences)
else:
self.update_vectors(sv, total_sentences)
<|end_body_0|>
<|body_start_1|>
logger.info(f'initializing sentence vectors for {total_sentences} sentences')
if sv.mapfile_path:
sv... | Contains helper functions to perpare the weights for the training of BaseSentence2VecModel | BaseSentence2VecPreparer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseSentence2VecPreparer:
"""Contains helper functions to perpare the weights for the training of BaseSentence2VecModel"""
def prepare_vectors(self, sv: SentenceVectors, total_sentences: int, update: bool=False):
"""Build tables and model weights based on final vocabulary settings.""... | stack_v2_sparse_classes_75kplus_train_068572 | 36,649 | no_license | [
{
"docstring": "Build tables and model weights based on final vocabulary settings.",
"name": "prepare_vectors",
"signature": "def prepare_vectors(self, sv: SentenceVectors, total_sentences: int, update: bool=False)"
},
{
"docstring": "Initialize all sentence vectors to zero and overwrite existin... | 3 | stack_v2_sparse_classes_30k_train_020155 | Implement the Python class `BaseSentence2VecPreparer` described below.
Class description:
Contains helper functions to perpare the weights for the training of BaseSentence2VecModel
Method signatures and docstrings:
- def prepare_vectors(self, sv: SentenceVectors, total_sentences: int, update: bool=False): Build table... | Implement the Python class `BaseSentence2VecPreparer` described below.
Class description:
Contains helper functions to perpare the weights for the training of BaseSentence2VecModel
Method signatures and docstrings:
- def prepare_vectors(self, sv: SentenceVectors, total_sentences: int, update: bool=False): Build table... | c5e948aedd325593d81e2dfe7ce096eaf9fc3ae1 | <|skeleton|>
class BaseSentence2VecPreparer:
"""Contains helper functions to perpare the weights for the training of BaseSentence2VecModel"""
def prepare_vectors(self, sv: SentenceVectors, total_sentences: int, update: bool=False):
"""Build tables and model weights based on final vocabulary settings.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseSentence2VecPreparer:
"""Contains helper functions to perpare the weights for the training of BaseSentence2VecModel"""
def prepare_vectors(self, sv: SentenceVectors, total_sentences: int, update: bool=False):
"""Build tables and model weights based on final vocabulary settings."""
if ... | the_stack_v2_python_sparse | retrieval_model/fse/models/base_s2v.py | SCNUJackyChen/Concept-Linking-on-MIMIC-III | train | 1 |
880ecc1de1f3e5a4ed2709dd93305d8dc68caf68 | [
"project_name = 'project_does_not_exist'\nbase_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)))\nproject_dir = os.path.basename(base_dir)\nself.assertNotEqual(project_dir, project_name)",
"base_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)))\nproject_dir = os.path.basename(base_dir)... | <|body_start_0|>
project_name = 'project_does_not_exist'
base_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)))
project_dir = os.path.basename(base_dir)
self.assertNotEqual(project_dir, project_name)
<|end_body_0|>
<|body_start_1|>
base_dir = os.path.join(os.path.d... | TestWSGI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestWSGI:
def test_wsgi_settings_not_found(self):
"""Override project name, this test should fail."""
<|body_0|>
def test_wsgi_settings_exist(self):
"""Use project_name from .wsgi."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
project_name = 'proj... | stack_v2_sparse_classes_75kplus_train_068573 | 727 | permissive | [
{
"docstring": "Override project name, this test should fail.",
"name": "test_wsgi_settings_not_found",
"signature": "def test_wsgi_settings_not_found(self)"
},
{
"docstring": "Use project_name from .wsgi.",
"name": "test_wsgi_settings_exist",
"signature": "def test_wsgi_settings_exist(s... | 2 | stack_v2_sparse_classes_30k_train_042406 | Implement the Python class `TestWSGI` described below.
Class description:
Implement the TestWSGI class.
Method signatures and docstrings:
- def test_wsgi_settings_not_found(self): Override project name, this test should fail.
- def test_wsgi_settings_exist(self): Use project_name from .wsgi. | Implement the Python class `TestWSGI` described below.
Class description:
Implement the TestWSGI class.
Method signatures and docstrings:
- def test_wsgi_settings_not_found(self): Override project name, this test should fail.
- def test_wsgi_settings_exist(self): Use project_name from .wsgi.
<|skeleton|>
class TestW... | 450be55e82496ef4aeec0a0794708cb82c7cb26c | <|skeleton|>
class TestWSGI:
def test_wsgi_settings_not_found(self):
"""Override project name, this test should fail."""
<|body_0|>
def test_wsgi_settings_exist(self):
"""Use project_name from .wsgi."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestWSGI:
def test_wsgi_settings_not_found(self):
"""Override project name, this test should fail."""
project_name = 'project_does_not_exist'
base_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)))
project_dir = os.path.basename(base_dir)
self.assertNotEqua... | the_stack_v2_python_sparse | mysite/test_wsgi.py | daisycrego/mercury-telemetry | train | 1 | |
08df523706898d31ef481f0a65f75dc3e02b8f24 | [
"self.n = n / 2\na = math.tan(math.pi * fc / fs)\na2 = a * a\nself.A = [0.0] * self.n\nself.d1 = [0.0] * self.n\nself.d2 = [0.0] * self.n\nself.w0 = [0.0] * self.n\nself.w1 = [0.0] * self.n\nself.w2 = [0.0] * self.n\nr = 0.0\nfor i in range(self.n):\n r = math.sin(math.pi * (2.0 * float(i) + 1.0) / (4.0 * float(... | <|body_start_0|>
self.n = n / 2
a = math.tan(math.pi * fc / fs)
a2 = a * a
self.A = [0.0] * self.n
self.d1 = [0.0] * self.n
self.d2 = [0.0] * self.n
self.w0 = [0.0] * self.n
self.w1 = [0.0] * self.n
self.w2 = [0.0] * self.n
r = 0.0
... | Butterworth | [
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Butterworth:
def __init__(self, n, fs, fc):
"""Butterworth Filter. See: U{http://www.exstrom.com/journal/sigproc/} Hollos, Stefan and Hollos, J. Richard, "Recursive Digital Filters: A Concise Guise", Exstrom Laboratories, LLC, Longmont, CO, USA April, 2014 ISBN 9781887187244 (ebook) URL:... | stack_v2_sparse_classes_75kplus_train_068574 | 1,928 | permissive | [
{
"docstring": "Butterworth Filter. See: U{http://www.exstrom.com/journal/sigproc/} Hollos, Stefan and Hollos, J. Richard, \"Recursive Digital Filters: A Concise Guise\", Exstrom Laboratories, LLC, Longmont, CO, USA April, 2014 ISBN 9781887187244 (ebook) URL: http://www.abrazol.com/books/filter1/ @param n: @par... | 2 | stack_v2_sparse_classes_30k_train_013902 | Implement the Python class `Butterworth` described below.
Class description:
Implement the Butterworth class.
Method signatures and docstrings:
- def __init__(self, n, fs, fc): Butterworth Filter. See: U{http://www.exstrom.com/journal/sigproc/} Hollos, Stefan and Hollos, J. Richard, "Recursive Digital Filters: A Conc... | Implement the Python class `Butterworth` described below.
Class description:
Implement the Butterworth class.
Method signatures and docstrings:
- def __init__(self, n, fs, fc): Butterworth Filter. See: U{http://www.exstrom.com/journal/sigproc/} Hollos, Stefan and Hollos, J. Richard, "Recursive Digital Filters: A Conc... | 6e4b569819ff0b2aede33dc1752ca6bd4d00c4c7 | <|skeleton|>
class Butterworth:
def __init__(self, n, fs, fc):
"""Butterworth Filter. See: U{http://www.exstrom.com/journal/sigproc/} Hollos, Stefan and Hollos, J. Richard, "Recursive Digital Filters: A Concise Guise", Exstrom Laboratories, LLC, Longmont, CO, USA April, 2014 ISBN 9781887187244 (ebook) URL:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Butterworth:
def __init__(self, n, fs, fc):
"""Butterworth Filter. See: U{http://www.exstrom.com/journal/sigproc/} Hollos, Stefan and Hollos, J. Richard, "Recursive Digital Filters: A Concise Guise", Exstrom Laboratories, LLC, Longmont, CO, USA April, 2014 ISBN 9781887187244 (ebook) URL: http://www.ab... | the_stack_v2_python_sparse | archived/projects/eyetracking/pipeline/butterworth.py | nirdslab/streaminghub | train | 2 | |
67acc2cb107c201069897ac6ded3e7457fe4e046 | [
"username = kwargs.get('user')\ncached_org = cache.get(f'{ORG_PROFILE_CACHE}{username}')\nif cached_org:\n return Response(cached_org)\nresponse = super().retrieve(request, *args, **kwargs)\ncache.set(f'{ORG_PROFILE_CACHE}{username}', response.data)\nreturn response",
"response = super().create(request, *args,... | <|body_start_0|>
username = kwargs.get('user')
cached_org = cache.get(f'{ORG_PROFILE_CACHE}{username}')
if cached_org:
return Response(cached_org)
response = super().retrieve(request, *args, **kwargs)
cache.set(f'{ORG_PROFILE_CACHE}{username}', response.data)
... | List, Retrieve, Update, Create/Register Organizations. | OrganizationProfileViewSet | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationProfileViewSet:
"""List, Retrieve, Update, Create/Register Organizations."""
def retrieve(self, request, *args, **kwargs):
"""Get organization from cache or db"""
<|body_0|>
def create(self, request, *args, **kwargs):
"""Create and cache organization"... | stack_v2_sparse_classes_75kplus_train_068575 | 4,869 | permissive | [
{
"docstring": "Get organization from cache or db",
"name": "retrieve",
"signature": "def retrieve(self, request, *args, **kwargs)"
},
{
"docstring": "Create and cache organization",
"name": "create",
"signature": "def create(self, request, *args, **kwargs)"
},
{
"docstring": "Cl... | 5 | stack_v2_sparse_classes_30k_train_048963 | Implement the Python class `OrganizationProfileViewSet` described below.
Class description:
List, Retrieve, Update, Create/Register Organizations.
Method signatures and docstrings:
- def retrieve(self, request, *args, **kwargs): Get organization from cache or db
- def create(self, request, *args, **kwargs): Create an... | Implement the Python class `OrganizationProfileViewSet` described below.
Class description:
List, Retrieve, Update, Create/Register Organizations.
Method signatures and docstrings:
- def retrieve(self, request, *args, **kwargs): Get organization from cache or db
- def create(self, request, *args, **kwargs): Create an... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class OrganizationProfileViewSet:
"""List, Retrieve, Update, Create/Register Organizations."""
def retrieve(self, request, *args, **kwargs):
"""Get organization from cache or db"""
<|body_0|>
def create(self, request, *args, **kwargs):
"""Create and cache organization"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrganizationProfileViewSet:
"""List, Retrieve, Update, Create/Register Organizations."""
def retrieve(self, request, *args, **kwargs):
"""Get organization from cache or db"""
username = kwargs.get('user')
cached_org = cache.get(f'{ORG_PROFILE_CACHE}{username}')
if cached_o... | the_stack_v2_python_sparse | onadata/apps/api/viewsets/organization_profile_viewset.py | onaio/onadata | train | 177 |
ef02babe5878a7737cc5671d53e693ee690383d3 | [
"if pattern.islower():\n val = val.lower()\npattern = unidecode(pattern)\nval = unidecode(val)\nreturn pattern in val",
"clause = f'unidecode({self.field})'\nif self.pattern.islower():\n clause = f'lower({clause})'\nreturn (f\"{clause} LIKE ? ESCAPE '\\\\'\", [f'%{unidecode(self.pattern)}%'])"
] | <|body_start_0|>
if pattern.islower():
val = val.lower()
pattern = unidecode(pattern)
val = unidecode(val)
return pattern in val
<|end_body_0|>
<|body_start_1|>
clause = f'unidecode({self.field})'
if self.pattern.islower():
clause = f'lower({claus... | Compare items using bare ASCII, without accents etc. | BareascQuery | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BareascQuery:
"""Compare items using bare ASCII, without accents etc."""
def string_match(cls, pattern, val):
"""Convert both pattern and string to plain ASCII before matching. If pattern is all lower case, also convert string to lower case so match is also case insensitive"""
... | stack_v2_sparse_classes_75kplus_train_068576 | 3,145 | permissive | [
{
"docstring": "Convert both pattern and string to plain ASCII before matching. If pattern is all lower case, also convert string to lower case so match is also case insensitive",
"name": "string_match",
"signature": "def string_match(cls, pattern, val)"
},
{
"docstring": "Compare ascii version ... | 2 | stack_v2_sparse_classes_30k_train_051664 | Implement the Python class `BareascQuery` described below.
Class description:
Compare items using bare ASCII, without accents etc.
Method signatures and docstrings:
- def string_match(cls, pattern, val): Convert both pattern and string to plain ASCII before matching. If pattern is all lower case, also convert string ... | Implement the Python class `BareascQuery` described below.
Class description:
Compare items using bare ASCII, without accents etc.
Method signatures and docstrings:
- def string_match(cls, pattern, val): Convert both pattern and string to plain ASCII before matching. If pattern is all lower case, also convert string ... | 0e5ade4f711dbf563d35c290affb0254eee41235 | <|skeleton|>
class BareascQuery:
"""Compare items using bare ASCII, without accents etc."""
def string_match(cls, pattern, val):
"""Convert both pattern and string to plain ASCII before matching. If pattern is all lower case, also convert string to lower case so match is also case insensitive"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BareascQuery:
"""Compare items using bare ASCII, without accents etc."""
def string_match(cls, pattern, val):
"""Convert both pattern and string to plain ASCII before matching. If pattern is all lower case, also convert string to lower case so match is also case insensitive"""
if pattern.... | the_stack_v2_python_sparse | beetsplug/bareasc.py | beetbox/beets | train | 8,977 |
185ba6894ea91cda94e50b7bbb4f2c71af57f4fa | [
"h5py.File.__init__(self, photo_file, 'r')\nself.filtersystems = self.keys()\nself.filtersystems.remove('ini_file')\nself.ccds = [key for key in self[self.filtersystems[0]].keys()]",
"log = logger(__name__)\nif fsys in self.filtersystems:\n self.ccd = ccd\n self.fsys = fsys\n self.data = self['/%s/%s/dat... | <|body_start_0|>
h5py.File.__init__(self, photo_file, 'r')
self.filtersystems = self.keys()
self.filtersystems.remove('ini_file')
self.ccds = [key for key in self[self.filtersystems[0]].keys()]
<|end_body_0|>
<|body_start_1|>
log = logger(__name__)
if fsys in self.filter... | Reads a .hdf5 Input photometry file. | Input | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Input:
"""Reads a .hdf5 Input photometry file."""
def __init__(self, photo_file):
"""Reads a.hdf5 input photometry file. Parameters ---------- photo_file: string Photometry input file."""
<|body_0|>
def get_filtersys(self, fsys, ccd):
"""Select a filter system an... | stack_v2_sparse_classes_75kplus_train_068577 | 1,829 | no_license | [
{
"docstring": "Reads a.hdf5 input photometry file. Parameters ---------- photo_file: string Photometry input file.",
"name": "__init__",
"signature": "def __init__(self, photo_file)"
},
{
"docstring": "Select a filter system and a ccd on the inputfile. Will raise an exception if ccd or filtersy... | 2 | stack_v2_sparse_classes_30k_train_015989 | Implement the Python class `Input` described below.
Class description:
Reads a .hdf5 Input photometry file.
Method signatures and docstrings:
- def __init__(self, photo_file): Reads a.hdf5 input photometry file. Parameters ---------- photo_file: string Photometry input file.
- def get_filtersys(self, fsys, ccd): Sele... | Implement the Python class `Input` described below.
Class description:
Reads a .hdf5 Input photometry file.
Method signatures and docstrings:
- def __init__(self, photo_file): Reads a.hdf5 input photometry file. Parameters ---------- photo_file: string Photometry input file.
- def get_filtersys(self, fsys, ccd): Sele... | 90083c46bedcb8b03a3411a4661a8990a2ef4d8c | <|skeleton|>
class Input:
"""Reads a .hdf5 Input photometry file."""
def __init__(self, photo_file):
"""Reads a.hdf5 input photometry file. Parameters ---------- photo_file: string Photometry input file."""
<|body_0|>
def get_filtersys(self, fsys, ccd):
"""Select a filter system an... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Input:
"""Reads a .hdf5 Input photometry file."""
def __init__(self, photo_file):
"""Reads a.hdf5 input photometry file. Parameters ---------- photo_file: string Photometry input file."""
h5py.File.__init__(self, photo_file, 'r')
self.filtersystems = self.keys()
self.filte... | the_stack_v2_python_sparse | src/magal/io/readinput.py | wschoenell/magal | train | 0 |
35ce505d9abbc2926d4ea59da3b1b58ac65d3ac4 | [
"bin_path = '/home/cephuser/venv/bin/'\nself.prefix = bin_path + 's3cmd'\nif options is None:\n options = []\nself.operation = operation\nself.options = ' '.join(options)",
"if params is None:\n params = []\ncommand_list = [self.prefix, self.options, self.operation] + params\ncmd = list(filter(lambda cmd: l... | <|body_start_0|>
bin_path = '/home/cephuser/venv/bin/'
self.prefix = bin_path + 's3cmd'
if options is None:
options = []
self.operation = operation
self.options = ' '.join(options)
<|end_body_0|>
<|body_start_1|>
if params is None:
params = []
... | S3CMD | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3CMD:
def __init__(self, operation, options=None):
"""Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command"""
<|body_0|>
def command(self, params=None):
"""Args: params(list): list of params... | stack_v2_sparse_classes_75kplus_train_068578 | 1,012 | permissive | [
{
"docstring": "Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command",
"name": "__init__",
"signature": "def __init__(self, operation, options=None)"
},
{
"docstring": "Args: params(list): list of params to be passed in ... | 2 | stack_v2_sparse_classes_30k_train_037261 | Implement the Python class `S3CMD` described below.
Class description:
Implement the S3CMD class.
Method signatures and docstrings:
- def __init__(self, operation, options=None): Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command
- def comm... | Implement the Python class `S3CMD` described below.
Class description:
Implement the S3CMD class.
Method signatures and docstrings:
- def __init__(self, operation, options=None): Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command
- def comm... | 4c3b9b3e8e7f42d43270a9b79299a8b404a76046 | <|skeleton|>
class S3CMD:
def __init__(self, operation, options=None):
"""Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command"""
<|body_0|>
def command(self, params=None):
"""Args: params(list): list of params... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class S3CMD:
def __init__(self, operation, options=None):
"""Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command"""
bin_path = '/home/cephuser/venv/bin/'
self.prefix = bin_path + 's3cmd'
if options is None:
... | the_stack_v2_python_sparse | rgw/v2/lib/s3cmd/resource_op.py | red-hat-storage/ceph-qe-scripts | train | 9 | |
2fb505d5feba4d69aa1544ff9574cb5e10ea6d17 | [
"super().__init__()\nself.embeddings = nn.ModuleDict()\nself.attributes = nn.ModuleDict()\nfor _, entity in stimulus.Static:\n continuous = len([e for e in entity if e[1].CONTINUOUS])\n discrete = len([e for e in entity if e[1].DISCRETE])\n self.attributes[entity.__name__] = nn.Linear((continuous + discret... | <|body_start_0|>
super().__init__()
self.embeddings = nn.ModuleDict()
self.attributes = nn.ModuleDict()
for _, entity in stimulus.Static:
continuous = len([e for e in entity if e[1].CONTINUOUS])
discrete = len([e for e in entity if e[1].DISCRETE])
self... | Input | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Input:
def __init__(self, config, embeddings, attributes):
"""Network responsible for processing observations Args: config : A configuration object embeddings : An attribute embedding module attributes : An attribute attention module entities : An entity attention module"""
<|bod... | stack_v2_sparse_classes_75kplus_train_068579 | 2,463 | permissive | [
{
"docstring": "Network responsible for processing observations Args: config : A configuration object embeddings : An attribute embedding module attributes : An attribute attention module entities : An entity attention module",
"name": "__init__",
"signature": "def __init__(self, config, embeddings, att... | 2 | stack_v2_sparse_classes_30k_train_003402 | Implement the Python class `Input` described below.
Class description:
Implement the Input class.
Method signatures and docstrings:
- def __init__(self, config, embeddings, attributes): Network responsible for processing observations Args: config : A configuration object embeddings : An attribute embedding module att... | Implement the Python class `Input` described below.
Class description:
Implement the Input class.
Method signatures and docstrings:
- def __init__(self, config, embeddings, attributes): Network responsible for processing observations Args: config : A configuration object embeddings : An attribute embedding module att... | 42a5e8b20591f0e4789201b02cbbaf3837352881 | <|skeleton|>
class Input:
def __init__(self, config, embeddings, attributes):
"""Network responsible for processing observations Args: config : A configuration object embeddings : An attribute embedding module attributes : An attribute attention module entities : An entity attention module"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Input:
def __init__(self, config, embeddings, attributes):
"""Network responsible for processing observations Args: config : A configuration object embeddings : An attribute embedding module attributes : An attribute attention module entities : An entity attention module"""
super().__init__()
... | the_stack_v2_python_sparse | neural_mmo/forge/ethyr/torch/io/stimulus.py | alirezanobakht13/neural-mmo | train | 0 | |
a630cc21708feb7813bdf8969b71c1882e230aa8 | [
"walks: Set[Walk] = {(entity,)}\nfor i in range(self.max_depth):\n for walk in walks.copy():\n if is_reverse:\n hops = kg.get_hops(walk[0], True)\n for pred, obj in hops:\n walks.add((obj, pred) + walk)\n else:\n hops = kg.get_hops(walk[-1])\n ... | <|body_start_0|>
walks: Set[Walk] = {(entity,)}
for i in range(self.max_depth):
for walk in walks.copy():
if is_reverse:
hops = kg.get_hops(walk[0], True)
for pred, obj in hops:
walks.add((obj, pred) + walk)
... | Random walking strategy which extracts walks from a root node using the Depth First Search (DFS) algorithm if a maximum number of walks is specified, otherwise the Breadth First Search (BFS) algorithm is used. Attributes: _is_support_remote: True if the walking strategy can be used with a remote Knowledge Graph, False ... | RandomWalker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalker:
"""Random walking strategy which extracts walks from a root node using the Depth First Search (DFS) algorithm if a maximum number of walks is specified, otherwise the Breadth First Search (BFS) algorithm is used. Attributes: _is_support_remote: True if the walking strategy can be us... | stack_v2_sparse_classes_75kplus_train_068580 | 6,555 | permissive | [
{
"docstring": "Extracts random walks for an entity based on Knowledge Graph using the Breadth First Search (BFS) algorithm. Args: kg: The Knowledge Graph. entity: The root node to extract walks. is_reverse: True to get the parent neighbors instead of the child neighbors, False otherwise. Defaults to False. Ret... | 5 | stack_v2_sparse_classes_30k_train_043077 | Implement the Python class `RandomWalker` described below.
Class description:
Random walking strategy which extracts walks from a root node using the Depth First Search (DFS) algorithm if a maximum number of walks is specified, otherwise the Breadth First Search (BFS) algorithm is used. Attributes: _is_support_remote:... | Implement the Python class `RandomWalker` described below.
Class description:
Random walking strategy which extracts walks from a root node using the Depth First Search (DFS) algorithm if a maximum number of walks is specified, otherwise the Breadth First Search (BFS) algorithm is used. Attributes: _is_support_remote:... | 940ef534cd44698dfb625a0f55a47b781a8dacae | <|skeleton|>
class RandomWalker:
"""Random walking strategy which extracts walks from a root node using the Depth First Search (DFS) algorithm if a maximum number of walks is specified, otherwise the Breadth First Search (BFS) algorithm is used. Attributes: _is_support_remote: True if the walking strategy can be us... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomWalker:
"""Random walking strategy which extracts walks from a root node using the Depth First Search (DFS) algorithm if a maximum number of walks is specified, otherwise the Breadth First Search (BFS) algorithm is used. Attributes: _is_support_remote: True if the walking strategy can be used with a rem... | the_stack_v2_python_sparse | pyrdf2vec/walkers/random.py | IBCNServices/pyRDF2Vec | train | 229 |
d2b18751c4b082ba1b3b8c89db79e922bd4c3ddd | [
"ctx.save_for_backward(dim, kappa)\nkappa_copy = kappa.clone()\nm = sp.iv(dim, kappa_copy)\nx = torch.tensor(m).to(device)\nreturn x.clone()",
"dim, kappa = ctx.saved_tensors\ngrad_input = grad_output.clone()\ngrad = grad_input * (bessel_iv(dim - 1, kappa) + bessel_iv(dim + 1, kappa)) * 0.5\nreturn (None, grad)"
... | <|body_start_0|>
ctx.save_for_backward(dim, kappa)
kappa_copy = kappa.clone()
m = sp.iv(dim, kappa_copy)
x = torch.tensor(m).to(device)
return x.clone()
<|end_body_0|>
<|body_start_1|>
dim, kappa = ctx.saved_tensors
grad_input = grad_output.clone()
grad =... | We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors. | BesselIv | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BesselIv:
"""We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors."""
def forward(ctx, dim, kappa):
"""In the forward pass we receive a Tensor containing the input and retur... | stack_v2_sparse_classes_75kplus_train_068581 | 2,522 | permissive | [
{
"docstring": "In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation. You can cache arbitrary objects for use in the backward pass using the ctx.save_for_backward method.",
... | 2 | stack_v2_sparse_classes_30k_train_012360 | Implement the Python class `BesselIv` described below.
Class description:
We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors.
Method signatures and docstrings:
- def forward(ctx, dim, kappa): In the forwar... | Implement the Python class `BesselIv` described below.
Class description:
We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors.
Method signatures and docstrings:
- def forward(ctx, dim, kappa): In the forwar... | 95a39fa9f7a0659e432475e8dfb9a46e305d53b7 | <|skeleton|>
class BesselIv:
"""We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors."""
def forward(ctx, dim, kappa):
"""In the forward pass we receive a Tensor containing the input and retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BesselIv:
"""We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors."""
def forward(ctx, dim, kappa):
"""In the forward pass we receive a Tensor containing the input and return a Tensor co... | the_stack_v2_python_sparse | NVLL/distribution/try_bessel.py | jennhu/vmf_vae_nlp | train | 0 |
29ddabda7222c5ee53bb6956c0135a0a869425f0 | [
"if _debug:\n IOGroup._debug('__init__')\nIOCB.__init__(self)\nself.ioMembers = []\nself.ioState = COMPLETED\nself.ioComplete.set()",
"if _debug:\n IOGroup._debug('add %r', iocb)\nself.ioMembers.append(iocb)\nself.ioState = PENDING\nself.ioComplete.clear()\niocb.add_callback(self.group_callback)",
"if _de... | <|body_start_0|>
if _debug:
IOGroup._debug('__init__')
IOCB.__init__(self)
self.ioMembers = []
self.ioState = COMPLETED
self.ioComplete.set()
<|end_body_0|>
<|body_start_1|>
if _debug:
IOGroup._debug('add %r', iocb)
self.ioMembers.append(i... | IOGroup | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOGroup:
def __init__(self):
"""Initialize a group."""
<|body_0|>
def add(self, iocb):
"""Add an IOCB to the group, you can also add other groups."""
<|body_1|>
def group_callback(self, iocb):
"""Callback when a child iocb completes."""
<... | stack_v2_sparse_classes_75kplus_train_068582 | 29,983 | permissive | [
{
"docstring": "Initialize a group.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add an IOCB to the group, you can also add other groups.",
"name": "add",
"signature": "def add(self, iocb)"
},
{
"docstring": "Callback when a child iocb completes.",
... | 4 | null | Implement the Python class `IOGroup` described below.
Class description:
Implement the IOGroup class.
Method signatures and docstrings:
- def __init__(self): Initialize a group.
- def add(self, iocb): Add an IOCB to the group, you can also add other groups.
- def group_callback(self, iocb): Callback when a child iocb... | Implement the Python class `IOGroup` described below.
Class description:
Implement the IOGroup class.
Method signatures and docstrings:
- def __init__(self): Initialize a group.
- def add(self, iocb): Add an IOCB to the group, you can also add other groups.
- def group_callback(self, iocb): Callback when a child iocb... | a5be2ad5ac69821c12299716b167dd52041b5342 | <|skeleton|>
class IOGroup:
def __init__(self):
"""Initialize a group."""
<|body_0|>
def add(self, iocb):
"""Add an IOCB to the group, you can also add other groups."""
<|body_1|>
def group_callback(self, iocb):
"""Callback when a child iocb completes."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IOGroup:
def __init__(self):
"""Initialize a group."""
if _debug:
IOGroup._debug('__init__')
IOCB.__init__(self)
self.ioMembers = []
self.ioState = COMPLETED
self.ioComplete.set()
def add(self, iocb):
"""Add an IOCB to the group, you can... | the_stack_v2_python_sparse | py25/bacpypes/iocb.py | JoelBender/bacpypes | train | 284 | |
cf58fcdc9b8992c75065587a53a9f5a42e6610bf | [
"well = WellService.get_by_well_id(well_id)\nif well is None:\n return self.format_failure(404, 'Well Not Found')\nreturn self.format_success(200, {'well': well})",
"well = WellService.get_by_well_id(well_id)\nif well is None:\n self.format_failure(404, 'Well Not Found')\nreturn self.format_success(200, {'w... | <|body_start_0|>
well = WellService.get_by_well_id(well_id)
if well is None:
return self.format_failure(404, 'Well Not Found')
return self.format_success(200, {'well': well})
<|end_body_0|>
<|body_start_1|>
well = WellService.get_by_well_id(well_id)
if well is None:
... | API Resource for /wells/<well_id>/hygiene | WellHygiene | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WellHygiene:
"""API Resource for /wells/<well_id>/hygiene"""
def get(self, well_id, **_):
"""GET /wells/<well_id>/hygiene"""
<|body_0|>
def post(self, well_id: str):
"""POST /wells/<well_id>/hygiene"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_068583 | 1,884 | no_license | [
{
"docstring": "GET /wells/<well_id>/hygiene",
"name": "get",
"signature": "def get(self, well_id, **_)"
},
{
"docstring": "POST /wells/<well_id>/hygiene",
"name": "post",
"signature": "def post(self, well_id: str)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032264 | Implement the Python class `WellHygiene` described below.
Class description:
API Resource for /wells/<well_id>/hygiene
Method signatures and docstrings:
- def get(self, well_id, **_): GET /wells/<well_id>/hygiene
- def post(self, well_id: str): POST /wells/<well_id>/hygiene | Implement the Python class `WellHygiene` described below.
Class description:
API Resource for /wells/<well_id>/hygiene
Method signatures and docstrings:
- def get(self, well_id, **_): GET /wells/<well_id>/hygiene
- def post(self, well_id: str): POST /wells/<well_id>/hygiene
<|skeleton|>
class WellHygiene:
"""API... | 8ab4034413262ff2271740d73df72b3d83ce5918 | <|skeleton|>
class WellHygiene:
"""API Resource for /wells/<well_id>/hygiene"""
def get(self, well_id, **_):
"""GET /wells/<well_id>/hygiene"""
<|body_0|>
def post(self, well_id: str):
"""POST /wells/<well_id>/hygiene"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WellHygiene:
"""API Resource for /wells/<well_id>/hygiene"""
def get(self, well_id, **_):
"""GET /wells/<well_id>/hygiene"""
well = WellService.get_by_well_id(well_id)
if well is None:
return self.format_failure(404, 'Well Not Found')
return self.format_success... | the_stack_v2_python_sparse | app/main/controllers/wells/well_hygiene_controller.py | Malawi-Water-Wells-project/malawi-auth-api | train | 1 |
be6ce65fd9f932e06e54637679b885045bacd108 | [
"arguments = inspect.signature(getattr(instance, method)).parameters\nif arguments.__len__() == 0:\n cls._call_method(instance, method)\nelif params is not None:\n cls._call_method(instance, method, arguments, params)\nelse:\n cls._call_method(instance, method, arguments, data)",
"if not arguments:\n ... | <|body_start_0|>
arguments = inspect.signature(getattr(instance, method)).parameters
if arguments.__len__() == 0:
cls._call_method(instance, method)
elif params is not None:
cls._call_method(instance, method, arguments, params)
else:
cls._call_method(i... | Class executes method of a required class with given data based on a type of data specification | MethodExecutor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MethodExecutor:
"""Class executes method of a required class with given data based on a type of data specification"""
def execute_method(cls, instance, method, params, data):
"""The main method of a class. Gets arguments of a method to be run and calls method for calling itself with ... | stack_v2_sparse_classes_75kplus_train_068584 | 4,122 | permissive | [
{
"docstring": "The main method of a class. Gets arguments of a method to be run and calls method for calling itself with the right parameters. Args: instance: Instance of the class whose method we want to execute method (str): Name of a class method to execute. params (dict): Data from params in scenario step ... | 3 | stack_v2_sparse_classes_30k_train_010070 | Implement the Python class `MethodExecutor` described below.
Class description:
Class executes method of a required class with given data based on a type of data specification
Method signatures and docstrings:
- def execute_method(cls, instance, method, params, data): The main method of a class. Gets arguments of a m... | Implement the Python class `MethodExecutor` described below.
Class description:
Class executes method of a required class with given data based on a type of data specification
Method signatures and docstrings:
- def execute_method(cls, instance, method, params, data): The main method of a class. Gets arguments of a m... | 9653d880f7603e374a0f210bd1fcfedf2f1fd717 | <|skeleton|>
class MethodExecutor:
"""Class executes method of a required class with given data based on a type of data specification"""
def execute_method(cls, instance, method, params, data):
"""The main method of a class. Gets arguments of a method to be run and calls method for calling itself with ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MethodExecutor:
"""Class executes method of a required class with given data based on a type of data specification"""
def execute_method(cls, instance, method, params, data):
"""The main method of a class. Gets arguments of a method to be run and calls method for calling itself with the right par... | the_stack_v2_python_sparse | selenium_generator/handlers/keywords.py | jjaros587/selenium_generator | train | 1 |
7d00c6711949aba82b8f136574229b94b6657c62 | [
"super().__init__(feature_info=feature_info, file_io=file_io, **kwargs)\nself.fns = self.feature_layer_args[self.FNS]\nif len(self.fns) == 0:\n raise ValueError('At least 1 pooling function should be specified. Found : {}'.format(len(self.fns)))\nself.masked_val_lookup = {'sum': 0.0, 'mean': 0.0, 'max': -self.fe... | <|body_start_0|>
super().__init__(feature_info=feature_info, file_io=file_io, **kwargs)
self.fns = self.feature_layer_args[self.FNS]
if len(self.fns) == 0:
raise ValueError('At least 1 pooling function should be specified. Found : {}'.format(len(self.fns)))
self.masked_val_lo... | 1D pooling to reduce a variable length sequence feature into a scalar value. This method optionally allows users to add multiple such pooling operations to produce a fixed dimensional feature vector as well. | Global1dPooling | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Global1dPooling:
"""1D pooling to reduce a variable length sequence feature into a scalar value. This method optionally allows users to add multiple such pooling operations to produce a fixed dimensional feature vector as well."""
def __init__(self, feature_info: dict, file_io: FileIO, **kwa... | stack_v2_sparse_classes_75kplus_train_068585 | 9,705 | permissive | [
{
"docstring": "Initialize a feature layer to apply global 1D pooling operation on input tensor Parameters ---------- feature_info : dict Dictionary representing the feature_config for the input feature file_io : FileIO object FileIO handler object for reading and writing Notes ----- Args under `feature_layer_i... | 2 | stack_v2_sparse_classes_30k_train_054580 | Implement the Python class `Global1dPooling` described below.
Class description:
1D pooling to reduce a variable length sequence feature into a scalar value. This method optionally allows users to add multiple such pooling operations to produce a fixed dimensional feature vector as well.
Method signatures and docstri... | Implement the Python class `Global1dPooling` described below.
Class description:
1D pooling to reduce a variable length sequence feature into a scalar value. This method optionally allows users to add multiple such pooling operations to produce a fixed dimensional feature vector as well.
Method signatures and docstri... | bc2366e9180597ba4772b39249e290be28f504b8 | <|skeleton|>
class Global1dPooling:
"""1D pooling to reduce a variable length sequence feature into a scalar value. This method optionally allows users to add multiple such pooling operations to produce a fixed dimensional feature vector as well."""
def __init__(self, feature_info: dict, file_io: FileIO, **kwa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Global1dPooling:
"""1D pooling to reduce a variable length sequence feature into a scalar value. This method optionally allows users to add multiple such pooling operations to produce a fixed dimensional feature vector as well."""
def __init__(self, feature_info: dict, file_io: FileIO, **kwargs):
... | the_stack_v2_python_sparse | python/ml4ir/base/features/feature_fns/sequence.py | salesforce/ml4ir | train | 94 |
e70daf7dbb037bd71d8f8aa4bb4ab6b239ee09de | [
"self.value_list = w\nfor i in range(1, len(w)):\n self.value_list[i] += self.value_list[i - 1]",
"temp_value = 0\nlow = 0\nhigh = len(self.value_list)\ntarget_value = random.randint(1, self.value_list[-1])\nwhile low < high:\n mid = (low + high) // 2\n if self.value_list[mid] < target_value:\n lo... | <|body_start_0|>
self.value_list = w
for i in range(1, len(w)):
self.value_list[i] += self.value_list[i - 1]
<|end_body_0|>
<|body_start_1|>
temp_value = 0
low = 0
high = len(self.value_list)
target_value = random.randint(1, self.value_list[-1])
while... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.value_list = w
for i in range(1, len(w)):
self.value_list[i] += self.va... | stack_v2_sparse_classes_75kplus_train_068586 | 880 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023667 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | dc45210cb2cc50bfefd8c21c865e6ee2163a022a | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.value_list = w
for i in range(1, len(w)):
self.value_list[i] += self.value_list[i - 1]
def pickIndex(self):
""":rtype: int"""
temp_value = 0
low = 0
high = len(self.value_lis... | the_stack_v2_python_sparse | practice/solution/0528_random_pick_with_weight.py | kesarb/leetcode-summary-python | train | 0 | |
94d47c0fb8696230492bf7897510a87e985f30e1 | [
"super(BasicVs, self).__init__(input_file=input_file, params=params, BaselevelHandlerClass=BaselevelHandlerClass)\nK_sp = self.get_parameter_from_exponent('K_sp', raise_error=False)\nK_ss = self.get_parameter_from_exponent('K_ss', raise_error=False)\nlinear_diffusivity = self._length_factor ** 2.0 * self.get_parame... | <|body_start_0|>
super(BasicVs, self).__init__(input_file=input_file, params=params, BaselevelHandlerClass=BaselevelHandlerClass)
K_sp = self.get_parameter_from_exponent('K_sp', raise_error=False)
K_ss = self.get_parameter_from_exponent('K_ss', raise_error=False)
linear_diffusivity = sel... | A BasicVs computes erosion using linear diffusion, basic stream power, and Q ~ A exp( -b S / A). "VSA" stands for "variable source area". | BasicVs | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicVs:
"""A BasicVs computes erosion using linear diffusion, basic stream power, and Q ~ A exp( -b S / A). "VSA" stands for "variable source area"."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the BasicVs."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_068587 | 5,696 | permissive | [
{
"docstring": "Initialize the BasicVs.",
"name": "__init__",
"signature": "def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None)"
},
{
"docstring": "Calculate and store effective drainage area. Effective drainage area is defined as: $A_{eff} = A \\\\exp ( \u0007lpha S / A... | 3 | null | Implement the Python class `BasicVs` described below.
Class description:
A BasicVs computes erosion using linear diffusion, basic stream power, and Q ~ A exp( -b S / A). "VSA" stands for "variable source area".
Method signatures and docstrings:
- def __init__(self, input_file=None, params=None, BaselevelHandlerClass=... | Implement the Python class `BasicVs` described below.
Class description:
A BasicVs computes erosion using linear diffusion, basic stream power, and Q ~ A exp( -b S / A). "VSA" stands for "variable source area".
Method signatures and docstrings:
- def __init__(self, input_file=None, params=None, BaselevelHandlerClass=... | 1b756477b8a8ab6a8f1275b1b30ec84855c840ea | <|skeleton|>
class BasicVs:
"""A BasicVs computes erosion using linear diffusion, basic stream power, and Q ~ A exp( -b S / A). "VSA" stands for "variable source area"."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the BasicVs."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicVs:
"""A BasicVs computes erosion using linear diffusion, basic stream power, and Q ~ A exp( -b S / A). "VSA" stands for "variable source area"."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the BasicVs."""
super(BasicVs, self).__init_... | the_stack_v2_python_sparse | terrainbento/derived_models/model_200_basicVs/model_200_basicVs.py | mcflugen/terrainbento | train | 0 |
b1b8755221603ac8f8b14d52348ff53d5e68c71e | [
"url = self.l + read_yaml()[7]['url1']\ntoken = readconfig('token')\nresult = set_show_fields(url=url, header={'Authorization': token})\nprint(result)\nreturn result",
"url = self.l + read_yaml()[7]['url2']\nresult = get_show_fields(url=url, header=self.header)\na = result['data']\nprint(a)\nreturn result"
] | <|body_start_0|>
url = self.l + read_yaml()[7]['url1']
token = readconfig('token')
result = set_show_fields(url=url, header={'Authorization': token})
print(result)
return result
<|end_body_0|>
<|body_start_1|>
url = self.l + read_yaml()[7]['url2']
result = get_sh... | TestSetShowFields | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSetShowFields:
def test_set_showfields(self):
"""修改联系人自定义列表头,接口地址:/api/scrm/setShowFields"""
<|body_0|>
def test_get_showfields(self):
"""获取联系人自定义列表头,接口地址:/api/scrm/getShowFields"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
url = self.l + rea... | stack_v2_sparse_classes_75kplus_train_068588 | 791 | no_license | [
{
"docstring": "修改联系人自定义列表头,接口地址:/api/scrm/setShowFields",
"name": "test_set_showfields",
"signature": "def test_set_showfields(self)"
},
{
"docstring": "获取联系人自定义列表头,接口地址:/api/scrm/getShowFields",
"name": "test_get_showfields",
"signature": "def test_get_showfields(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027839 | Implement the Python class `TestSetShowFields` described below.
Class description:
Implement the TestSetShowFields class.
Method signatures and docstrings:
- def test_set_showfields(self): 修改联系人自定义列表头,接口地址:/api/scrm/setShowFields
- def test_get_showfields(self): 获取联系人自定义列表头,接口地址:/api/scrm/getShowFields | Implement the Python class `TestSetShowFields` described below.
Class description:
Implement the TestSetShowFields class.
Method signatures and docstrings:
- def test_set_showfields(self): 修改联系人自定义列表头,接口地址:/api/scrm/setShowFields
- def test_get_showfields(self): 获取联系人自定义列表头,接口地址:/api/scrm/getShowFields
<|skeleton|>
... | 75f18afa6d74cb1916a2496d1a1f267bf8ddb93c | <|skeleton|>
class TestSetShowFields:
def test_set_showfields(self):
"""修改联系人自定义列表头,接口地址:/api/scrm/setShowFields"""
<|body_0|>
def test_get_showfields(self):
"""获取联系人自定义列表头,接口地址:/api/scrm/getShowFields"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSetShowFields:
def test_set_showfields(self):
"""修改联系人自定义列表头,接口地址:/api/scrm/setShowFields"""
url = self.l + read_yaml()[7]['url1']
token = readconfig('token')
result = set_show_fields(url=url, header={'Authorization': token})
print(result)
return result
... | the_stack_v2_python_sparse | Test_case/test_5setshowfields.py | jiangna123000/api_test_case | train | 0 | |
0196678135e737eb842099a068cf5c26c132440d | [
"if len(features) == 0:\n raise ValueError('features must have at least 1 element')\nself.features = features\nself.activation = activation\nself.use_bias = use_bias\nself.dtype = dtype\nself.precision = precision\nself.kernel_init = kernel_init\nself.bias_init = bias_init",
"last_layer_idx = len(self.features... | <|body_start_0|>
if len(features) == 0:
raise ValueError('features must have at least 1 element')
self.features = features
self.activation = activation
self.use_bias = use_bias
self.dtype = dtype
self.precision = precision
self.kernel_init = kernel_ini... | A Multi-Layer Perceptron (MLP) that applies a sequence of linear layers with a given activation (relu by default), the last layer is linear. | MLP | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
"""A Multi-Layer Perceptron (MLP) that applies a sequence of linear layers with a given activation (relu by default), the last layer is linear."""
def __init__(self, features: tp.Sequence[int], activation: tp.Callable[[jnp.ndarray], jnp.ndarray]=jax.nn.relu, use_bias: bool=True, dtype: ... | stack_v2_sparse_classes_75kplus_train_068589 | 2,931 | permissive | [
{
"docstring": "Arguments: features: a sequence of L+1 integers, where L is the number of layers, the first integer is the number of input features and all subsequent integers are the number of output features of the respective layer. activation: the activation function to use. use_bias: whether to add a bias t... | 2 | null | Implement the Python class `MLP` described below.
Class description:
A Multi-Layer Perceptron (MLP) that applies a sequence of linear layers with a given activation (relu by default), the last layer is linear.
Method signatures and docstrings:
- def __init__(self, features: tp.Sequence[int], activation: tp.Callable[[... | Implement the Python class `MLP` described below.
Class description:
A Multi-Layer Perceptron (MLP) that applies a sequence of linear layers with a given activation (relu by default), the last layer is linear.
Method signatures and docstrings:
- def __init__(self, features: tp.Sequence[int], activation: tp.Callable[[... | 494f6d886d0d540608049d5c98106dce81e32f9f | <|skeleton|>
class MLP:
"""A Multi-Layer Perceptron (MLP) that applies a sequence of linear layers with a given activation (relu by default), the last layer is linear."""
def __init__(self, features: tp.Sequence[int], activation: tp.Callable[[jnp.ndarray], jnp.ndarray]=jax.nn.relu, use_bias: bool=True, dtype: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLP:
"""A Multi-Layer Perceptron (MLP) that applies a sequence of linear layers with a given activation (relu by default), the last layer is linear."""
def __init__(self, features: tp.Sequence[int], activation: tp.Callable[[jnp.ndarray], jnp.ndarray]=jax.nn.relu, use_bias: bool=True, dtype: tp.Any=jnp.fl... | the_stack_v2_python_sparse | treex/nn/mlp.py | zeeroocooll/treex | train | 0 |
c72708186102272632328e42702e33c195d2b8d8 | [
"if weights == []:\n self.weights = [round(random.random(), 2) for i in range(nb_of_entry)]\n self.sill = round(random.random(), 2)\nelse:\n self.weights = weights\n self.sill = sill",
"result = []\nif len(entry) != len(self.weights):\n raise ValueError('error incorect len of liste')\nfor pos in ra... | <|body_start_0|>
if weights == []:
self.weights = [round(random.random(), 2) for i in range(nb_of_entry)]
self.sill = round(random.random(), 2)
else:
self.weights = weights
self.sill = sill
<|end_body_0|>
<|body_start_1|>
result = []
if le... | describe the neurone object | Neurone | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Neurone:
"""describe the neurone object"""
def __init__(self, nb_of_entry, weights=[], sill=0):
"""create a neurone if weights is not define, create a random neurone with number_of_entry entry else create a neurone with a list of weight and sill as sill"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_068590 | 6,862 | no_license | [
{
"docstring": "create a neurone if weights is not define, create a random neurone with number_of_entry entry else create a neurone with a list of weight and sill as sill",
"name": "__init__",
"signature": "def __init__(self, nb_of_entry, weights=[], sill=0)"
},
{
"docstring": "define the multip... | 4 | null | Implement the Python class `Neurone` described below.
Class description:
describe the neurone object
Method signatures and docstrings:
- def __init__(self, nb_of_entry, weights=[], sill=0): create a neurone if weights is not define, create a random neurone with number_of_entry entry else create a neurone with a list ... | Implement the Python class `Neurone` described below.
Class description:
describe the neurone object
Method signatures and docstrings:
- def __init__(self, nb_of_entry, weights=[], sill=0): create a neurone if weights is not define, create a random neurone with number_of_entry entry else create a neurone with a list ... | 147773cc8871d74f1ec1d6bd03e3cce95e9490d1 | <|skeleton|>
class Neurone:
"""describe the neurone object"""
def __init__(self, nb_of_entry, weights=[], sill=0):
"""create a neurone if weights is not define, create a random neurone with number_of_entry entry else create a neurone with a list of weight and sill as sill"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Neurone:
"""describe the neurone object"""
def __init__(self, nb_of_entry, weights=[], sill=0):
"""create a neurone if weights is not define, create a random neurone with number_of_entry entry else create a neurone with a list of weight and sill as sill"""
if weights == []:
se... | the_stack_v2_python_sparse | analyse_de_données/Projet/CharacterRecognition/NeuralNetwork.py | porigonop/code_v2 | train | 0 |
d9a498e7ec694766c61d66025b59413bb71e96df | [
"super().__init__(data=data, sampling_rate=sampling_rate, time_intervals=time_intervals, include_start=include_start)\nself.eeg_result: Dict[str, pd.DataFrame] = {}\n'Dictionary with EEG processing result dataframes, split into different phases.\\n\\n '",
"from mne.time_frequency import psd_array_welch\nee... | <|body_start_0|>
super().__init__(data=data, sampling_rate=sampling_rate, time_intervals=time_intervals, include_start=include_start)
self.eeg_result: Dict[str, pd.DataFrame] = {}
'Dictionary with EEG processing result dataframes, split into different phases.\n\n '
<|end_body_0|>
<|body_... | Class for processing EEG data. | EegProcessor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EegProcessor:
"""Class for processing EEG data."""
def __init__(self, data: Union[pd.DataFrame, Dict[str, pd.DataFrame]], sampling_rate: Optional[float]=None, time_intervals: Optional[Union[pd.Series, Dict[str, Sequence[str]]]]=None, include_start: Optional[bool]=False):
"""Initializ... | stack_v2_sparse_classes_75kplus_train_068591 | 5,188 | permissive | [
{
"docstring": "Initialize an ``EegProcessor`` instance. You can either pass a data dictionary 'data_dict' containing EEG data or dataframe containing EEG data. For the latter, you can additionally supply time information via ``time_intervals`` parameter to automatically split the data into single phases. Param... | 2 | stack_v2_sparse_classes_30k_train_022058 | Implement the Python class `EegProcessor` described below.
Class description:
Class for processing EEG data.
Method signatures and docstrings:
- def __init__(self, data: Union[pd.DataFrame, Dict[str, pd.DataFrame]], sampling_rate: Optional[float]=None, time_intervals: Optional[Union[pd.Series, Dict[str, Sequence[str]... | Implement the Python class `EegProcessor` described below.
Class description:
Class for processing EEG data.
Method signatures and docstrings:
- def __init__(self, data: Union[pd.DataFrame, Dict[str, pd.DataFrame]], sampling_rate: Optional[float]=None, time_intervals: Optional[Union[pd.Series, Dict[str, Sequence[str]... | 5b2eab0b0e4b52c1b3997f760ad0d1ae33d1a81d | <|skeleton|>
class EegProcessor:
"""Class for processing EEG data."""
def __init__(self, data: Union[pd.DataFrame, Dict[str, pd.DataFrame]], sampling_rate: Optional[float]=None, time_intervals: Optional[Union[pd.Series, Dict[str, Sequence[str]]]]=None, include_start: Optional[bool]=False):
"""Initializ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EegProcessor:
"""Class for processing EEG data."""
def __init__(self, data: Union[pd.DataFrame, Dict[str, pd.DataFrame]], sampling_rate: Optional[float]=None, time_intervals: Optional[Union[pd.Series, Dict[str, Sequence[str]]]]=None, include_start: Optional[bool]=False):
"""Initialize an ``EegPro... | the_stack_v2_python_sparse | src/biopsykit/signals/eeg/eeg.py | mad-lab-fau/BioPsyKit | train | 35 |
a94bc0e173d7a2bb5fd596e34cb725a745665238 | [
"if target in nums:\n return nums.index(target)\nelse:\n if target < nums[0]:\n return 0\n if target > nums[-1]:\n return len(nums)\n for i in range(len(nums) - 1):\n if nums[i] < target and nums[i + 1] > target:\n return i + 1",
"n = len(nums)\nif target > nums[n - 1]:... | <|body_start_0|>
if target in nums:
return nums.index(target)
else:
if target < nums[0]:
return 0
if target > nums[-1]:
return len(nums)
for i in range(len(nums) - 1):
if nums[i] < target and nums[i + 1] > ta... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchInsert(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def searchInsert2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_068592 | 814 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "searchInsert",
"signature": "def searchInsert(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "searchInsert2",
"signature": "def searchInsert2(self, nums, ... | 2 | stack_v2_sparse_classes_30k_train_023678 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsert(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def searchInsert2(self, nums, target): :type nums: List[int] :type target: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsert(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def searchInsert2(self, nums, target): :type nums: List[int] :type target: int :rtype:... | f1d780b7e8b91b4df704651514018143c6931f9d | <|skeleton|>
class Solution:
def searchInsert(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def searchInsert2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def searchInsert(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
if target in nums:
return nums.index(target)
else:
if target < nums[0]:
return 0
if target > nums[-1]:
return le... | the_stack_v2_python_sparse | ProgramForLeetCode/LeetCode/35_searchInsert.py | DQDH/Algorithm_Code | train | 0 | |
cd38af8d67b75fc21adcf7080585632955b826a5 | [
"self.Whf = np.random.normal(size=(i + h, h))\nself.Whb = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(2 * h, o))\nself.bhf = np.zeros((1, h))\nself.bhb = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"h_matrix = np.concatenate((h_prev.T, x_t.T), axis=0)\nh_next = np.tanh(np.matmul(h_matri... | <|body_start_0|>
self.Whf = np.random.normal(size=(i + h, h))
self.Whb = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(2 * h, o))
self.bhf = np.zeros((1, h))
self.bhb = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
... | BidirectionalCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BidirectionalCell:
def __init__(self, i, h, o):
"""class constructor :param i: dim of data :param h: dim of hidden states :param o: dim outputs Notes: Public Instances: Whf and bhf: for the hidden states forward direction Whb and bhb: for hiden states backward direction Wy and by: for ou... | stack_v2_sparse_classes_75kplus_train_068593 | 1,733 | no_license | [
{
"docstring": "class constructor :param i: dim of data :param h: dim of hidden states :param o: dim outputs Notes: Public Instances: Whf and bhf: for the hidden states forward direction Whb and bhb: for hiden states backward direction Wy and by: for outputs Notes: Weights: initialized using random normal dist ... | 2 | stack_v2_sparse_classes_30k_train_037239 | Implement the Python class `BidirectionalCell` described below.
Class description:
Implement the BidirectionalCell class.
Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor :param i: dim of data :param h: dim of hidden states :param o: dim outputs Notes: Public Instances: Whf and bhf: ... | Implement the Python class `BidirectionalCell` described below.
Class description:
Implement the BidirectionalCell class.
Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor :param i: dim of data :param h: dim of hidden states :param o: dim outputs Notes: Public Instances: Whf and bhf: ... | 4ac942126918c7acaa9ef88d18efe299b2f726fe | <|skeleton|>
class BidirectionalCell:
def __init__(self, i, h, o):
"""class constructor :param i: dim of data :param h: dim of hidden states :param o: dim outputs Notes: Public Instances: Whf and bhf: for the hidden states forward direction Whb and bhb: for hiden states backward direction Wy and by: for ou... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BidirectionalCell:
def __init__(self, i, h, o):
"""class constructor :param i: dim of data :param h: dim of hidden states :param o: dim outputs Notes: Public Instances: Whf and bhf: for the hidden states forward direction Whb and bhb: for hiden states backward direction Wy and by: for outputs Notes: W... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/5-bi_forward.py | DracoMindz/holbertonschool-machine_learning | train | 2 | |
0d48b941b27240380a6f93c9a8e6e16fe2e10dc6 | [
"S = np.linspace(S0 - 10, S0 + 10, 21)\nVd = np.maximum(S - K, 0)\nVd[S >= L] = 0\npayoff = UpAndOut(CallA(T, K), L)\nfor t in np.linspace(0, 1, N, endpoint=False):\n self.assertTrue((payoff.default(t, S) == Vd).all())\nself.assertRaises(AssertionError, payoff.default, T, S)",
"S = np.linspace(S0 - 10, S0 + 10... | <|body_start_0|>
S = np.linspace(S0 - 10, S0 + 10, 21)
Vd = np.maximum(S - K, 0)
Vd[S >= L] = 0
payoff = UpAndOut(CallA(T, K), L)
for t in np.linspace(0, 1, N, endpoint=False):
self.assertTrue((payoff.default(t, S) == Vd).all())
self.assertRaises(AssertionErro... | Test UpAndOut payoff. | TestUpAndOut | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUpAndOut:
"""Test UpAndOut payoff."""
def test_default(self):
"""Test default value for American up-and-out call."""
<|body_0|>
def test_transcient(self):
"""Test value of transient for American up-and-out call."""
<|body_1|>
def test_terminal(se... | stack_v2_sparse_classes_75kplus_train_068594 | 17,183 | permissive | [
{
"docstring": "Test default value for American up-and-out call.",
"name": "test_default",
"signature": "def test_default(self)"
},
{
"docstring": "Test value of transient for American up-and-out call.",
"name": "test_transcient",
"signature": "def test_transcient(self)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_026703 | Implement the Python class `TestUpAndOut` described below.
Class description:
Test UpAndOut payoff.
Method signatures and docstrings:
- def test_default(self): Test default value for American up-and-out call.
- def test_transcient(self): Test value of transient for American up-and-out call.
- def test_terminal(self):... | Implement the Python class `TestUpAndOut` described below.
Class description:
Test UpAndOut payoff.
Method signatures and docstrings:
- def test_default(self): Test default value for American up-and-out call.
- def test_transcient(self): Test value of transient for American up-and-out call.
- def test_terminal(self):... | 651877e314d86f250475d4480832650f6e3051af | <|skeleton|>
class TestUpAndOut:
"""Test UpAndOut payoff."""
def test_default(self):
"""Test default value for American up-and-out call."""
<|body_0|>
def test_transcient(self):
"""Test value of transient for American up-and-out call."""
<|body_1|>
def test_terminal(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestUpAndOut:
"""Test UpAndOut payoff."""
def test_default(self):
"""Test default value for American up-and-out call."""
S = np.linspace(S0 - 10, S0 + 10, 21)
Vd = np.maximum(S - K, 0)
Vd[S >= L] = 0
payoff = UpAndOut(CallA(T, K), L)
for t in np.linspace(0,... | the_stack_v2_python_sparse | src/test_payoff.py | HW-Gabriel/amf_research | train | 0 |
09c1361435a52815b765b64595c0e3083c65751f | [
"url = 'https://login.taobao.com/member/login.jhtml'\nself.url = url\noptions = webdriver.ChromeOptions()\noptions.add_experimental_option('prefs', {'profile.managed_default_content_settings.images': 2})\noptions.add_experimental_option('excludeSwitches', ['enable-automation'])\nself.browser = webdriver.Chrome(opti... | <|body_start_0|>
url = 'https://login.taobao.com/member/login.jhtml'
self.url = url
options = webdriver.ChromeOptions()
options.add_experimental_option('prefs', {'profile.managed_default_content_settings.images': 2})
options.add_experimental_option('excludeSwitches', ['enable-aut... | Taobao_Spider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Taobao_Spider:
def __init__(self, username, password):
"""初始化参数"""
<|body_0|>
def run(self):
"""登陆接口"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
url = 'https://login.taobao.com/member/login.jhtml'
self.url = url
options = webdriv... | stack_v2_sparse_classes_75kplus_train_068595 | 2,847 | permissive | [
{
"docstring": "初始化参数",
"name": "__init__",
"signature": "def __init__(self, username, password)"
},
{
"docstring": "登陆接口",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012265 | Implement the Python class `Taobao_Spider` described below.
Class description:
Implement the Taobao_Spider class.
Method signatures and docstrings:
- def __init__(self, username, password): 初始化参数
- def run(self): 登陆接口 | Implement the Python class `Taobao_Spider` described below.
Class description:
Implement the Taobao_Spider class.
Method signatures and docstrings:
- def __init__(self, username, password): 初始化参数
- def run(self): 登陆接口
<|skeleton|>
class Taobao_Spider:
def __init__(self, username, password):
"""初始化参数"""
... | 56f61fd992fd0e7bafc3116ee6c5455e2d148846 | <|skeleton|>
class Taobao_Spider:
def __init__(self, username, password):
"""初始化参数"""
<|body_0|>
def run(self):
"""登陆接口"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Taobao_Spider:
def __init__(self, username, password):
"""初始化参数"""
url = 'https://login.taobao.com/member/login.jhtml'
self.url = url
options = webdriver.ChromeOptions()
options.add_experimental_option('prefs', {'profile.managed_default_content_settings.images': 2})
... | the_stack_v2_python_sparse | taobao/taobao.py | ryanzicky/awesome-python-login-model | train | 2 | |
a67493220b29e2d21931faece8651f9a2ddf73f2 | [
"name = f'Random_mu={mu}'\nsuper().__init__(model, name, rounds, sequences_batch_size, model_queries_per_batch, starting_sequence, log_file)\nself.mu = mu\nself.rng = np.random.default_rng(seed)\nself.alphabet = alphabet\nself.elitist = elitist",
"old_sequences = measured_sequences['sequence']\nold_sequence_set =... | <|body_start_0|>
name = f'Random_mu={mu}'
super().__init__(model, name, rounds, sequences_batch_size, model_queries_per_batch, starting_sequence, log_file)
self.mu = mu
self.rng = np.random.default_rng(seed)
self.alphabet = alphabet
self.elitist = elitist
<|end_body_0|>
... | A simple random explorer. Chooses a random previously measured sequence and mutates it. A good baseline to compare other search strategies against. Since random search is not data-driven, the model is only used to score sequences, but not to guide the search strategy. | Random | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Random:
"""A simple random explorer. Chooses a random previously measured sequence and mutates it. A good baseline to compare other search strategies against. Since random search is not data-driven, the model is only used to score sequences, but not to guide the search strategy."""
def __ini... | stack_v2_sparse_classes_75kplus_train_068596 | 2,745 | permissive | [
{
"docstring": "Create a random search explorer. Args: mu: Average number of residue mutations from parent for generated sequences. elitist: If true, will propose the top `sequences_batch_size` sequences generated according to `model`. If false, randomly proposes `sequences_batch_size` sequences without taking ... | 2 | stack_v2_sparse_classes_30k_train_045823 | Implement the Python class `Random` described below.
Class description:
A simple random explorer. Chooses a random previously measured sequence and mutates it. A good baseline to compare other search strategies against. Since random search is not data-driven, the model is only used to score sequences, but not to guide... | Implement the Python class `Random` described below.
Class description:
A simple random explorer. Chooses a random previously measured sequence and mutates it. A good baseline to compare other search strategies against. Since random search is not data-driven, the model is only used to score sequences, but not to guide... | 744e792456d93e8c48fc58220689c0b4cff6ded9 | <|skeleton|>
class Random:
"""A simple random explorer. Chooses a random previously measured sequence and mutates it. A good baseline to compare other search strategies against. Since random search is not data-driven, the model is only used to score sequences, but not to guide the search strategy."""
def __ini... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Random:
"""A simple random explorer. Chooses a random previously measured sequence and mutates it. A good baseline to compare other search strategies against. Since random search is not data-driven, the model is only used to score sequences, but not to guide the search strategy."""
def __init__(self, mod... | the_stack_v2_python_sparse | flexs/baselines/explorers/random.py | jonshao/FLEXS | train | 0 |
4970ac986818faa6c1eca91e47e1ec198b9d1265 | [
"lines = self.test.render(anchor='@CA,C,N', mask='!:NA,WAT,HOH', align_mask=':1-100', trajin=[Path('test.crd')], parm=Path('test.prm'), prefix='snapshots/').splitlines()\nself.assertEqual(lines[0], f'# Generated by fmojinja version {get_version()}')\nself.assertEqual(lines[3], 'autoimage anchor @CA,C,N origin', 'au... | <|body_start_0|>
lines = self.test.render(anchor='@CA,C,N', mask='!:NA,WAT,HOH', align_mask=':1-100', trajin=[Path('test.crd')], parm=Path('test.prm'), prefix='snapshots/').splitlines()
self.assertEqual(lines[0], f'# Generated by fmojinja version {get_version()}')
self.assertEqual(lines[3], 'aut... | TestSnapshot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSnapshot:
def test_simple_1(self):
"""simple test 1 for snapshot python -m fmojinja.cpptraj snapshot -p test.prm -y test.crd --align-mask :1-100 --mask !:NA,WAT,HOH --prefix snapshots/ :return: None"""
<|body_0|>
def test_simple_2(self):
"""simple test 2 for snap... | stack_v2_sparse_classes_75kplus_train_068597 | 3,199 | permissive | [
{
"docstring": "simple test 1 for snapshot python -m fmojinja.cpptraj snapshot -p test.prm -y test.crd --align-mask :1-100 --mask !:NA,WAT,HOH --prefix snapshots/ :return: None",
"name": "test_simple_1",
"signature": "def test_simple_1(self)"
},
{
"docstring": "simple test 2 for snapshot python ... | 2 | stack_v2_sparse_classes_30k_train_016207 | Implement the Python class `TestSnapshot` described below.
Class description:
Implement the TestSnapshot class.
Method signatures and docstrings:
- def test_simple_1(self): simple test 1 for snapshot python -m fmojinja.cpptraj snapshot -p test.prm -y test.crd --align-mask :1-100 --mask !:NA,WAT,HOH --prefix snapshots... | Implement the Python class `TestSnapshot` described below.
Class description:
Implement the TestSnapshot class.
Method signatures and docstrings:
- def test_simple_1(self): simple test 1 for snapshot python -m fmojinja.cpptraj snapshot -p test.prm -y test.crd --align-mask :1-100 --mask !:NA,WAT,HOH --prefix snapshots... | c0728660628b3d46fa9923f5439136d966f29e2f | <|skeleton|>
class TestSnapshot:
def test_simple_1(self):
"""simple test 1 for snapshot python -m fmojinja.cpptraj snapshot -p test.prm -y test.crd --align-mask :1-100 --mask !:NA,WAT,HOH --prefix snapshots/ :return: None"""
<|body_0|>
def test_simple_2(self):
"""simple test 2 for snap... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSnapshot:
def test_simple_1(self):
"""simple test 1 for snapshot python -m fmojinja.cpptraj snapshot -p test.prm -y test.crd --align-mask :1-100 --mask !:NA,WAT,HOH --prefix snapshots/ :return: None"""
lines = self.test.render(anchor='@CA,C,N', mask='!:NA,WAT,HOH', align_mask=':1-100', tra... | the_stack_v2_python_sparse | fmojinja/cpptraj/test_snapshot.py | physchemstar/fmojinja | train | 1 | |
20fa88941344e2835fa8e175a61cf16ba8c14d00 | [
"self.porosity = 0.92\nself.k_matrix = 0.0058\nself.PPI = 10.0\nself.K = 2e-07\nself.Nu_D",
"self.Re_K = self.velocity * self.K ** 0.5 / self.nu\nself.f = 1.0 / self.Re_K + 0.55\nself.k = self.k_matrix\nself.deltaP = self.f * self.perimeter * self.node_length / self.flow_area * (0.5 * self.rho * self.velocity ** ... | <|body_start_0|>
self.porosity = 0.92
self.k_matrix = 0.0058
self.PPI = 10.0
self.K = 2e-07
self.Nu_D
<|end_body_0|>
<|body_start_1|>
self.Re_K = self.velocity * self.K ** 0.5 / self.nu
self.f = 1.0 / self.Re_K + 0.55
self.k = self.k_matrix
self.d... | Class for porous media according to the book of Bejan. Bejan, A. “Designed Porous Media: Maximal Heat Transfer Density at Decreasing Length Scales.” International Journal of Heat and Mass Transfer 47, no. 14 (2004): 3073–3083. Methods: __init__ solve_enh | BejanPorous | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BejanPorous:
"""Class for porous media according to the book of Bejan. Bejan, A. “Designed Porous Media: Maximal Heat Transfer Density at Decreasing Length Scales.” International Journal of Heat and Mass Transfer 47, no. 14 (2004): 3073–3083. Methods: __init__ solve_enh"""
def __init__(self)... | stack_v2_sparse_classes_75kplus_train_068598 | 15,856 | no_license | [
{
"docstring": "Initializes a bunch of constants.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Solves for convection parameters with enhancement.",
"name": "solve_enh",
"signature": "def solve_enh(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019405 | Implement the Python class `BejanPorous` described below.
Class description:
Class for porous media according to the book of Bejan. Bejan, A. “Designed Porous Media: Maximal Heat Transfer Density at Decreasing Length Scales.” International Journal of Heat and Mass Transfer 47, no. 14 (2004): 3073–3083. Methods: __init... | Implement the Python class `BejanPorous` described below.
Class description:
Class for porous media according to the book of Bejan. Bejan, A. “Designed Porous Media: Maximal Heat Transfer Density at Decreasing Length Scales.” International Journal of Heat and Mass Transfer 47, no. 14 (2004): 3073–3083. Methods: __init... | d619b66b1f16557e06c94eee1c16d4ee2a9e896a | <|skeleton|>
class BejanPorous:
"""Class for porous media according to the book of Bejan. Bejan, A. “Designed Porous Media: Maximal Heat Transfer Density at Decreasing Length Scales.” International Journal of Heat and Mass Transfer 47, no. 14 (2004): 3073–3083. Methods: __init__ solve_enh"""
def __init__(self)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BejanPorous:
"""Class for porous media according to the book of Bejan. Bejan, A. “Designed Porous Media: Maximal Heat Transfer Density at Decreasing Length Scales.” International Journal of Heat and Mass Transfer 47, no. 14 (2004): 3073–3083. Methods: __init__ solve_enh"""
def __init__(self):
"""... | the_stack_v2_python_sparse | Modules/enhancement.py | hfateh/TE_Model-1 | train | 0 |
ff0a6c140c9347b698c5ad7c9dd3590642033ea0 | [
"win_reward = 0.0\nheart_cards = {c for c in cards if c.suit == Suit.HEARTS}\nwin_reward += len(heart_cards) * cls._HEART_REWARD\nif cls._QUEEN_OF_SPADES in cards:\n win_reward += cls._QUEEN_REWARD\nreturn win_reward",
"if len(next_state.agent_hand) != 0 or len(next_state.opponent_hand) != 0:\n return 0.0\n... | <|body_start_0|>
win_reward = 0.0
heart_cards = {c for c in cards if c.suit == Suit.HEARTS}
win_reward += len(heart_cards) * cls._HEART_REWARD
if cls._QUEEN_OF_SPADES in cards:
win_reward += cls._QUEEN_REWARD
return win_reward
<|end_body_0|>
<|body_start_1|>
... | A reward model for the game. | RewardModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RewardModel:
"""A reward model for the game."""
def __trick_reward(cls, cards: AbstractSet[Card]) -> float:
"""Calculates the reward for winning a particular trick. Args: cards: The cards in the trick. Returns: The reward."""
<|body_0|>
def __check_moonshot_reward(cls, n... | stack_v2_sparse_classes_75kplus_train_068599 | 3,277 | permissive | [
{
"docstring": "Calculates the reward for winning a particular trick. Args: cards: The cards in the trick. Returns: The reward.",
"name": "__trick_reward",
"signature": "def __trick_reward(cls, cards: AbstractSet[Card]) -> float"
},
{
"docstring": "Checks if a player shot the moon and gets the r... | 3 | stack_v2_sparse_classes_30k_train_014744 | Implement the Python class `RewardModel` described below.
Class description:
A reward model for the game.
Method signatures and docstrings:
- def __trick_reward(cls, cards: AbstractSet[Card]) -> float: Calculates the reward for winning a particular trick. Args: cards: The cards in the trick. Returns: The reward.
- de... | Implement the Python class `RewardModel` described below.
Class description:
A reward model for the game.
Method signatures and docstrings:
- def __trick_reward(cls, cards: AbstractSet[Card]) -> float: Calculates the reward for winning a particular trick. Args: cards: The cards in the trick. Returns: The reward.
- de... | b8a3de10c7961d1328ee0273fdde8b444070dc24 | <|skeleton|>
class RewardModel:
"""A reward model for the game."""
def __trick_reward(cls, cards: AbstractSet[Card]) -> float:
"""Calculates the reward for winning a particular trick. Args: cards: The cards in the trick. Returns: The reward."""
<|body_0|>
def __check_moonshot_reward(cls, n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RewardModel:
"""A reward model for the game."""
def __trick_reward(cls, cards: AbstractSet[Card]) -> float:
"""Calculates the reward for winning a particular trick. Args: cards: The cards in the trick. Returns: The reward."""
win_reward = 0.0
heart_cards = {c for c in cards if c.s... | the_stack_v2_python_sparse | hearts_pomdp/models/reward.py | djpetti/hearts_pomdp | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.