blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
54b887145ecf4fba69389346118b7358b4dc77cb | [
"super(Classification, self).__init__(in_channels, outputs=classes, anchors=anchors, features=features)\ntorch.nn.init.constant_(self.last_conv.bias, float(-torch.log(torch.Tensor([(1 - prior) / prior]))))\nself.classes = classes\nself.activation = nn.Sigmoid()",
"out = super(Classification, self).forward(feature... | <|body_start_0|>
super(Classification, self).__init__(in_channels, outputs=classes, anchors=anchors, features=features)
torch.nn.init.constant_(self.last_conv.bias, float(-torch.log(torch.Tensor([(1 - prior) / prior]))))
self.classes = classes
self.activation = nn.Sigmoid()
<|end_body_0|... | Classification submodule of RetinaNet. It generates, given a feature map, a tensor with the probability of each class. | Classification | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Classification:
"""Classification submodule of RetinaNet. It generates, given a feature map, a tensor with the probability of each class."""
def __init__(self, in_channels, classes, anchors=9, features=256, prior=0.01):
"""Initialize the network. Args: in_channels (int): The number o... | stack_v2_sparse_classes_36k_train_024600 | 27,489 | no_license | [
{
"docstring": "Initialize the network. Args: in_channels (int): The number of channels of the feature map. classes (int): Indicates the number of classes to predict. anchors (int, optional): The number of anchors per location in the feature map. features (int, optional): Indicates the number of inner features ... | 2 | null | Implement the Python class `Classification` described below.
Class description:
Classification submodule of RetinaNet. It generates, given a feature map, a tensor with the probability of each class.
Method signatures and docstrings:
- def __init__(self, in_channels, classes, anchors=9, features=256, prior=0.01): Init... | Implement the Python class `Classification` described below.
Class description:
Classification submodule of RetinaNet. It generates, given a feature map, a tensor with the probability of each class.
Method signatures and docstrings:
- def __init__(self, in_channels, classes, anchors=9, features=256, prior=0.01): Init... | a22aa5b00369c2692bf4fa537bce20144d14d5cb | <|skeleton|>
class Classification:
"""Classification submodule of RetinaNet. It generates, given a feature map, a tensor with the probability of each class."""
def __init__(self, in_channels, classes, anchors=9, features=256, prior=0.01):
"""Initialize the network. Args: in_channels (int): The number o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Classification:
"""Classification submodule of RetinaNet. It generates, given a feature map, a tensor with the probability of each class."""
def __init__(self, in_channels, classes, anchors=9, features=256, prior=0.01):
"""Initialize the network. Args: in_channels (int): The number of channels of... | the_stack_v2_python_sparse | torchsight/models/retinanet.py | SetaSouto/torchsight | train | 2 |
c39e966d4c0185173a64833e16112d7ecc15c8ee | [
"self.dp = [0]\nself.len = len(nums)\nfor val in nums:\n self.dp.append(val + self.dp[-1])",
"if i < 0:\n i = 0\nif j >= self.len:\n j = self.len - 1\nreturn self.dp[j + 1] - self.dp[i]"
] | <|body_start_0|>
self.dp = [0]
self.len = len(nums)
for val in nums:
self.dp.append(val + self.dp[-1])
<|end_body_0|>
<|body_start_1|>
if i < 0:
i = 0
if j >= self.len:
j = self.len - 1
return self.dp[j + 1] - self.dp[i]
<|end_body_1|>... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dp = [0]
self.len = len(nums)
for val ... | stack_v2_sparse_classes_36k_train_024601 | 535 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004965 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | e2837f3d6c23f012148a2d1f9d0ef6d34d4e6912 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.dp = [0]
self.len = len(nums)
for val in nums:
self.dp.append(val + self.dp[-1])
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
if i < 0:
i =... | the_stack_v2_python_sparse | Dp/range-sum-query-immutable.py | wttttt-wang/leetcode_withTopics | train | 0 | |
805247b1df525a81df931e92db09ce35b27c7f21 | [
"super(CustomCrossEntropyLoss, self).__init__()\nself.use_sigmoid = desc['use_sigmoid'] if 'use_sigmoid' in desc else False\nself.use_mask = desc['use_mask'] if 'use_mask' in desc else False\nself.reduction = desc['reduction'] if 'reduction' in desc else 'mean'\nself.loss_weight = desc['loss_weight'] if 'loss_weigh... | <|body_start_0|>
super(CustomCrossEntropyLoss, self).__init__()
self.use_sigmoid = desc['use_sigmoid'] if 'use_sigmoid' in desc else False
self.use_mask = desc['use_mask'] if 'use_mask' in desc else False
self.reduction = desc['reduction'] if 'reduction' in desc else 'mean'
self.... | Cross Entropy Loss. | CustomCrossEntropyLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomCrossEntropyLoss:
"""Cross Entropy Loss."""
def __init__(self, desc):
"""Init Cross Entropy loss. :param desc: config dict"""
<|body_0|>
def forward(self, cls_score, label, weight=None, avg_factor=None, reduction_override=None, **kwargs):
"""Forward compute... | stack_v2_sparse_classes_36k_train_024602 | 4,653 | permissive | [
{
"docstring": "Init Cross Entropy loss. :param desc: config dict",
"name": "__init__",
"signature": "def __init__(self, desc)"
},
{
"docstring": "Forward compute. :param cls_score: class score :param label: gt labels :param weight: weights :param avg_factor: avg factor :param reduction_override... | 2 | null | Implement the Python class `CustomCrossEntropyLoss` described below.
Class description:
Cross Entropy Loss.
Method signatures and docstrings:
- def __init__(self, desc): Init Cross Entropy loss. :param desc: config dict
- def forward(self, cls_score, label, weight=None, avg_factor=None, reduction_override=None, **kwa... | Implement the Python class `CustomCrossEntropyLoss` described below.
Class description:
Cross Entropy Loss.
Method signatures and docstrings:
- def __init__(self, desc): Init Cross Entropy loss. :param desc: config dict
- def forward(self, cls_score, label, weight=None, avg_factor=None, reduction_override=None, **kwa... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class CustomCrossEntropyLoss:
"""Cross Entropy Loss."""
def __init__(self, desc):
"""Init Cross Entropy loss. :param desc: config dict"""
<|body_0|>
def forward(self, cls_score, label, weight=None, avg_factor=None, reduction_override=None, **kwargs):
"""Forward compute... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomCrossEntropyLoss:
"""Cross Entropy Loss."""
def __init__(self, desc):
"""Init Cross Entropy loss. :param desc: config dict"""
super(CustomCrossEntropyLoss, self).__init__()
self.use_sigmoid = desc['use_sigmoid'] if 'use_sigmoid' in desc else False
self.use_mask = des... | the_stack_v2_python_sparse | zeus/networks/pytorch/losses/custom_cross_entropy_loss.py | huawei-noah/xingtian | train | 308 |
f69446230814e794529a3d5ced006360e74a44e6 | [
"VapiInterface.__init__(self, config, _InteropReportStub)\nself._VAPI_OPERATION_IDS = {}\nself._VAPI_OPERATION_IDS.update({'create_task': 'create$task'})",
"task_id = self._invoke('create$task', {'spec': spec})\ntask_svc = Tasks(self._config)\ntask_instance = Task(task_id, task_svc, type.ReferenceType(__name__, '... | <|body_start_0|>
VapiInterface.__init__(self, config, _InteropReportStub)
self._VAPI_OPERATION_IDS = {}
self._VAPI_OPERATION_IDS.update({'create_task': 'create$task'})
<|end_body_0|>
<|body_start_1|>
task_id = self._invoke('create$task', {'spec': spec})
task_svc = Tasks(self._co... | The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance. | InteropReport | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteropReport:
"""The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance."""
def __init__(self, config):
""":type config: :class:`vmware... | stack_v2_sparse_classes_36k_train_024603 | 39,273 | permissive | [
{
"docstring": ":type config: :class:`vmware.vapi.bindings.stub.StubConfiguration` :param config: Configuration to be used for creating the stub.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Creates interoperability report between a vCenter Server release ve... | 2 | stack_v2_sparse_classes_30k_train_009506 | Implement the Python class `InteropReport` described below.
Class description:
The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance.
Method signatures and docstrings:
-... | Implement the Python class `InteropReport` described below.
Class description:
The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance.
Method signatures and docstrings:
-... | c07e1be98615201139b26c28db3aa584c4254b66 | <|skeleton|>
class InteropReport:
"""The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance."""
def __init__(self, config):
""":type config: :class:`vmware... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InteropReport:
"""The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance."""
def __init__(self, config):
""":type config: :class:`vmware.vapi.binding... | the_stack_v2_python_sparse | com/vmware/vcenter/lcm/discovery_client.py | adammillerio/vsphere-automation-sdk-python | train | 0 |
2bb585ad2a30602bcdb6220ba8bdc0fe0f79791e | [
"super().__init__()\nself.conv1 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1, bias_attr=True)\nself.conv2 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1, bias_attr=True)\nself.relu = nn.ReLU()",
"x = self.relu(x)\nout = self.conv1(x)\nout = self.relu(out)\nout = self.conv... | <|body_start_0|>
super().__init__()
self.conv1 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1, bias_attr=True)
self.conv2 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1, bias_attr=True)
self.relu = nn.ReLU()
<|end_body_0|>
<|body_start_1|>
... | Residual convolution module. | ResidualConvUnit | [
"MIT",
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualConvUnit:
"""Residual convolution module."""
def __init__(self, features):
"""Init. Args: features (int): number of features"""
<|body_0|>
def forward(self, x):
"""Forward pass. Args: x (tensor): input Returns: tensor: output"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_024604 | 4,881 | permissive | [
{
"docstring": "Init. Args: features (int): number of features",
"name": "__init__",
"signature": "def __init__(self, features)"
},
{
"docstring": "Forward pass. Args: x (tensor): input Returns: tensor: output",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | null | Implement the Python class `ResidualConvUnit` described below.
Class description:
Residual convolution module.
Method signatures and docstrings:
- def __init__(self, features): Init. Args: features (int): number of features
- def forward(self, x): Forward pass. Args: x (tensor): input Returns: tensor: output | Implement the Python class `ResidualConvUnit` described below.
Class description:
Residual convolution module.
Method signatures and docstrings:
- def __init__(self, features): Init. Args: features (int): number of features
- def forward(self, x): Forward pass. Args: x (tensor): input Returns: tensor: output
<|skele... | 038fb5afe017b82334ad39a256531d2c4e9e1e1a | <|skeleton|>
class ResidualConvUnit:
"""Residual convolution module."""
def __init__(self, features):
"""Init. Args: features (int): number of features"""
<|body_0|>
def forward(self, x):
"""Forward pass. Args: x (tensor): input Returns: tensor: output"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResidualConvUnit:
"""Residual convolution module."""
def __init__(self, features):
"""Init. Args: features (int): number of features"""
super().__init__()
self.conv1 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1, bias_attr=True)
self.conv2 = nn.Conv2D(... | the_stack_v2_python_sparse | 15.PaddleGAN/PaddleGAN/ppgan/apps/midas/blocks.py | yingshaoxo/ML | train | 5 |
d548bb5632eeafd2be09d6bb0b03af651c3553fa | [
"threading.Thread.__init__(self)\nself.server = serv\nself.clientList = []\nself.running = True\nlogFile = 'abls.log'\nlogging.basicConfig(filename=logFile, level=logging.DEBUG)\nself.keyMgr = keyMgr\nself.loggedIn = False",
"global MSG_LOGIN\nself.shim = DBShim('/Users/caw/Projects/SecureLoggingSystem/src/Databa... | <|body_start_0|>
threading.Thread.__init__(self)
self.server = serv
self.clientList = []
self.running = True
logFile = 'abls.log'
logging.basicConfig(filename=logFile, level=logging.DEBUG)
self.keyMgr = keyMgr
self.loggedIn = False
<|end_body_0|>
<|body_s... | This is an active thread that is responsible for serving all messages that come in from audit proxy. | AuditClientHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuditClientHandler:
"""This is an active thread that is responsible for serving all messages that come in from audit proxy."""
def __init__(self, serv, keyMgr):
"""Initialize the client handler with the parent server (AuditProxy)"""
<|body_0|>
def run(self):
"""T... | stack_v2_sparse_classes_36k_train_024605 | 1,869 | no_license | [
{
"docstring": "Initialize the client handler with the parent server (AuditProxy)",
"name": "__init__",
"signature": "def __init__(self, serv, keyMgr)"
},
{
"docstring": "The main loop for this client handler thread. Strip out a message, parse it according to the protocol, and then invoke the ne... | 2 | null | Implement the Python class `AuditClientHandler` described below.
Class description:
This is an active thread that is responsible for serving all messages that come in from audit proxy.
Method signatures and docstrings:
- def __init__(self, serv, keyMgr): Initialize the client handler with the parent server (AuditProx... | Implement the Python class `AuditClientHandler` described below.
Class description:
This is an active thread that is responsible for serving all messages that come in from audit proxy.
Method signatures and docstrings:
- def __init__(self, serv, keyMgr): Initialize the client handler with the parent server (AuditProx... | 24a826f760c7412da371d022e07fe0fe14e27fba | <|skeleton|>
class AuditClientHandler:
"""This is an active thread that is responsible for serving all messages that come in from audit proxy."""
def __init__(self, serv, keyMgr):
"""Initialize the client handler with the parent server (AuditProxy)"""
<|body_0|>
def run(self):
"""T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuditClientHandler:
"""This is an active thread that is responsible for serving all messages that come in from audit proxy."""
def __init__(self, serv, keyMgr):
"""Initialize the client handler with the parent server (AuditProxy)"""
threading.Thread.__init__(self)
self.server = se... | the_stack_v2_python_sparse | src/main/core/AuditModule/AuditStrategy.py | chris-wood/SecureLoggingSystem | train | 1 |
e2e6d7a9bbe85219b05eac77ead939d91b29db8c | [
"self.set_header('content-type', 'application/json')\nuser_id = self.user.id\ntry:\n query_result = LogQueryDao().get_user_logquerys(user_id)\n logquerys = [_.to_dict() for _ in query_result]\n self.finish(json.dumps({'status': 0, 'msg': 'ok', 'values': logquerys}))\nexcept Exception as e:\n logger.erro... | <|body_start_0|>
self.set_header('content-type', 'application/json')
user_id = self.user.id
try:
query_result = LogQueryDao().get_user_logquerys(user_id)
logquerys = [_.to_dict() for _ in query_result]
self.finish(json.dumps({'status': 0, 'msg': 'ok', 'values'... | LogQueryConfigHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogQueryConfigHandler:
def get(self):
"""根据用户id搜索日志查询列表 :return: [{fromtime:, endtime:, terms:, show_cols:}] @API summary: 获取日志查询列表 notes: 获取日志查询列表 tags: - platform produces: - application/json"""
<|body_0|>
def post(self):
"""添加或者修改日志查询 @API summary: 添加或者修改日志查询 note... | stack_v2_sparse_classes_36k_train_024606 | 3,138 | permissive | [
{
"docstring": "根据用户id搜索日志查询列表 :return: [{fromtime:, endtime:, terms:, show_cols:}] @API summary: 获取日志查询列表 notes: 获取日志查询列表 tags: - platform produces: - application/json",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "添加或者修改日志查询 @API summary: 添加或者修改日志查询 notes: 以有无id判断是添加或修改操作 tag... | 3 | stack_v2_sparse_classes_30k_train_015628 | Implement the Python class `LogQueryConfigHandler` described below.
Class description:
Implement the LogQueryConfigHandler class.
Method signatures and docstrings:
- def get(self): 根据用户id搜索日志查询列表 :return: [{fromtime:, endtime:, terms:, show_cols:}] @API summary: 获取日志查询列表 notes: 获取日志查询列表 tags: - platform produces: - a... | Implement the Python class `LogQueryConfigHandler` described below.
Class description:
Implement the LogQueryConfigHandler class.
Method signatures and docstrings:
- def get(self): 根据用户id搜索日志查询列表 :return: [{fromtime:, endtime:, terms:, show_cols:}] @API summary: 获取日志查询列表 notes: 获取日志查询列表 tags: - platform produces: - a... | 2e32e6e7b225e0bd87ee8c847c22862f12c51bb1 | <|skeleton|>
class LogQueryConfigHandler:
def get(self):
"""根据用户id搜索日志查询列表 :return: [{fromtime:, endtime:, terms:, show_cols:}] @API summary: 获取日志查询列表 notes: 获取日志查询列表 tags: - platform produces: - application/json"""
<|body_0|>
def post(self):
"""添加或者修改日志查询 @API summary: 添加或者修改日志查询 note... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogQueryConfigHandler:
def get(self):
"""根据用户id搜索日志查询列表 :return: [{fromtime:, endtime:, terms:, show_cols:}] @API summary: 获取日志查询列表 notes: 获取日志查询列表 tags: - platform produces: - application/json"""
self.set_header('content-type', 'application/json')
user_id = self.user.id
try:
... | the_stack_v2_python_sparse | nebula/views/logquery.py | threathunterX/nebula_web | train | 2 | |
01c85ffb40f5a48c6033f1ca80304aec3963e86c | [
"year_dao = YearDAO()\ntry:\n year = year_dao.find_by_slug(year_slug)\n public_galleries = list(filter(lambda gallery: not gallery.private, year.galleries))\n return ({'year': year_dao.serialize(year_slug), 'public_galleries': [gallery.slug for gallery in public_galleries]}, 200)\nexcept NoResultFound:\n ... | <|body_start_0|>
year_dao = YearDAO()
try:
year = year_dao.find_by_slug(year_slug)
public_galleries = list(filter(lambda gallery: not gallery.private, year.galleries))
return ({'year': year_dao.serialize(year_slug), 'public_galleries': [gallery.slug for gallery in pub... | Year | [
"LicenseRef-scancode-public-domain",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Year:
def get(self, year_slug):
"""Get the list of public galleries of a given year"""
<|body_0|>
def delete(self, year_slug):
"""Delete a given year"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
year_dao = YearDAO()
try:
year ... | stack_v2_sparse_classes_36k_train_024607 | 20,155 | permissive | [
{
"docstring": "Get the list of public galleries of a given year",
"name": "get",
"signature": "def get(self, year_slug)"
},
{
"docstring": "Delete a given year",
"name": "delete",
"signature": "def delete(self, year_slug)"
}
] | 2 | null | Implement the Python class `Year` described below.
Class description:
Implement the Year class.
Method signatures and docstrings:
- def get(self, year_slug): Get the list of public galleries of a given year
- def delete(self, year_slug): Delete a given year | Implement the Python class `Year` described below.
Class description:
Implement the Year class.
Method signatures and docstrings:
- def get(self, year_slug): Get the list of public galleries of a given year
- def delete(self, year_slug): Delete a given year
<|skeleton|>
class Year:
def get(self, year_slug):
... | 2a1b53d5fa07621fa3e41b10e26af9dd32b0e874 | <|skeleton|>
class Year:
def get(self, year_slug):
"""Get the list of public galleries of a given year"""
<|body_0|>
def delete(self, year_slug):
"""Delete a given year"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Year:
def get(self, year_slug):
"""Get the list of public galleries of a given year"""
year_dao = YearDAO()
try:
year = year_dao.find_by_slug(year_slug)
public_galleries = list(filter(lambda gallery: not gallery.private, year.galleries))
return ({'ye... | the_stack_v2_python_sparse | web/app/ponthe/api/private/routes.py | adriensade/Galeries | train | 0 | |
61a77abcc6a8dc7c218f7df2fb2cf5cdd0dc6ede | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AccessPackageAssignmentRequestCallbackData()",
"from .access_package_custom_extension_stage import AccessPackageCustomExtensionStage\nfrom .custom_extension_data import CustomExtensionData\nfrom .access_package_custom_extension_stage i... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AccessPackageAssignmentRequestCallbackData()
<|end_body_0|>
<|body_start_1|>
from .access_package_custom_extension_stage import AccessPackageCustomExtensionStage
from .custom_extension_d... | AccessPackageAssignmentRequestCallbackData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessPackageAssignmentRequestCallbackData:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageAssignmentRequestCallbackData:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to ... | stack_v2_sparse_classes_36k_train_024608 | 3,917 | 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: AccessPackageAssignmentRequestCallbackData",
"name": "create_from_discriminator_value",
"signature": "def cr... | 3 | null | Implement the Python class `AccessPackageAssignmentRequestCallbackData` described below.
Class description:
Implement the AccessPackageAssignmentRequestCallbackData class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageAssignmentRequestCal... | Implement the Python class `AccessPackageAssignmentRequestCallbackData` described below.
Class description:
Implement the AccessPackageAssignmentRequestCallbackData class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageAssignmentRequestCal... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AccessPackageAssignmentRequestCallbackData:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageAssignmentRequestCallbackData:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccessPackageAssignmentRequestCallbackData:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageAssignmentRequestCallbackData:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discr... | the_stack_v2_python_sparse | msgraph/generated/models/access_package_assignment_request_callback_data.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
d99076c73561af3b8140b8da225fac8333c6f608 | [
"assert imgs.ndim == 4, 'data ndim must be 4 (batch, rows, cols, chans)'\nself.num_examples, self.num_rows, self.num_cols, self.num_channels = imgs.shape\nself.images = imgs\nself.ndim = imgs.ndim\nself.shape = imgs.shape\nself.num_pixels = np.prod(self.shape[1:])\nself.labels = lbls\nself.ignore_labels = ignore_lb... | <|body_start_0|>
assert imgs.ndim == 4, 'data ndim must be 4 (batch, rows, cols, chans)'
self.num_examples, self.num_rows, self.num_cols, self.num_channels = imgs.shape
self.images = imgs
self.ndim = imgs.ndim
self.shape = imgs.shape
self.num_pixels = np.prod(self.shape[1... | Dataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
def __init__(self, imgs, lbls, ignore_lbls=None, rand_state=np.random.RandomState()):
"""Inputs: imgs [np.ndarray] of ndim 4 (examples, rows, cols, channels) lbls [np.ndarray] of ndim 2 (examples, labels) ignore_lbls [np.ndarray] of same shape as lbls rand_state [np.random.Rando... | stack_v2_sparse_classes_36k_train_024609 | 4,397 | permissive | [
{
"docstring": "Inputs: imgs [np.ndarray] of ndim 4 (examples, rows, cols, channels) lbls [np.ndarray] of ndim 2 (examples, labels) ignore_lbls [np.ndarray] of same shape as lbls rand_state [np.random.RandomState]",
"name": "__init__",
"signature": "def __init__(self, imgs, lbls, ignore_lbls=None, rand_... | 6 | null | Implement the Python class `Dataset` described below.
Class description:
Implement the Dataset class.
Method signatures and docstrings:
- def __init__(self, imgs, lbls, ignore_lbls=None, rand_state=np.random.RandomState()): Inputs: imgs [np.ndarray] of ndim 4 (examples, rows, cols, channels) lbls [np.ndarray] of ndim... | Implement the Python class `Dataset` described below.
Class description:
Implement the Dataset class.
Method signatures and docstrings:
- def __init__(self, imgs, lbls, ignore_lbls=None, rand_state=np.random.RandomState()): Inputs: imgs [np.ndarray] of ndim 4 (examples, rows, cols, channels) lbls [np.ndarray] of ndim... | c872706c8bfbecdae57707f41bfd76e5b09b3f03 | <|skeleton|>
class Dataset:
def __init__(self, imgs, lbls, ignore_lbls=None, rand_state=np.random.RandomState()):
"""Inputs: imgs [np.ndarray] of ndim 4 (examples, rows, cols, channels) lbls [np.ndarray] of ndim 2 (examples, labels) ignore_lbls [np.ndarray] of same shape as lbls rand_state [np.random.Rando... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset:
def __init__(self, imgs, lbls, ignore_lbls=None, rand_state=np.random.RandomState()):
"""Inputs: imgs [np.ndarray] of ndim 4 (examples, rows, cols, channels) lbls [np.ndarray] of ndim 2 (examples, labels) ignore_lbls [np.ndarray] of same shape as lbls rand_state [np.random.RandomState]"""
... | the_stack_v2_python_sparse | tf1x/data/dataset.py | dpaiton/DeepSparseCoding | train | 14 | |
0c7c692536dc5e58d65661314e16b826ad56779f | [
"self.object = self.get_object()\nimages = self.object.simple_image_assets.all()\nform = SimpleImageForm()\nreturn {'images': images, 'form': form}",
"self.object = self.get_object()\ndocuments = self.object.simple_document_assets.all()\nform = SimpleDocumentForm()\nreturn {'documents': documents, 'form': form}",... | <|body_start_0|>
self.object = self.get_object()
images = self.object.simple_image_assets.all()
form = SimpleImageForm()
return {'images': images, 'form': form}
<|end_body_0|>
<|body_start_1|>
self.object = self.get_object()
documents = self.object.simple_document_assets... | Show call details. | CallDetailView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallDetailView:
"""Show call details."""
def simple_images(self):
"""Return simple images."""
<|body_0|>
def simple_documents(self):
"""Return simple documents."""
<|body_1|>
def simple_audio(self):
"""Return simple audio."""
<|body_2... | stack_v2_sparse_classes_36k_train_024610 | 28,644 | permissive | [
{
"docstring": "Return simple images.",
"name": "simple_images",
"signature": "def simple_images(self)"
},
{
"docstring": "Return simple documents.",
"name": "simple_documents",
"signature": "def simple_documents(self)"
},
{
"docstring": "Return simple audio.",
"name": "simpl... | 4 | stack_v2_sparse_classes_30k_train_004921 | Implement the Python class `CallDetailView` described below.
Class description:
Show call details.
Method signatures and docstrings:
- def simple_images(self): Return simple images.
- def simple_documents(self): Return simple documents.
- def simple_audio(self): Return simple audio.
- def simple_video(self): Return s... | Implement the Python class `CallDetailView` described below.
Class description:
Show call details.
Method signatures and docstrings:
- def simple_images(self): Return simple images.
- def simple_documents(self): Return simple documents.
- def simple_audio(self): Return simple audio.
- def simple_video(self): Return s... | dc6bc79d450f7e2bdf59cfbcd306d05a736e4db9 | <|skeleton|>
class CallDetailView:
"""Show call details."""
def simple_images(self):
"""Return simple images."""
<|body_0|>
def simple_documents(self):
"""Return simple documents."""
<|body_1|>
def simple_audio(self):
"""Return simple audio."""
<|body_2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CallDetailView:
"""Show call details."""
def simple_images(self):
"""Return simple images."""
self.object = self.get_object()
images = self.object.simple_image_assets.all()
form = SimpleImageForm()
return {'images': images, 'form': form}
def simple_documents(s... | the_stack_v2_python_sparse | project/editorial/views/contractors.py | ProjectFacet/facet | train | 25 |
063c5c857da3d42ac7cd1025fc22786d732b571d | [
"text = WikipediaParser.EXTRACTOR.transform(text)\ntext = WikipediaParser.EXTRACTOR.wiki2text(text)\ntext = WikipediaParser.REF_EXP1.sub('', text)\ntext = WikipediaParser.REF_EXP2.sub('', text)\nreturn text",
"for _, elem in etree.iterparse(fn, tag=WikipediaParser.WIKI_NAMESPACE + 'page'):\n title = elem.findt... | <|body_start_0|>
text = WikipediaParser.EXTRACTOR.transform(text)
text = WikipediaParser.EXTRACTOR.wiki2text(text)
text = WikipediaParser.REF_EXP1.sub('', text)
text = WikipediaParser.REF_EXP2.sub('', text)
return text
<|end_body_0|>
<|body_start_1|>
for _, elem in etree... | WikipediaParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikipediaParser:
def preprocess(text):
"""preprocess string"""
<|body_0|>
def iterparse(self, fn):
"""parse iteratively"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
text = WikipediaParser.EXTRACTOR.transform(text)
text = WikipediaParser.E... | stack_v2_sparse_classes_36k_train_024611 | 1,712 | no_license | [
{
"docstring": "preprocess string",
"name": "preprocess",
"signature": "def preprocess(text)"
},
{
"docstring": "parse iteratively",
"name": "iterparse",
"signature": "def iterparse(self, fn)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016455 | Implement the Python class `WikipediaParser` described below.
Class description:
Implement the WikipediaParser class.
Method signatures and docstrings:
- def preprocess(text): preprocess string
- def iterparse(self, fn): parse iteratively | Implement the Python class `WikipediaParser` described below.
Class description:
Implement the WikipediaParser class.
Method signatures and docstrings:
- def preprocess(text): preprocess string
- def iterparse(self, fn): parse iteratively
<|skeleton|>
class WikipediaParser:
def preprocess(text):
"""prep... | fc1c7e9a9280b2bc4798a1e211d4634f9e8704d3 | <|skeleton|>
class WikipediaParser:
def preprocess(text):
"""preprocess string"""
<|body_0|>
def iterparse(self, fn):
"""parse iteratively"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WikipediaParser:
def preprocess(text):
"""preprocess string"""
text = WikipediaParser.EXTRACTOR.transform(text)
text = WikipediaParser.EXTRACTOR.wiki2text(text)
text = WikipediaParser.REF_EXP1.sub('', text)
text = WikipediaParser.REF_EXP2.sub('', text)
return te... | the_stack_v2_python_sparse | indexer/bz2parse.py | ashwinpn/WikiSea | train | 0 | |
a56036d071ebec4abf9e3c445f90d6545614bb7b | [
"self.Z = Z\nself.M = len(Z) - 1\nassert Z.shape[0] - 2 == l.shape[0] == k.shape[0] - 2\nself.k = k\nself.l = l\nself.phase = self.k[1:-1, :] * self.l\nself.tau = Z[1:, :] * 2 / (Z[0:-1, :] + Z[1:, :])\nself.rho = (Z[1:, :] - Z[0:-1, :]) / (Z[1:, :] + Z[0:-1, :])\nself.Gammas = []\nself.tau = []",
"rho = self.rho... | <|body_start_0|>
self.Z = Z
self.M = len(Z) - 1
assert Z.shape[0] - 2 == l.shape[0] == k.shape[0] - 2
self.k = k
self.l = l
self.phase = self.k[1:-1, :] * self.l
self.tau = Z[1:, :] * 2 / (Z[0:-1, :] + Z[1:, :])
self.rho = (Z[1:, :] - Z[0:-1, :]) / (Z[1:, ... | SlabStructure | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlabStructure:
def __init__(self, Z, l, k):
"""Initialze a slab structure of stacked impedance surfaces with different thicknesses Z0 | Z1 | Z2 | ... | ZN-1 | ZN l1 | l2 | ... | lN-1"""
<|body_0|>
def build_gamma(self):
"""Get the scattering coefficient of the stacke... | stack_v2_sparse_classes_36k_train_024612 | 5,545 | no_license | [
{
"docstring": "Initialze a slab structure of stacked impedance surfaces with different thicknesses Z0 | Z1 | Z2 | ... | ZN-1 | ZN l1 | l2 | ... | lN-1",
"name": "__init__",
"signature": "def __init__(self, Z, l, k)"
},
{
"docstring": "Get the scattering coefficient of the stacked structure by r... | 3 | stack_v2_sparse_classes_30k_train_003309 | Implement the Python class `SlabStructure` described below.
Class description:
Implement the SlabStructure class.
Method signatures and docstrings:
- def __init__(self, Z, l, k): Initialze a slab structure of stacked impedance surfaces with different thicknesses Z0 | Z1 | Z2 | ... | ZN-1 | ZN l1 | l2 | ... | lN-1
- d... | Implement the Python class `SlabStructure` described below.
Class description:
Implement the SlabStructure class.
Method signatures and docstrings:
- def __init__(self, Z, l, k): Initialze a slab structure of stacked impedance surfaces with different thicknesses Z0 | Z1 | Z2 | ... | ZN-1 | ZN l1 | l2 | ... | lN-1
- d... | 1e7f001ec54682dbcd96f743a3ef7219985a3c6f | <|skeleton|>
class SlabStructure:
def __init__(self, Z, l, k):
"""Initialze a slab structure of stacked impedance surfaces with different thicknesses Z0 | Z1 | Z2 | ... | ZN-1 | ZN l1 | l2 | ... | lN-1"""
<|body_0|>
def build_gamma(self):
"""Get the scattering coefficient of the stacke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SlabStructure:
def __init__(self, Z, l, k):
"""Initialze a slab structure of stacked impedance surfaces with different thicknesses Z0 | Z1 | Z2 | ... | ZN-1 | ZN l1 | l2 | ... | lN-1"""
self.Z = Z
self.M = len(Z) - 1
assert Z.shape[0] - 2 == l.shape[0] == k.shape[0] - 2
... | the_stack_v2_python_sparse | python_scripts/slab_scattering.py | UmrathSt/metamaterials | train | 1 | |
2e0911386131492c0fa74ac6899e6e79db31e8eb | [
"TYPE, ID = ('type', 'id')\nPERSON, GROUP = ('person', 'group')\nquery_type = request.query_params.get(TYPE, None)\nquery_id = request.query_params.get(ID, None)\nif query_type == GROUP:\n data = AuthorService.get_author_group_info(group_id=query_id, user_service=UserService())\n return SimpleResponse(data)\n... | <|body_start_0|>
TYPE, ID = ('type', 'id')
PERSON, GROUP = ('person', 'group')
query_type = request.query_params.get(TYPE, None)
query_id = request.query_params.get(ID, None)
if query_type == GROUP:
data = AuthorService.get_author_group_info(group_id=query_id, user_se... | AuthorViewSet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthorViewSet:
def list(self, request):
"""获得关于作者的信息,根据参数的不同可以获得单个user的和user_group的信息 ### Request Example: /author/type=person&id=asdhjk21hjkads2134 获取用户id为XXX的个人信息 /author/type=group&id=asdhjk21hjkads2134 获取作者群组id为XXX的群组信息 type -- 查询类型 (person | group) id -- 用户或者group的id (String), !注意, ... | stack_v2_sparse_classes_36k_train_024613 | 9,000 | permissive | [
{
"docstring": "获得关于作者的信息,根据参数的不同可以获得单个user的和user_group的信息 ### Request Example: /author/type=person&id=asdhjk21hjkads2134 获取用户id为XXX的个人信息 /author/type=group&id=asdhjk21hjkads2134 获取作者群组id为XXX的群组信息 type -- 查询类型 (person | group) id -- 用户或者group的id (String), !注意, id两个字母均为小写 --- omit_serializer: true",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_016501 | Implement the Python class `AuthorViewSet` described below.
Class description:
Implement the AuthorViewSet class.
Method signatures and docstrings:
- def list(self, request): 获得关于作者的信息,根据参数的不同可以获得单个user的和user_group的信息 ### Request Example: /author/type=person&id=asdhjk21hjkads2134 获取用户id为XXX的个人信息 /author/type=group&id... | Implement the Python class `AuthorViewSet` described below.
Class description:
Implement the AuthorViewSet class.
Method signatures and docstrings:
- def list(self, request): 获得关于作者的信息,根据参数的不同可以获得单个user的和user_group的信息 ### Request Example: /author/type=person&id=asdhjk21hjkads2134 获取用户id为XXX的个人信息 /author/type=group&id... | 31ac08148fbe67ab166faa897c0cbe72cd7f62db | <|skeleton|>
class AuthorViewSet:
def list(self, request):
"""获得关于作者的信息,根据参数的不同可以获得单个user的和user_group的信息 ### Request Example: /author/type=person&id=asdhjk21hjkads2134 获取用户id为XXX的个人信息 /author/type=group&id=asdhjk21hjkads2134 获取作者群组id为XXX的群组信息 type -- 查询类型 (person | group) id -- 用户或者group的id (String), !注意, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthorViewSet:
def list(self, request):
"""获得关于作者的信息,根据参数的不同可以获得单个user的和user_group的信息 ### Request Example: /author/type=person&id=asdhjk21hjkads2134 获取用户id为XXX的个人信息 /author/type=group&id=asdhjk21hjkads2134 获取作者群组id为XXX的群组信息 type -- 查询类型 (person | group) id -- 用户或者group的id (String), !注意, id两个字母均为小写 ---... | the_stack_v2_python_sparse | wheat/apps/book/apis.py | fortyMiles/moment-note | train | 2 | |
9ad687a235263b2dcdd782d71d47b89ff973d3a0 | [
"self.list = []\nself.sum = 0\nself.capacity = size\nself.size = 0\nself.flag = 0",
"if self.size < self.capacity:\n self.list.append(val)\n self.size += 1.0\n self.sum += val\n return self.sum / self.size\nelse:\n self.sum -= self.list[self.flag]\n self.flag += 1\n self.list.append(val)\n ... | <|body_start_0|>
self.list = []
self.sum = 0
self.capacity = size
self.size = 0
self.flag = 0
<|end_body_0|>
<|body_start_1|>
if self.size < self.capacity:
self.list.append(val)
self.size += 1.0
self.sum += val
return self.... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.list = []
self.sum = 0
... | stack_v2_sparse_classes_36k_train_024614 | 889 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | null | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 6d361cad2821248350f1d8432fdfef86895ca281 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.list = []
self.sum = 0
self.capacity = size
self.size = 0
self.flag = 0
def next(self, val):
""":type val: int :rtype: float"""
if self.... | the_stack_v2_python_sparse | Design/movingAverage.py | tr1503/LeetCode | train | 0 | |
10a992aa6aa356853d8348f4d7521e65ae6bb39b | [
"mock_client = Taxii2FeedClient(url='', collection_to_fetch=None, proxies=[], verify=False, objects_to_fetch=[])\nwith pytest.raises(DemistoException, match='Could not find a collection to fetch from.'):\n mock_client.build_iterator()",
"mock_client = Taxii2FeedClient(url='', collection_to_fetch=None, proxies=... | <|body_start_0|>
mock_client = Taxii2FeedClient(url='', collection_to_fetch=None, proxies=[], verify=False, objects_to_fetch=[])
with pytest.raises(DemistoException, match='Could not find a collection to fetch from.'):
mock_client.build_iterator()
<|end_body_0|>
<|body_start_1|>
moc... | Scenario: Get indicators via build_iterator method | TestBuildIterator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBuildIterator:
"""Scenario: Get indicators via build_iterator method"""
def test_no_collection_to_fetch(self):
"""Scenario: Fail to build iterator when there is no collection to fetch from Given: - Collection to fetch is empty When: - Calling build_iterators Then: - Ensure except... | stack_v2_sparse_classes_36k_train_024615 | 15,321 | permissive | [
{
"docstring": "Scenario: Fail to build iterator when there is no collection to fetch from Given: - Collection to fetch is empty When: - Calling build_iterators Then: - Ensure exception is raised with proper error message",
"name": "test_no_collection_to_fetch",
"signature": "def test_no_collection_to_f... | 3 | null | Implement the Python class `TestBuildIterator` described below.
Class description:
Scenario: Get indicators via build_iterator method
Method signatures and docstrings:
- def test_no_collection_to_fetch(self): Scenario: Fail to build iterator when there is no collection to fetch from Given: - Collection to fetch is em... | Implement the Python class `TestBuildIterator` described below.
Class description:
Scenario: Get indicators via build_iterator method
Method signatures and docstrings:
- def test_no_collection_to_fetch(self): Scenario: Fail to build iterator when there is no collection to fetch from Given: - Collection to fetch is em... | 01b57f8c658c2faed047313d3034e8052ffa83ce | <|skeleton|>
class TestBuildIterator:
"""Scenario: Get indicators via build_iterator method"""
def test_no_collection_to_fetch(self):
"""Scenario: Fail to build iterator when there is no collection to fetch from Given: - Collection to fetch is empty When: - Calling build_iterators Then: - Ensure except... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestBuildIterator:
"""Scenario: Get indicators via build_iterator method"""
def test_no_collection_to_fetch(self):
"""Scenario: Fail to build iterator when there is no collection to fetch from Given: - Collection to fetch is empty When: - Calling build_iterators Then: - Ensure exception is raised... | the_stack_v2_python_sparse | Packs/ApiModules/Scripts/TAXII2ApiModule/TAXII2ApiModule_test.py | adambaumeister/content | train | 2 |
025a2da059013785fecfcaf19bfbd8e042158938 | [
"ret = None\nl = []\nmapper = StudentJSONMapper()\nfor student in students:\n l.append(mapper.map_to_json(student))\nreturn json.dumps(l, indent=4, sort_keys=True)",
"l = []\nmapper = StudentJSONMapper()\nfor student in students:\n l.append(mapper.map_to_json(student))\nwith open(filename, 'w') as fh:\n ... | <|body_start_0|>
ret = None
l = []
mapper = StudentJSONMapper()
for student in students:
l.append(mapper.map_to_json(student))
return json.dumps(l, indent=4, sort_keys=True)
<|end_body_0|>
<|body_start_1|>
l = []
mapper = StudentJSONMapper()
f... | This class is used for exporting students to JSON files, and importing students from JSON files. | StudentJSONSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentJSONSerializer:
"""This class is used for exporting students to JSON files, and importing students from JSON files."""
def exportAsJSON(self, students):
"""Generates JSON data from students :param students: list of model.Student.Student-s :return: JSON data"""
<|body_0... | stack_v2_sparse_classes_36k_train_024616 | 1,650 | no_license | [
{
"docstring": "Generates JSON data from students :param students: list of model.Student.Student-s :return: JSON data",
"name": "exportAsJSON",
"signature": "def exportAsJSON(self, students)"
},
{
"docstring": "Exports students to the JSON file with the given filename. :param students: list of m... | 3 | stack_v2_sparse_classes_30k_train_010856 | Implement the Python class `StudentJSONSerializer` described below.
Class description:
This class is used for exporting students to JSON files, and importing students from JSON files.
Method signatures and docstrings:
- def exportAsJSON(self, students): Generates JSON data from students :param students: list of model... | Implement the Python class `StudentJSONSerializer` described below.
Class description:
This class is used for exporting students to JSON files, and importing students from JSON files.
Method signatures and docstrings:
- def exportAsJSON(self, students): Generates JSON data from students :param students: list of model... | a30389aa4542a23011a955ac61bf5b853c3e7854 | <|skeleton|>
class StudentJSONSerializer:
"""This class is used for exporting students to JSON files, and importing students from JSON files."""
def exportAsJSON(self, students):
"""Generates JSON data from students :param students: list of model.Student.Student-s :return: JSON data"""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StudentJSONSerializer:
"""This class is used for exporting students to JSON files, and importing students from JSON files."""
def exportAsJSON(self, students):
"""Generates JSON data from students :param students: list of model.Student.Student-s :return: JSON data"""
ret = None
l ... | the_stack_v2_python_sparse | serializer/StudentJSONSerializer.py | edutilos6666/PythonSciStudentProject | train | 0 |
6e7f3ad14bf079b61e88f95a18e0a7e1e0758cd4 | [
"self.ctype = 'columns_calculate'\n'str: type of data processor'\nself.keys = keys\nself.lam = lam\nself.dtypes = [self.typecast(d) for d in dtypes]",
"tmp_df = self.lam(lam_arg)\nfor key, dtype in zip(self.keys, self.dtypes):\n lam_arg[key] = tmp_df[key]\n lam_arg[key] = lam_arg[key].astype(dtype)\nreturn ... | <|body_start_0|>
self.ctype = 'columns_calculate'
'str: type of data processor'
self.keys = keys
self.lam = lam
self.dtypes = [self.typecast(d) for d in dtypes]
<|end_body_0|>
<|body_start_1|>
tmp_df = self.lam(lam_arg)
for key, dtype in zip(self.keys, self.dtype... | Used to calculate new column values to add to the DataFrame | ColumnsCalculate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColumnsCalculate:
"""Used to calculate new column values to add to the DataFrame"""
def __init__(self, keys: List[str], lam: Callable[[pd.DataFrame], pd.DataFrame], dtypes: List[Any]):
"""Creates a ColumnsCalculate object Args: keys: A list of the keys to add/replace in the existing ... | stack_v2_sparse_classes_36k_train_024617 | 3,115 | permissive | [
{
"docstring": "Creates a ColumnsCalculate object Args: keys: A list of the keys to add/replace in the existing DataFrame lam: A function that takes as parameter a DataFrame, and returns a DataFrame with column names matching ``keys`` and the columns having/being castable to ``dtypes`` dtypes: A list of python ... | 2 | null | Implement the Python class `ColumnsCalculate` described below.
Class description:
Used to calculate new column values to add to the DataFrame
Method signatures and docstrings:
- def __init__(self, keys: List[str], lam: Callable[[pd.DataFrame], pd.DataFrame], dtypes: List[Any]): Creates a ColumnsCalculate object Args:... | Implement the Python class `ColumnsCalculate` described below.
Class description:
Used to calculate new column values to add to the DataFrame
Method signatures and docstrings:
- def __init__(self, keys: List[str], lam: Callable[[pd.DataFrame], pd.DataFrame], dtypes: List[Any]): Creates a ColumnsCalculate object Args:... | 8c8b14280441f5153ff146c23359a0eb91022ddb | <|skeleton|>
class ColumnsCalculate:
"""Used to calculate new column values to add to the DataFrame"""
def __init__(self, keys: List[str], lam: Callable[[pd.DataFrame], pd.DataFrame], dtypes: List[Any]):
"""Creates a ColumnsCalculate object Args: keys: A list of the keys to add/replace in the existing ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColumnsCalculate:
"""Used to calculate new column values to add to the DataFrame"""
def __init__(self, keys: List[str], lam: Callable[[pd.DataFrame], pd.DataFrame], dtypes: List[Any]):
"""Creates a ColumnsCalculate object Args: keys: A list of the keys to add/replace in the existing DataFrame lam... | the_stack_v2_python_sparse | src/api2db/ingest/post_process/columns_calculate.py | TristenHarr/api2db | train | 46 |
2093a28f0be7675b204dab7f6fa01d38bb512cc3 | [
"self.inletNode = inletNode\nself.idealinletNode = idealinletNode\nself.outletNode = outletNode",
"\"\"\"the cycle based on compressor inlet\"\"\"\n'node outelt = state 1'\n'Exp'\n'State 1, P1,T1 known'\n'pressure loss and heat exchange parameters'\nself.dp = node[self.inletNode].p - node[self.idealinletNode].p\n... | <|body_start_0|>
self.inletNode = inletNode
self.idealinletNode = idealinletNode
self.outletNode = outletNode
<|end_body_0|>
<|body_start_1|>
"""the cycle based on compressor inlet"""
'node outelt = state 1'
'Exp'
'State 1, P1,T1 known'
'pressure loss and... | evaporator component | Evaporator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Evaporator:
"""evaporator component"""
def __init__(self, inletNode, outletNode, idealinletNode):
"""init evaporator node"""
<|body_0|>
def simulate(self, node, mdot_a, cp, Ta_in, Ta_out):
"""ideal"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_024618 | 3,605 | no_license | [
{
"docstring": "init evaporator node",
"name": "__init__",
"signature": "def __init__(self, inletNode, outletNode, idealinletNode)"
},
{
"docstring": "ideal",
"name": "simulate",
"signature": "def simulate(self, node, mdot_a, cp, Ta_in, Ta_out)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000419 | Implement the Python class `Evaporator` described below.
Class description:
evaporator component
Method signatures and docstrings:
- def __init__(self, inletNode, outletNode, idealinletNode): init evaporator node
- def simulate(self, node, mdot_a, cp, Ta_in, Ta_out): ideal | Implement the Python class `Evaporator` described below.
Class description:
evaporator component
Method signatures and docstrings:
- def __init__(self, inletNode, outletNode, idealinletNode): init evaporator node
- def simulate(self, node, mdot_a, cp, Ta_in, Ta_out): ideal
<|skeleton|>
class Evaporator:
"""evapo... | 6843fd139ff2355b98eac0ac9cf09aee6fede7cd | <|skeleton|>
class Evaporator:
"""evaporator component"""
def __init__(self, inletNode, outletNode, idealinletNode):
"""init evaporator node"""
<|body_0|>
def simulate(self, node, mdot_a, cp, Ta_in, Ta_out):
"""ideal"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Evaporator:
"""evaporator component"""
def __init__(self, inletNode, outletNode, idealinletNode):
"""init evaporator node"""
self.inletNode = inletNode
self.idealinletNode = idealinletNode
self.outletNode = outletNode
def simulate(self, node, mdot_a, cp, Ta_in, Ta_out... | the_stack_v2_python_sparse | original/component.py | Nathanzhn/GA4 | train | 0 |
27edd0935d7d301b998b804b9c769d665962febe | [
"super(CreateIncrementalVersionTask, self).__init__(*args, **kwargs)\nself.setOption('incremental', True)\nself.setOption('incrementalSpecificVersion', 0)",
"if metadata is None:\n metadata = {}\nif 'sourceVersion' not in metadata:\n metadata['sourceVersion'] = self.version()\nsuper(CreateIncrementalVersion... | <|body_start_0|>
super(CreateIncrementalVersionTask, self).__init__(*args, **kwargs)
self.setOption('incremental', True)
self.setOption('incrementalSpecificVersion', 0)
<|end_body_0|>
<|body_start_1|>
if metadata is None:
metadata = {}
if 'sourceVersion' not in metad... | ABC for creating an incremental version. | CreateIncrementalVersionTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateIncrementalVersionTask:
"""ABC for creating an incremental version."""
def __init__(self, *args, **kwargs):
"""Create a version."""
<|body_0|>
def addFile(self, filePath, metadata=None):
"""Add a file a published to the version. This information is used to ... | stack_v2_sparse_classes_36k_train_024619 | 4,077 | permissive | [
{
"docstring": "Create a version.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Add a file a published to the version. This information is used to write \"files.json\" where metadata information can be associated with the file through metadata parame... | 4 | stack_v2_sparse_classes_30k_test_000130 | Implement the Python class `CreateIncrementalVersionTask` described below.
Class description:
ABC for creating an incremental version.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a version.
- def addFile(self, filePath, metadata=None): Add a file a published to the version. This in... | Implement the Python class `CreateIncrementalVersionTask` described below.
Class description:
ABC for creating an incremental version.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a version.
- def addFile(self, filePath, metadata=None): Add a file a published to the version. This in... | 046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4 | <|skeleton|>
class CreateIncrementalVersionTask:
"""ABC for creating an incremental version."""
def __init__(self, *args, **kwargs):
"""Create a version."""
<|body_0|>
def addFile(self, filePath, metadata=None):
"""Add a file a published to the version. This information is used to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateIncrementalVersionTask:
"""ABC for creating an incremental version."""
def __init__(self, *args, **kwargs):
"""Create a version."""
super(CreateIncrementalVersionTask, self).__init__(*args, **kwargs)
self.setOption('incremental', True)
self.setOption('incrementalSpec... | the_stack_v2_python_sparse | src/lib/kombi/Task/Version/CreateIncrementalVersionTask.py | kombiHQ/kombi | train | 2 |
4662410ae513856d393f7d755cea9c2fe1ed0261 | [
"jumps, curEnd, curFarthest, n = (0, 0, 0, len(nums))\nfor i in range(n - 1):\n curFarthest = max(nums[i] + i, curFarthest)\n if i == curEnd:\n jumps += 1\n curEnd = curFarthest\nreturn jumps",
"if not nums or len(nums) < 2:\n return 0\n\ndef maxIdx(jumpRange):\n maximumIdx = 0\n maxN... | <|body_start_0|>
jumps, curEnd, curFarthest, n = (0, 0, 0, len(nums))
for i in range(n - 1):
curFarthest = max(nums[i] + i, curFarthest)
if i == curEnd:
jumps += 1
curEnd = curFarthest
return jumps
<|end_body_0|>
<|body_start_1|>
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def jump2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
jumps, curEnd, curFarthest, n = (0, 0, 0, len(nums))
... | stack_v2_sparse_classes_36k_train_024620 | 1,560 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "jump",
"signature": "def jump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "jump2",
"signature": "def jump2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004244 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): :type nums: List[int] :rtype: int
- def jump2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): :type nums: List[int] :rtype: int
- def jump2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def jump(self, nums):
... | 75aef2f6c42aeb51261b9450a24099957a084d51 | <|skeleton|>
class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def jump2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
jumps, curEnd, curFarthest, n = (0, 0, 0, len(nums))
for i in range(n - 1):
curFarthest = max(nums[i] + i, curFarthest)
if i == curEnd:
jumps += 1
curEnd = cu... | the_stack_v2_python_sparse | Python/0045_JumpGame2/jump.py | mtmmy/Leetcode | train | 3 | |
c1bd690b5c0c4305db1daa6f2024ac6ab57f6972 | [
"self.param = Config()\nself.param.width = width\nself.param.target = target\nself.param.time = time.time()\nself.param.n = 0\nself.param.unit_name = unit_name\nself.param.verbose = verbose\nself.param.current = 0\nif verbose:\n self.param.logger = Logger()",
"if not self.param.verbose:\n return 0\nself.par... | <|body_start_0|>
self.param = Config()
self.param.width = width
self.param.target = target
self.param.time = time.time()
self.param.n = 0
self.param.unit_name = unit_name
self.param.verbose = verbose
self.param.current = 0
if verbose:
s... | Displays a progress bar. | Progbar | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Progbar:
"""Displays a progress bar."""
def __init__(self, target, width=25, verbose=1, unit_name='step'):
"""Args: target: Total number of steps expected, None if unknown. width: Progress bar width on screen. verbose: Verbosity mode, 0 (silent), 1 (verbose) unit_name: Display name f... | stack_v2_sparse_classes_36k_train_024621 | 4,106 | permissive | [
{
"docstring": "Args: target: Total number of steps expected, None if unknown. width: Progress bar width on screen. verbose: Verbosity mode, 0 (silent), 1 (verbose) unit_name: Display name for step counts (usually \"step\" or \"sample\").",
"name": "__init__",
"signature": "def __init__(self, target, wi... | 3 | stack_v2_sparse_classes_30k_train_011660 | Implement the Python class `Progbar` described below.
Class description:
Displays a progress bar.
Method signatures and docstrings:
- def __init__(self, target, width=25, verbose=1, unit_name='step'): Args: target: Total number of steps expected, None if unknown. width: Progress bar width on screen. verbose: Verbosit... | Implement the Python class `Progbar` described below.
Class description:
Displays a progress bar.
Method signatures and docstrings:
- def __init__(self, target, width=25, verbose=1, unit_name='step'): Args: target: Total number of steps expected, None if unknown. width: Progress bar width on screen. verbose: Verbosit... | dbaab809939d3af52c6d57b6df0553ea18024bf4 | <|skeleton|>
class Progbar:
"""Displays a progress bar."""
def __init__(self, target, width=25, verbose=1, unit_name='step'):
"""Args: target: Total number of steps expected, None if unknown. width: Progress bar width on screen. verbose: Verbosity mode, 0 (silent), 1 (verbose) unit_name: Display name f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Progbar:
"""Displays a progress bar."""
def __init__(self, target, width=25, verbose=1, unit_name='step'):
"""Args: target: Total number of steps expected, None if unknown. width: Progress bar width on screen. verbose: Verbosity mode, 0 (silent), 1 (verbose) unit_name: Display name for step count... | the_stack_v2_python_sparse | linora/utils/_progbar.py | Hourout/linora | train | 11 |
8e2d37d3848a28427cf801da86557efa125ccf88 | [
"try:\n natController = NatController()\n json_data = json.dumps(natController.get_floating_ip_public_address(id))\n resp = Response(json_data, status=200, mimetype='application/json')\n return resp\nexcept ValueError as ve:\n logging.debug(ve)\n return Response(status=404)\nexcept Exception as er... | <|body_start_0|>
try:
natController = NatController()
json_data = json.dumps(natController.get_floating_ip_public_address(id))
resp = Response(json_data, status=200, mimetype='application/json')
return resp
except ValueError as ve:
logging.debu... | Nat_FloatingIP_PublicAddress | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nat_FloatingIP_PublicAddress:
def get(self, id=None):
"""Gets the Floating IP public address parameter"""
<|body_0|>
def put(self, id):
"""Update the Floating IP public address parameter"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_024622 | 6,500 | no_license | [
{
"docstring": "Gets the Floating IP public address parameter",
"name": "get",
"signature": "def get(self, id=None)"
},
{
"docstring": "Update the Floating IP public address parameter",
"name": "put",
"signature": "def put(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000885 | Implement the Python class `Nat_FloatingIP_PublicAddress` described below.
Class description:
Implement the Nat_FloatingIP_PublicAddress class.
Method signatures and docstrings:
- def get(self, id=None): Gets the Floating IP public address parameter
- def put(self, id): Update the Floating IP public address parameter | Implement the Python class `Nat_FloatingIP_PublicAddress` described below.
Class description:
Implement the Nat_FloatingIP_PublicAddress class.
Method signatures and docstrings:
- def get(self, id=None): Gets the Floating IP public address parameter
- def put(self, id): Update the Floating IP public address parameter... | b543ca1f90e1463a08e15ab45c7248e1db238327 | <|skeleton|>
class Nat_FloatingIP_PublicAddress:
def get(self, id=None):
"""Gets the Floating IP public address parameter"""
<|body_0|>
def put(self, id):
"""Update the Floating IP public address parameter"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Nat_FloatingIP_PublicAddress:
def get(self, id=None):
"""Gets the Floating IP public address parameter"""
try:
natController = NatController()
json_data = json.dumps(natController.get_floating_ip_public_address(id))
resp = Response(json_data, status=200, mim... | the_stack_v2_python_sparse | configuration-agent/nat/rest_api/resources/floating_ip.py | piscoroma/Configurable-VNF | train | 0 | |
58997fb14bcabf70d1e6d44d3a1fb25d09f37284 | [
"if self.action == 'list':\n return serializers.PageLiteSerializer\nreturn super().get_serializer_class()",
"domain = self.request.get_host()\nif domain in settings.FRONTEND_HOME_URL:\n return self.queryset.filter(site__isnull=True)\nreturn self.queryset.filter(site__domain=domain)"
] | <|body_start_0|>
if self.action == 'list':
return serializers.PageLiteSerializer
return super().get_serializer_class()
<|end_body_0|>
<|body_start_1|>
domain = self.request.get_host()
if domain in settings.FRONTEND_HOME_URL:
return self.queryset.filter(site__isnu... | Viewset for the API of the ``page`` object. | PageViewSet | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PageViewSet:
"""Viewset for the API of the ``page`` object."""
def get_serializer_class(self):
"""Get serializer for this view based on the current action."""
<|body_0|>
def get_queryset(self):
"""Filter pages based on the current domain."""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_024623 | 1,383 | permissive | [
{
"docstring": "Get serializer for this view based on the current action.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Filter pages based on the current domain.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
}
] | 2 | null | Implement the Python class `PageViewSet` described below.
Class description:
Viewset for the API of the ``page`` object.
Method signatures and docstrings:
- def get_serializer_class(self): Get serializer for this view based on the current action.
- def get_queryset(self): Filter pages based on the current domain. | Implement the Python class `PageViewSet` described below.
Class description:
Viewset for the API of the ``page`` object.
Method signatures and docstrings:
- def get_serializer_class(self): Get serializer for this view based on the current action.
- def get_queryset(self): Filter pages based on the current domain.
<|... | f767f1bdc12c9712f26ea17cb8b19f536389f0ed | <|skeleton|>
class PageViewSet:
"""Viewset for the API of the ``page`` object."""
def get_serializer_class(self):
"""Get serializer for this view based on the current action."""
<|body_0|>
def get_queryset(self):
"""Filter pages based on the current domain."""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PageViewSet:
"""Viewset for the API of the ``page`` object."""
def get_serializer_class(self):
"""Get serializer for this view based on the current action."""
if self.action == 'list':
return serializers.PageLiteSerializer
return super().get_serializer_class()
def... | the_stack_v2_python_sparse | src/backend/marsha/page/api.py | openfun/marsha | train | 92 |
f00defa699fd87c608a01f9856165bda5e4a0fc3 | [
"TrainerMixin.__init__(self)\nself.estimator = estimator\nself.file_path = file_path",
"mask_kgb = y != -1\nmask_igb = ~mask_kgb\nX_kgb, y_kgb, X_igb = (X[mask_kgb], y[mask_kgb], X[mask_igb])\nself.estimator.fit(X_kgb, y_kgb)\nX_igb_bad, X_igb_good = (X_igb.copy(), X_igb.copy())\nX_igb_bad['weight'] = self.estima... | <|body_start_0|>
TrainerMixin.__init__(self)
self.estimator = estimator
self.file_path = file_path
<|end_body_0|>
<|body_start_1|>
mask_kgb = y != -1
mask_igb = ~mask_kgb
X_kgb, y_kgb, X_igb = (X[mask_kgb], y[mask_kgb], X[mask_igb])
self.estimator.fit(X_kgb, y_kg... | 模糊展开法 step 1. 构建KGB模型,并对拒绝样本打分,得到P(good)和P(bad)。 step 2. 将每条拒绝样本复制为不同类别,不同权重的两条:一条标记为good,权重为P(good);另一条标记为bad,权重为P(bad)。 step 3. 利用变换后的拒绝样本和放贷已知好坏样本(类别不变,权重设为1)建立AGB模型。 | FuzzyAugmentation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FuzzyAugmentation:
"""模糊展开法 step 1. 构建KGB模型,并对拒绝样本打分,得到P(good)和P(bad)。 step 2. 将每条拒绝样本复制为不同类别,不同权重的两条:一条标记为good,权重为P(good);另一条标记为bad,权重为P(bad)。 step 3. 利用变换后的拒绝样本和放贷已知好坏样本(类别不变,权重设为1)建立AGB模型。"""
def __init__(self, estimator, file_path: str=None):
"""初始化函数 :param estimator: 学习器, 学习器fi... | stack_v2_sparse_classes_36k_train_024624 | 17,175 | no_license | [
{
"docstring": "初始化函数 :param estimator: 学习器, 学习器fit必须包含权重参数 :param file_path: 最终建模使用样本输出路径",
"name": "__init__",
"signature": "def __init__(self, estimator, file_path: str=None)"
},
{
"docstring": "拟合学习器 :param X: 包括通过样本和拒绝样本 :param y: -1代表拒绝样本,0,1代表通过样本 :return:",
"name": "fit",
"signat... | 2 | stack_v2_sparse_classes_30k_train_010304 | Implement the Python class `FuzzyAugmentation` described below.
Class description:
模糊展开法 step 1. 构建KGB模型,并对拒绝样本打分,得到P(good)和P(bad)。 step 2. 将每条拒绝样本复制为不同类别,不同权重的两条:一条标记为good,权重为P(good);另一条标记为bad,权重为P(bad)。 step 3. 利用变换后的拒绝样本和放贷已知好坏样本(类别不变,权重设为1)建立AGB模型。
Method signatures and docstrings:
- def __init__(self, estimator,... | Implement the Python class `FuzzyAugmentation` described below.
Class description:
模糊展开法 step 1. 构建KGB模型,并对拒绝样本打分,得到P(good)和P(bad)。 step 2. 将每条拒绝样本复制为不同类别,不同权重的两条:一条标记为good,权重为P(good);另一条标记为bad,权重为P(bad)。 step 3. 利用变换后的拒绝样本和放贷已知好坏样本(类别不变,权重设为1)建立AGB模型。
Method signatures and docstrings:
- def __init__(self, estimator,... | 1634ac69e8616f85c4233039e2d40246149a1617 | <|skeleton|>
class FuzzyAugmentation:
"""模糊展开法 step 1. 构建KGB模型,并对拒绝样本打分,得到P(good)和P(bad)。 step 2. 将每条拒绝样本复制为不同类别,不同权重的两条:一条标记为good,权重为P(good);另一条标记为bad,权重为P(bad)。 step 3. 利用变换后的拒绝样本和放贷已知好坏样本(类别不变,权重设为1)建立AGB模型。"""
def __init__(self, estimator, file_path: str=None):
"""初始化函数 :param estimator: 学习器, 学习器fi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FuzzyAugmentation:
"""模糊展开法 step 1. 构建KGB模型,并对拒绝样本打分,得到P(good)和P(bad)。 step 2. 将每条拒绝样本复制为不同类别,不同权重的两条:一条标记为good,权重为P(good);另一条标记为bad,权重为P(bad)。 step 3. 利用变换后的拒绝样本和放贷已知好坏样本(类别不变,权重设为1)建立AGB模型。"""
def __init__(self, estimator, file_path: str=None):
"""初始化函数 :param estimator: 学习器, 学习器fit必须包含权重参数 :pa... | the_stack_v2_python_sparse | model_training/RITrainer.py | pengliang1226/model_procedure | train | 0 |
a65c4958009b7a18433563f561c32f68bc3dcefb | [
"ObjectManager.__init__(self)\nself.getters.update({'achievements': 'get_many_to_many', 'name': 'get_general', 'organization': 'get_foreign_key', 'tasks': 'get_many_to_many'})\nself.setters.update({'achievements': 'set_many', 'name': 'set_general', 'organization': 'set_foreign_key', 'tasks': 'set_many'})\nself.my_d... | <|body_start_0|>
ObjectManager.__init__(self)
self.getters.update({'achievements': 'get_many_to_many', 'name': 'get_general', 'organization': 'get_foreign_key', 'tasks': 'get_many_to_many'})
self.setters.update({'achievements': 'set_many', 'name': 'set_general', 'organization': 'set_foreign_key'... | Manage curriculums in the Power Reg system | CurriculumManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurriculumManager:
"""Manage curriculums in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name, organization=None):
"""Create a new curriculum. :param name: human-readable name :param organization: organizat... | stack_v2_sparse_classes_36k_train_024625 | 1,529 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new curriculum. :param name: human-readable name :param organization: organization to which this belongs :return: a reference to the newly created curriculum",
"name": "create",
... | 2 | null | Implement the Python class `CurriculumManager` described below.
Class description:
Manage curriculums in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name, organization=None): Create a new curriculum. :param name: human-readable name :param or... | Implement the Python class `CurriculumManager` described below.
Class description:
Manage curriculums in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name, organization=None): Create a new curriculum. :param name: human-readable name :param or... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class CurriculumManager:
"""Manage curriculums in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name, organization=None):
"""Create a new curriculum. :param name: human-readable name :param organization: organizat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CurriculumManager:
"""Manage curriculums in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.getters.update({'achievements': 'get_many_to_many', 'name': 'get_general', 'organization': 'get_foreign_key', 'tasks': 'get_many_to_many'})
... | the_stack_v2_python_sparse | pr_services/credential_system/curriculum_manager.py | ninemoreminutes/openassign-server | train | 0 |
aa4c6f10795ae00117ff3fdeb1c77f2b2f3964e7 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IosStoreAppAssignmentSettings()",
"from .mobile_app_assignment_settings import MobileAppAssignmentSettings\nfrom .mobile_app_assignment_settings import MobileAppAssignmentSettings\nfields: Dict[str, Callable[[Any], None]] = {'isRemovab... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IosStoreAppAssignmentSettings()
<|end_body_0|>
<|body_start_1|>
from .mobile_app_assignment_settings import MobileAppAssignmentSettings
from .mobile_app_assignment_settings import Mobile... | Contains properties used to assign an iOS Store mobile app to a group. | IosStoreAppAssignmentSettings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IosStoreAppAssignmentSettings:
"""Contains properties used to assign an iOS Store mobile app to a group."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosStoreAppAssignmentSettings:
"""Creates a new instance of the appropriate class based on discrimi... | stack_v2_sparse_classes_36k_train_024626 | 3,409 | 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: IosStoreAppAssignmentSettings",
"name": "create_from_discriminator_value",
"signature": "def create_from_dis... | 3 | stack_v2_sparse_classes_30k_train_016391 | Implement the Python class `IosStoreAppAssignmentSettings` described below.
Class description:
Contains properties used to assign an iOS Store mobile app to a group.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosStoreAppAssignmentSettings: Creates ... | Implement the Python class `IosStoreAppAssignmentSettings` described below.
Class description:
Contains properties used to assign an iOS Store mobile app to a group.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosStoreAppAssignmentSettings: Creates ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IosStoreAppAssignmentSettings:
"""Contains properties used to assign an iOS Store mobile app to a group."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosStoreAppAssignmentSettings:
"""Creates a new instance of the appropriate class based on discrimi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IosStoreAppAssignmentSettings:
"""Contains properties used to assign an iOS Store mobile app to a group."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosStoreAppAssignmentSettings:
"""Creates a new instance of the appropriate class based on discriminator value A... | the_stack_v2_python_sparse | msgraph/generated/models/ios_store_app_assignment_settings.py | microsoftgraph/msgraph-sdk-python | train | 135 |
435f48322403ca8e571f3bccfe8cc3a0a1677b7e | [
"super().__init__()\ncheck_boundaries(boundaries)\nself.boundaries = boundaries",
"self.randomize(None)\nself.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1])\nlength = signal.shape[1]\ngaussiannoise = self.magnitude * torch.randn(length)\nsignal = convert_to_tensor(signal) + gaussianno... | <|body_start_0|>
super().__init__()
check_boundaries(boundaries)
self.boundaries = boundaries
<|end_body_0|>
<|body_start_1|>
self.randomize(None)
self.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1])
length = signal.shape[1]
gaussianno... | Add a random gaussian noise to the input signal | SignalRandAddGaussianNoise | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalRandAddGaussianNoise:
"""Add a random gaussian noise to the input signal"""
def __init__(self, boundaries: Sequence[float]=(0.001, 0.02)) -> None:
"""Args: boundaries: list defining lower and upper boundaries for the signal magnitude, default : ``[0.001,0.02]``"""
<|bod... | stack_v2_sparse_classes_36k_train_024627 | 16,322 | permissive | [
{
"docstring": "Args: boundaries: list defining lower and upper boundaries for the signal magnitude, default : ``[0.001,0.02]``",
"name": "__init__",
"signature": "def __init__(self, boundaries: Sequence[float]=(0.001, 0.02)) -> None"
},
{
"docstring": "Args: signal: input 1 dimension signal to ... | 2 | stack_v2_sparse_classes_30k_train_013046 | Implement the Python class `SignalRandAddGaussianNoise` described below.
Class description:
Add a random gaussian noise to the input signal
Method signatures and docstrings:
- def __init__(self, boundaries: Sequence[float]=(0.001, 0.02)) -> None: Args: boundaries: list defining lower and upper boundaries for the sign... | Implement the Python class `SignalRandAddGaussianNoise` described below.
Class description:
Add a random gaussian noise to the input signal
Method signatures and docstrings:
- def __init__(self, boundaries: Sequence[float]=(0.001, 0.02)) -> None: Args: boundaries: list defining lower and upper boundaries for the sign... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class SignalRandAddGaussianNoise:
"""Add a random gaussian noise to the input signal"""
def __init__(self, boundaries: Sequence[float]=(0.001, 0.02)) -> None:
"""Args: boundaries: list defining lower and upper boundaries for the signal magnitude, default : ``[0.001,0.02]``"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignalRandAddGaussianNoise:
"""Add a random gaussian noise to the input signal"""
def __init__(self, boundaries: Sequence[float]=(0.001, 0.02)) -> None:
"""Args: boundaries: list defining lower and upper boundaries for the signal magnitude, default : ``[0.001,0.02]``"""
super().__init__()... | the_stack_v2_python_sparse | monai/transforms/signal/array.py | Project-MONAI/MONAI | train | 4,805 |
88000392ff7ed945a764d5d379e590379727bad8 | [
"super().__init__()\nself.unified_encoder = unified_encoder\nself.mlp = mlp",
"enc_src, _, _ = self.unified_encoder(*args)\nenc_src = enc_src.view(enc_src.shape[0], -1)\ny_pred = self.mlp(enc_src)\nreturn y_pred",
"data = (seq_cat_data, seq_cont_data, non_seq_cat_data, non_seq_cont_data)\nnonempty_tensors, none... | <|body_start_0|>
super().__init__()
self.unified_encoder = unified_encoder
self.mlp = mlp
<|end_body_0|>
<|body_start_1|>
enc_src, _, _ = self.unified_encoder(*args)
enc_src = enc_src.view(enc_src.shape[0], -1)
y_pred = self.mlp(enc_src)
return y_pred
<|end_body_... | TransformerChurnModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerChurnModel:
def __init__(self, unified_encoder, mlp):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1|>
def run(self, y, seq_cat_data, seq_cont_data, non_seq_ca... | stack_v2_sparse_classes_36k_train_024628 | 15,906 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, unified_encoder, mlp)"
},
{
"docstring": "Run a forward pass of model over the data.",
"name": "forward",
"signature": "def forward(self, *args)"
},
{
"docstring": "Run model on d... | 3 | stack_v2_sparse_classes_30k_train_009253 | Implement the Python class `TransformerChurnModel` described below.
Class description:
Implement the TransformerChurnModel class.
Method signatures and docstrings:
- def __init__(self, unified_encoder, mlp): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over the data.
- def run... | Implement the Python class `TransformerChurnModel` described below.
Class description:
Implement the TransformerChurnModel class.
Method signatures and docstrings:
- def __init__(self, unified_encoder, mlp): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over the data.
- def run... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class TransformerChurnModel:
def __init__(self, unified_encoder, mlp):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1|>
def run(self, y, seq_cat_data, seq_cont_data, non_seq_ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerChurnModel:
def __init__(self, unified_encoder, mlp):
"""Initialize model with params."""
super().__init__()
self.unified_encoder = unified_encoder
self.mlp = mlp
def forward(self, *args):
"""Run a forward pass of model over the data."""
enc_src,... | the_stack_v2_python_sparse | caspr/models/model_wrapper.py | microsoft/CASPR | train | 29 | |
ab628d0359650e08333c624ae1d2768a11bfa243 | [
"dp = (target + 1) * [0]\ndp[0] = 1\nfor i in range(1, target + 1):\n for j in nums:\n if i - j >= 0 and dp[i - j] > 0:\n dp[i] += dp[i - j]\nreturn dp[-1]",
"if not nums:\n return 0\nif target in self.dp:\n return self.dp[target]\ncount = 0\nfor i in nums:\n if target - i > 0:\n ... | <|body_start_0|>
dp = (target + 1) * [0]
dp[0] = 1
for i in range(1, target + 1):
for j in nums:
if i - j >= 0 and dp[i - j] > 0:
dp[i] += dp[i - j]
return dp[-1]
<|end_body_0|>
<|body_start_1|>
if not nums:
return 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum4(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int O(target*len(nums))"""
<|body_0|>
def combinationSum4(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_024629 | 1,221 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int O(target*len(nums))",
"name": "combinationSum4",
"signature": "def combinationSum4(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "combinationSum4",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_011686 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum4(self, nums, target): :type nums: List[int] :type target: int :rtype: int O(target*len(nums))
- def combinationSum4(self, nums, target): :type nums: List[int] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum4(self, nums, target): :type nums: List[int] :type target: int :rtype: int O(target*len(nums))
- def combinationSum4(self, nums, target): :type nums: List[int] ... | 8853f85214ac88db024d26e228f1848dd5acd933 | <|skeleton|>
class Solution:
def combinationSum4(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int O(target*len(nums))"""
<|body_0|>
def combinationSum4(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum4(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int O(target*len(nums))"""
dp = (target + 1) * [0]
dp[0] = 1
for i in range(1, target + 1):
for j in nums:
if i - j >= 0 and dp[i - j] > 0:
... | the_stack_v2_python_sparse | 377-CombinationSumIV/CombinationSumIV.py | cqxmzhc/my_leetcode_solutions | train | 2 | |
e0fa6ce4fd73a919851cd92f671d5a0a1bbeae9a | [
"if not s:\n return True\nleft, right = (0, len(s) - 1)\nwhile left < right:\n if s[left] != s[right]:\n return False\n left += 1\n right -= 1\nreturn True",
"if not s:\n return True\nleft, right = (0, len(s) - 1)\nwhile left < right:\n if s[left] != s[right]:\n return self.isPalin... | <|body_start_0|>
if not s:
return True
left, right = (0, len(s) - 1)
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
<|end_body_0|>
<|body_start_1|>
if not s:
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def validPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s:
return True
left, right = (0, le... | stack_v2_sparse_classes_36k_train_024630 | 788 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "validPalindrome",
"signature": "def validPalindrome(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s): :type s: str :rtype: bool
- def validPalindrome(self, s): :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s): :type s: str :rtype: bool
- def validPalindrome(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def isPalindrome(self, s):
... | 5b14b6f42baf59b04cbcc8e115df4272029b64c8 | <|skeleton|>
class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def validPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
if not s:
return True
left, right = (0, len(s) - 1)
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return ... | the_stack_v2_python_sparse | LeetCode/0680.Valid-Palindrome-Ii/Valid-Palindrome-Ii.py | htingwang/HandsOnAlgoDS | train | 12 | |
8f4452d3505f74421c421657a9b4d698b11b80fe | [
"super().__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(units=hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(units=dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(epsilo... | <|body_start_0|>
super().__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(units=hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(units=dm)
self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)
self... | class Encoder block | EncoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderBlock:
"""class Encoder block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""* dropout1 - the first dropout layer * dropout2 - the second dropout layer"""
<|body_0|>
def call(self, x, training, mask=None):
"""Returns: a tensor of shape (batch, inp... | stack_v2_sparse_classes_36k_train_024631 | 1,665 | no_license | [
{
"docstring": "* dropout1 - the first dropout layer * dropout2 - the second dropout layer",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "Returns: a tensor of shape (batch, input_seq_len, dm) containing the block’s output",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_010112 | Implement the Python class `EncoderBlock` described below.
Class description:
class Encoder block
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): * dropout1 - the first dropout layer * dropout2 - the second dropout layer
- def call(self, x, training, mask=None): Returns: a tensor... | Implement the Python class `EncoderBlock` described below.
Class description:
class Encoder block
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): * dropout1 - the first dropout layer * dropout2 - the second dropout layer
- def call(self, x, training, mask=None): Returns: a tensor... | 9ff78818c132d1233c11b8fc8fd469878b23b14e | <|skeleton|>
class EncoderBlock:
"""class Encoder block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""* dropout1 - the first dropout layer * dropout2 - the second dropout layer"""
<|body_0|>
def call(self, x, training, mask=None):
"""Returns: a tensor of shape (batch, inp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderBlock:
"""class Encoder block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""* dropout1 - the first dropout layer * dropout2 - the second dropout layer"""
super().__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(unit... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/7-transformer_encoder_block.py | Nzparra/holbertonschool-machine_learning | train | 0 |
f4377b24bbf4e50cd88ca47cf0e0b62fec7b5435 | [
"parser = parent.add_parser('port', help='retrieve ports from containers')\nparser.add_flag('--all', '-a', help='List all known port mappings for running containers')\nparser.add_argument('containers', nargs='*', help='containers to list ports')\nparser.set_defaults(class_=cls, method='port')",
"if not args.all a... | <|body_start_0|>
parser = parent.add_parser('port', help='retrieve ports from containers')
parser.add_flag('--all', '-a', help='List all known port mappings for running containers')
parser.add_argument('containers', nargs='*', help='containers to list ports')
parser.set_defaults(class_=c... | Class for retrieving ports from container. | Port | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Port:
"""Class for retrieving ports from container."""
def subparser(cls, parent):
"""Add Port command to parent parser."""
<|body_0|>
def __init__(self, args):
"""Construct Port class."""
<|body_1|>
def port(self):
"""Retrieve ports from con... | stack_v2_sparse_classes_36k_train_024632 | 1,992 | permissive | [
{
"docstring": "Add Port command to parent parser.",
"name": "subparser",
"signature": "def subparser(cls, parent)"
},
{
"docstring": "Construct Port class.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Retrieve ports from containers.",
"nam... | 3 | stack_v2_sparse_classes_30k_train_003054 | Implement the Python class `Port` described below.
Class description:
Class for retrieving ports from container.
Method signatures and docstrings:
- def subparser(cls, parent): Add Port command to parent parser.
- def __init__(self, args): Construct Port class.
- def port(self): Retrieve ports from containers. | Implement the Python class `Port` described below.
Class description:
Class for retrieving ports from container.
Method signatures and docstrings:
- def subparser(cls, parent): Add Port command to parent parser.
- def __init__(self, args): Construct Port class.
- def port(self): Retrieve ports from containers.
<|ske... | 94a46127cb0db2b6187186788a941ec72af476dd | <|skeleton|>
class Port:
"""Class for retrieving ports from container."""
def subparser(cls, parent):
"""Add Port command to parent parser."""
<|body_0|>
def __init__(self, args):
"""Construct Port class."""
<|body_1|>
def port(self):
"""Retrieve ports from con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Port:
"""Class for retrieving ports from container."""
def subparser(cls, parent):
"""Add Port command to parent parser."""
parser = parent.add_parser('port', help='retrieve ports from containers')
parser.add_flag('--all', '-a', help='List all known port mappings for running conta... | the_stack_v2_python_sparse | pypodman/pypodman/lib/actions/port_action.py | 4383/python-podman | train | 0 |
63be88ee34c7a7c99cee6fb3528d4ecf9bfd7578 | [
"self._with_bkg_par = bool(with_bkg_par)\nself._t_start = float(t_start)\nself._exposure = float(exposure)\nself._seed = int(seed)\nself._simput = simput\nself._data_dir = data_dir\nself._ra_cen = ra_cen\nself._dec_cen = dec_cen",
"try:\n os.makedirs(self._data_dir)\nexcept OSError as e:\n print('already ex... | <|body_start_0|>
self._with_bkg_par = bool(with_bkg_par)
self._t_start = float(t_start)
self._exposure = float(exposure)
self._seed = int(seed)
self._simput = simput
self._data_dir = data_dir
self._ra_cen = ra_cen
self._dec_cen = dec_cen
<|end_body_0|>
<|... | SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up. | Simulator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulator:
"""SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up."""
def __init__(self, with_bkg_par, t_start, exposure, seed, simput, data_dir, ra_cen, dec_cen):
""":param with_bkg_p... | stack_v2_sparse_classes_36k_train_024633 | 5,418 | no_license | [
{
"docstring": ":param with_bkg_par: Simulate with particle background. :param t_start: Start time of simulation. Input units of [s] :param exposure: Length of time to simulate for after t_start :param seed: Seed for random number generator. :param simput: Simput file (ie. the sky model)",
"name": "__init__... | 5 | stack_v2_sparse_classes_30k_train_010308 | Implement the Python class `Simulator` described below.
Class description:
SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up.
Method signatures and docstrings:
- def __init__(self, with_bkg_par, t_start, exposure, se... | Implement the Python class `Simulator` described below.
Class description:
SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up.
Method signatures and docstrings:
- def __init__(self, with_bkg_par, t_start, exposure, se... | 2b8ac686b1d445a39fcd28dbe07ef467c0b14c7e | <|skeleton|>
class Simulator:
"""SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up."""
def __init__(self, with_bkg_par, t_start, exposure, seed, simput, data_dir, ra_cen, dec_cen):
""":param with_bkg_p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Simulator:
"""SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up."""
def __init__(self, with_bkg_par, t_start, exposure, seed, simput, data_dir, ra_cen, dec_cen):
""":param with_bkg_par: Simulate ... | the_stack_v2_python_sparse | python/sixte/simulate_agn_only.py | HuiboZhou/mocks_high_fidelity | train | 0 |
c574c4faf6b3c60e957a118e179e8e8e737d0774 | [
"self.archive = []\nself.phoenixPreferenceTable = {}\nself.updatePreferences = []\nself.activateSkeinview = preferences.BooleanPreference().getFromValue('Activate Skeinview', True)\nself.archive.append(self.activateSkeinview)\nself.displayLineTextWhenMouseMoves = preferences.BooleanPreference().getFromValue('Displa... | <|body_start_0|>
self.archive = []
self.phoenixPreferenceTable = {}
self.updatePreferences = []
self.activateSkeinview = preferences.BooleanPreference().getFromValue('Activate Skeinview', True)
self.archive.append(self.activateSkeinview)
self.displayLineTextWhenMouseMoves... | A class to handle the skeinview preferences. | SkeinviewPreferences | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkeinviewPreferences:
"""A class to handle the skeinview preferences."""
def __init__(self):
"""Set the default preferences, execute title & preferences fileName."""
<|body_0|>
def execute(self):
"""Write button has been clicked."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_024634 | 27,879 | no_license | [
{
"docstring": "Set the default preferences, execute title & preferences fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Write button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001574 | Implement the Python class `SkeinviewPreferences` described below.
Class description:
A class to handle the skeinview preferences.
Method signatures and docstrings:
- def __init__(self): Set the default preferences, execute title & preferences fileName.
- def execute(self): Write button has been clicked. | Implement the Python class `SkeinviewPreferences` described below.
Class description:
A class to handle the skeinview preferences.
Method signatures and docstrings:
- def __init__(self): Set the default preferences, execute title & preferences fileName.
- def execute(self): Write button has been clicked.
<|skeleton|... | 9e24dabbca21e67fecda1ed55a5af45dce41bfe2 | <|skeleton|>
class SkeinviewPreferences:
"""A class to handle the skeinview preferences."""
def __init__(self):
"""Set the default preferences, execute title & preferences fileName."""
<|body_0|>
def execute(self):
"""Write button has been clicked."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SkeinviewPreferences:
"""A class to handle the skeinview preferences."""
def __init__(self):
"""Set the default preferences, execute title & preferences fileName."""
self.archive = []
self.phoenixPreferenceTable = {}
self.updatePreferences = []
self.activateSkeinvi... | the_stack_v2_python_sparse | reprap_python_beanshell/skeinforge_tools/analyze_plugins/skeinview.py | TeamTeamUSA/SkeinFox | train | 0 |
cf444655fa0b7d615899bc0c9d088c6177a155ab | [
"self.browser.get(self.live_server_url + '/contacts')\ninput_name = self.get_item_by_id('name')\ninput_email = self.get_item_by_id('email')\ninput_subject = self.get_item_by_id('subject')\ninput_msg = self.get_item_by_id('message')\nbutton = self.get_item_by_id('form-submit')\ninput_name.send_keys('Joe')\ninput_ema... | <|body_start_0|>
self.browser.get(self.live_server_url + '/contacts')
input_name = self.get_item_by_id('name')
input_email = self.get_item_by_id('email')
input_subject = self.get_item_by_id('subject')
input_msg = self.get_item_by_id('message')
button = self.get_item_by_id... | Тест формы в разделе 'КОНТАКТЫ' | ContactFormTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContactFormTest:
"""Тест формы в разделе 'КОНТАКТЫ'"""
def test_can_send_fill_form_items(self):
"""тест: заполняем поля формы и отправляем в action, хотим видеть сообщение об успешной отправке"""
<|body_0|>
def test_cannot_send_empy_feild_of_form(self):
"""тест: ... | stack_v2_sparse_classes_36k_train_024635 | 2,923 | no_license | [
{
"docstring": "тест: заполняем поля формы и отправляем в action, хотим видеть сообщение об успешной отправке",
"name": "test_can_send_fill_form_items",
"signature": "def test_can_send_fill_form_items(self)"
},
{
"docstring": "тест: форма не отправляет пустые поля",
"name": "test_cannot_send... | 2 | stack_v2_sparse_classes_30k_train_001496 | Implement the Python class `ContactFormTest` described below.
Class description:
Тест формы в разделе 'КОНТАКТЫ'
Method signatures and docstrings:
- def test_can_send_fill_form_items(self): тест: заполняем поля формы и отправляем в action, хотим видеть сообщение об успешной отправке
- def test_cannot_send_empy_feild_... | Implement the Python class `ContactFormTest` described below.
Class description:
Тест формы в разделе 'КОНТАКТЫ'
Method signatures and docstrings:
- def test_can_send_fill_form_items(self): тест: заполняем поля формы и отправляем в action, хотим видеть сообщение об успешной отправке
- def test_cannot_send_empy_feild_... | df240ff50f51b390f7e27ca35841c6482642d97d | <|skeleton|>
class ContactFormTest:
"""Тест формы в разделе 'КОНТАКТЫ'"""
def test_can_send_fill_form_items(self):
"""тест: заполняем поля формы и отправляем в action, хотим видеть сообщение об успешной отправке"""
<|body_0|>
def test_cannot_send_empy_feild_of_form(self):
"""тест: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContactFormTest:
"""Тест формы в разделе 'КОНТАКТЫ'"""
def test_can_send_fill_form_items(self):
"""тест: заполняем поля формы и отправляем в action, хотим видеть сообщение об успешной отправке"""
self.browser.get(self.live_server_url + '/contacts')
input_name = self.get_item_by_id... | the_stack_v2_python_sparse | functional_tests/test_forms.py | Th0rn-dev/kiteupru | train | 0 |
8cda23dd5618502792feb639b94515308ee66749 | [
"self.matomo_url = matomo_url\nself.matomo_api_key = matomo_api_key\nself.matomo_api_key = '&token_auth=' + self.matomo_api_key\nself.ssl_verify = ssl_verify\nself.cleanmatomo_url()",
"self.matomo_url = re.sub('/\\\\/$/', '', self.matomo_url)\nif re.match('^http://', self.matomo_url):\n self.matomo_url = re.su... | <|body_start_0|>
self.matomo_url = matomo_url
self.matomo_api_key = matomo_api_key
self.matomo_api_key = '&token_auth=' + self.matomo_api_key
self.ssl_verify = ssl_verify
self.cleanmatomo_url()
<|end_body_0|>
<|body_start_1|>
self.matomo_url = re.sub('/\\/$/', '', self.m... | This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore. | MatomoApiManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatomoApiManager:
"""This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore."""
def __init__(self, matomo_url, matomo_api_key, ssl... | stack_v2_sparse_classes_36k_train_024636 | 4,420 | permissive | [
{
"docstring": "Constructor initialises matomo_url, matomo_api_key, ssl_verify :param matomo_url: :param matomo_api_key: :param ssl_verify:",
"name": "__init__",
"signature": "def __init__(self, matomo_url, matomo_api_key, ssl_verify)"
},
{
"docstring": "Cleans Matomo-URL for proper requests. Ch... | 4 | stack_v2_sparse_classes_30k_train_015853 | Implement the Python class `MatomoApiManager` described below.
Class description:
This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore.
Method signatures ... | Implement the Python class `MatomoApiManager` described below.
Class description:
This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore.
Method signatures ... | b769510570d5921e30876565263813c0362994e2 | <|skeleton|>
class MatomoApiManager:
"""This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore."""
def __init__(self, matomo_url, matomo_api_key, ssl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MatomoApiManager:
"""This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore."""
def __init__(self, matomo_url, matomo_api_key, ssl_verify):
... | the_stack_v2_python_sparse | src/cms/views/statistics/matomo_api_manager.py | digitalfabrik/coldaid-backend | train | 4 |
69720234042a8feb576a5a9455428b62b7ab5d19 | [
"rows = []\nfor neighbor in neighbors:\n v4Addr = (ipnetwork.sprint_addr(neighbor.transportAddressV4.addr),)\n v6Addr = (ipnetwork.sprint_addr(neighbor.transportAddressV6.addr),)\n helloMsgSentTimeDelta = str(datetime.timedelta(milliseconds=neighbor.lastHelloMsgSentTimeDelta))\n handshakeMsgSentTimeDelt... | <|body_start_0|>
rows = []
for neighbor in neighbors:
v4Addr = (ipnetwork.sprint_addr(neighbor.transportAddressV4.addr),)
v6Addr = (ipnetwork.sprint_addr(neighbor.transportAddressV6.addr),)
helloMsgSentTimeDelta = str(datetime.timedelta(milliseconds=neighbor.lastHello... | SparkBaseCmd | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparkBaseCmd:
def print_spark_neighbors_detailed(self, neighbors: Sequence[SparkNeighbor]) -> None:
"""Construct print lines of Spark neighbors in detailed fashion"""
<|body_0|>
def print_spark_neighbors(self, neighbors: Sequence[SparkNeighbor]) -> None:
"""Render ne... | stack_v2_sparse_classes_36k_train_024637 | 9,796 | permissive | [
{
"docstring": "Construct print lines of Spark neighbors in detailed fashion",
"name": "print_spark_neighbors_detailed",
"signature": "def print_spark_neighbors_detailed(self, neighbors: Sequence[SparkNeighbor]) -> None"
},
{
"docstring": "Render neighbors without details",
"name": "print_sp... | 2 | stack_v2_sparse_classes_30k_train_018472 | Implement the Python class `SparkBaseCmd` described below.
Class description:
Implement the SparkBaseCmd class.
Method signatures and docstrings:
- def print_spark_neighbors_detailed(self, neighbors: Sequence[SparkNeighbor]) -> None: Construct print lines of Spark neighbors in detailed fashion
- def print_spark_neigh... | Implement the Python class `SparkBaseCmd` described below.
Class description:
Implement the SparkBaseCmd class.
Method signatures and docstrings:
- def print_spark_neighbors_detailed(self, neighbors: Sequence[SparkNeighbor]) -> None: Construct print lines of Spark neighbors in detailed fashion
- def print_spark_neigh... | 8e4c6e553f0314763c1595dd6097dd578d771f1c | <|skeleton|>
class SparkBaseCmd:
def print_spark_neighbors_detailed(self, neighbors: Sequence[SparkNeighbor]) -> None:
"""Construct print lines of Spark neighbors in detailed fashion"""
<|body_0|>
def print_spark_neighbors(self, neighbors: Sequence[SparkNeighbor]) -> None:
"""Render ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparkBaseCmd:
def print_spark_neighbors_detailed(self, neighbors: Sequence[SparkNeighbor]) -> None:
"""Construct print lines of Spark neighbors in detailed fashion"""
rows = []
for neighbor in neighbors:
v4Addr = (ipnetwork.sprint_addr(neighbor.transportAddressV4.addr),)
... | the_stack_v2_python_sparse | openr/py/openr/cli/commands/spark.py | facebook/openr | train | 936 | |
bbc75db6a54eafb495a2f906cfaa57c8af25028a | [
"if N <= 1:\n return N\nreturn self.fib(N - 1) + self.fib(N - 2)",
"if N <= 1:\n return N\na, b = (0, 1)\nfor i in range(1, N):\n a, b = (b, a + b)\nreturn b"
] | <|body_start_0|>
if N <= 1:
return N
return self.fib(N - 1) + self.fib(N - 2)
<|end_body_0|>
<|body_start_1|>
if N <= 1:
return N
a, b = (0, 1)
for i in range(1, N):
a, b = (b, a + b)
return b
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fib(self, N: int) -> int:
"""20190930 第一次尝试使用 lru_cache, 快得飞起 with lru_cache 执行用时 :40 ms, 在所有 Python3 提交中击败了94.85% 的用户 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了5.54%的用户 without lru_cache 执行用时 :940 ms, 在所有 Python3 提交中击败了25.81% 的用户 内存消耗 :13.9 MB, 在所有 Python3 提交中击败了5.54%的用户"""
... | stack_v2_sparse_classes_36k_train_024638 | 1,364 | no_license | [
{
"docstring": "20190930 第一次尝试使用 lru_cache, 快得飞起 with lru_cache 执行用时 :40 ms, 在所有 Python3 提交中击败了94.85% 的用户 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了5.54%的用户 without lru_cache 执行用时 :940 ms, 在所有 Python3 提交中击败了25.81% 的用户 内存消耗 :13.9 MB, 在所有 Python3 提交中击败了5.54%的用户",
"name": "fib",
"signature": "def fib(self, N: int) ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fib(self, N: int) -> int: 20190930 第一次尝试使用 lru_cache, 快得飞起 with lru_cache 执行用时 :40 ms, 在所有 Python3 提交中击败了94.85% 的用户 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了5.54%的用户 without lru_cach... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fib(self, N: int) -> int: 20190930 第一次尝试使用 lru_cache, 快得飞起 with lru_cache 执行用时 :40 ms, 在所有 Python3 提交中击败了94.85% 的用户 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了5.54%的用户 without lru_cach... | 99a3abf1774933af73a8405f9b59e5e64906bca4 | <|skeleton|>
class Solution:
def fib(self, N: int) -> int:
"""20190930 第一次尝试使用 lru_cache, 快得飞起 with lru_cache 执行用时 :40 ms, 在所有 Python3 提交中击败了94.85% 的用户 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了5.54%的用户 without lru_cache 执行用时 :940 ms, 在所有 Python3 提交中击败了25.81% 的用户 内存消耗 :13.9 MB, 在所有 Python3 提交中击败了5.54%的用户"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def fib(self, N: int) -> int:
"""20190930 第一次尝试使用 lru_cache, 快得飞起 with lru_cache 执行用时 :40 ms, 在所有 Python3 提交中击败了94.85% 的用户 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了5.54%的用户 without lru_cache 执行用时 :940 ms, 在所有 Python3 提交中击败了25.81% 的用户 内存消耗 :13.9 MB, 在所有 Python3 提交中击败了5.54%的用户"""
if N <= 1:
... | the_stack_v2_python_sparse | leetcode/509.fibonacci-number.py | iamkissg/leetcode | train | 0 | |
c8bdab8c57df5640cdde6ecb5432be8819a21b84 | [
"cleaned_data = super(UserDetailsForm, self).clean()\nif not self.files.get('avatar'):\n return cleaned_data\nif any((cleaned_data.get(k) is None for k in ['x1', 'y1', 'x2', 'y2'])):\n raise forms.ValidationError('please Upload your image again and crop')\ntry:\n img = pil_image.open(self.cleaned_data['ava... | <|body_start_0|>
cleaned_data = super(UserDetailsForm, self).clean()
if not self.files.get('avatar'):
return cleaned_data
if any((cleaned_data.get(k) is None for k in ['x1', 'y1', 'x2', 'y2'])):
raise forms.ValidationError('please Upload your image again and crop')
... | UserDetailsForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDetailsForm:
def clean(self):
"""instantiate PIL image; raise ValidationError if field contains no image"""
<|body_0|>
def crop(self, img):
"""crop the image to the user supplied coordinates"""
<|body_1|>
def resize(self, img, dimensions, maintain_ra... | stack_v2_sparse_classes_36k_train_024639 | 10,672 | permissive | [
{
"docstring": "instantiate PIL image; raise ValidationError if field contains no image",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "crop the image to the user supplied coordinates",
"name": "crop",
"signature": "def crop(self, img)"
},
{
"docstring": "res... | 4 | stack_v2_sparse_classes_30k_train_018507 | Implement the Python class `UserDetailsForm` described below.
Class description:
Implement the UserDetailsForm class.
Method signatures and docstrings:
- def clean(self): instantiate PIL image; raise ValidationError if field contains no image
- def crop(self, img): crop the image to the user supplied coordinates
- de... | Implement the Python class `UserDetailsForm` described below.
Class description:
Implement the UserDetailsForm class.
Method signatures and docstrings:
- def clean(self): instantiate PIL image; raise ValidationError if field contains no image
- def crop(self, img): crop the image to the user supplied coordinates
- de... | f567607c0d5d38b7519104c355e3738e01f8c6c9 | <|skeleton|>
class UserDetailsForm:
def clean(self):
"""instantiate PIL image; raise ValidationError if field contains no image"""
<|body_0|>
def crop(self, img):
"""crop the image to the user supplied coordinates"""
<|body_1|>
def resize(self, img, dimensions, maintain_ra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserDetailsForm:
def clean(self):
"""instantiate PIL image; raise ValidationError if field contains no image"""
cleaned_data = super(UserDetailsForm, self).clean()
if not self.files.get('avatar'):
return cleaned_data
if any((cleaned_data.get(k) is None for k in ['x1... | the_stack_v2_python_sparse | let_me_auth/forms.py | oleg-chubin/let_me_play | train | 2 | |
89fe96847ecdbbbff36e2b1b3c71ea3142ca86a1 | [
"num = len(adj)\ndist = [float('inf') for i in range(num)]\nprev = [float('inf') for i in range(num)]\ndist[start] = 0\nq = []\nheapq.heappush(q, (0, start))\nwhile len(q) != 0:\n prov_cost, src = heapq.heappop(q)\n if dist[src] < prov_cost:\n continue\n for dest in range(num):\n cost = adj[s... | <|body_start_0|>
num = len(adj)
dist = [float('inf') for i in range(num)]
prev = [float('inf') for i in range(num)]
dist[start] = 0
q = []
heapq.heappush(q, (0, start))
while len(q) != 0:
prov_cost, src = heapq.heappop(q)
if dist[src] < pro... | Dijkstra | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dijkstra:
def dijkstra(self, adj, start, goal=None):
"""ダイクストラアルゴリズムによる最短経路を求めるメソッド 入力 adj: adj[i][j]の値が頂点iから頂点jまでの距離(頂点iから頂点jに枝がない場合,値はfloat('inf'))となるような2次元リスト(正方行列) start: 始点のID goal: オプション引数.終点のID 出力 goalを引数に持つ場合,startからgoalまでの最短経路を格納したリストを返す 持たない場合は,startから各頂点までの最短距離を格納したリストを返す >>> ... | stack_v2_sparse_classes_36k_train_024640 | 3,901 | no_license | [
{
"docstring": "ダイクストラアルゴリズムによる最短経路を求めるメソッド 入力 adj: adj[i][j]の値が頂点iから頂点jまでの距離(頂点iから頂点jに枝がない場合,値はfloat('inf'))となるような2次元リスト(正方行列) start: 始点のID goal: オプション引数.終点のID 出力 goalを引数に持つ場合,startからgoalまでの最短経路を格納したリストを返す 持たない場合は,startから各頂点までの最短距離を格納したリストを返す >>> d = Dijkstra() >>> d.dijkstra([[float('inf'), 2, 4, float('inf')... | 2 | null | Implement the Python class `Dijkstra` described below.
Class description:
Implement the Dijkstra class.
Method signatures and docstrings:
- def dijkstra(self, adj, start, goal=None): ダイクストラアルゴリズムによる最短経路を求めるメソッド 入力 adj: adj[i][j]の値が頂点iから頂点jまでの距離(頂点iから頂点jに枝がない場合,値はfloat('inf'))となるような2次元リスト(正方行列) start: 始点のID goal: オプショ... | Implement the Python class `Dijkstra` described below.
Class description:
Implement the Dijkstra class.
Method signatures and docstrings:
- def dijkstra(self, adj, start, goal=None): ダイクストラアルゴリズムによる最短経路を求めるメソッド 入力 adj: adj[i][j]の値が頂点iから頂点jまでの距離(頂点iから頂点jに枝がない場合,値はfloat('inf'))となるような2次元リスト(正方行列) start: 始点のID goal: オプショ... | a12d30e0d1eeb58235b6fc51a558f409a2ee3792 | <|skeleton|>
class Dijkstra:
def dijkstra(self, adj, start, goal=None):
"""ダイクストラアルゴリズムによる最短経路を求めるメソッド 入力 adj: adj[i][j]の値が頂点iから頂点jまでの距離(頂点iから頂点jに枝がない場合,値はfloat('inf'))となるような2次元リスト(正方行列) start: 始点のID goal: オプション引数.終点のID 出力 goalを引数に持つ場合,startからgoalまでの最短経路を格納したリストを返す 持たない場合は,startから各頂点までの最短距離を格納したリストを返す >>> ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dijkstra:
def dijkstra(self, adj, start, goal=None):
"""ダイクストラアルゴリズムによる最短経路を求めるメソッド 入力 adj: adj[i][j]の値が頂点iから頂点jまでの距離(頂点iから頂点jに枝がない場合,値はfloat('inf'))となるような2次元リスト(正方行列) start: 始点のID goal: オプション引数.終点のID 出力 goalを引数に持つ場合,startからgoalまでの最短経路を格納したリストを返す 持たない場合は,startから各頂点までの最短距離を格納したリストを返す >>> d = Dijkstra()... | the_stack_v2_python_sparse | utils/graph/dijkstra2.py | masa3141/procon | train | 0 | |
39cb11ec2adb46b3502fb8686a59b1be41018a6f | [
"if sqrt:\n sigmas = [math.sqrt(float(i) * max_sigma / float(steps)) for i in range(0, steps + 1)]\nelse:\n sigmas = [float(i) * max_sigma / float(steps) for i in range(0, steps + 1)]\nstep_vector_diff = [sigmas[i + 1] - sigmas[i] for i in range(0, steps)]\ntotal_gradients = np.zeros_like(x_value)\nfor i in r... | <|body_start_0|>
if sqrt:
sigmas = [math.sqrt(float(i) * max_sigma / float(steps)) for i in range(0, steps + 1)]
else:
sigmas = [float(i) * max_sigma / float(steps) for i in range(0, steps + 1)]
step_vector_diff = [sigmas[i + 1] - sigmas[i] for i in range(0, steps)]
... | BlurIG | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlurIG:
def get_mask(self, image, max_sigma=50, num_steps=100, grad_step=0.01, sqrt=False, preprocess=True):
"""Computes Blur Integrated Gradients for a predicted label. Args: image (ndarray): Original image top_pred_idx: Predicted label for the input image baseline (ndarray): The baseli... | stack_v2_sparse_classes_36k_train_024641 | 2,360 | permissive | [
{
"docstring": "Computes Blur Integrated Gradients for a predicted label. Args: image (ndarray): Original image top_pred_idx: Predicted label for the input image baseline (ndarray): The baseline image to start with for interpolation num_steps: Number of interpolation steps between the baseline and the input use... | 2 | stack_v2_sparse_classes_30k_train_002786 | Implement the Python class `BlurIG` described below.
Class description:
Implement the BlurIG class.
Method signatures and docstrings:
- def get_mask(self, image, max_sigma=50, num_steps=100, grad_step=0.01, sqrt=False, preprocess=True): Computes Blur Integrated Gradients for a predicted label. Args: image (ndarray): ... | Implement the Python class `BlurIG` described below.
Class description:
Implement the BlurIG class.
Method signatures and docstrings:
- def get_mask(self, image, max_sigma=50, num_steps=100, grad_step=0.01, sqrt=False, preprocess=True): Computes Blur Integrated Gradients for a predicted label. Args: image (ndarray): ... | 55f73f4789c3be581f972dd231d2b4245b820d21 | <|skeleton|>
class BlurIG:
def get_mask(self, image, max_sigma=50, num_steps=100, grad_step=0.01, sqrt=False, preprocess=True):
"""Computes Blur Integrated Gradients for a predicted label. Args: image (ndarray): Original image top_pred_idx: Predicted label for the input image baseline (ndarray): The baseli... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlurIG:
def get_mask(self, image, max_sigma=50, num_steps=100, grad_step=0.01, sqrt=False, preprocess=True):
"""Computes Blur Integrated Gradients for a predicted label. Args: image (ndarray): Original image top_pred_idx: Predicted label for the input image baseline (ndarray): The baseline image to st... | the_stack_v2_python_sparse | methods/blur_IG.py | Castrol68/saliency-tensorflow2 | train | 0 | |
8756de84121cd82e447a4a535729defcadbef8ba | [
"self._config = config\nself.result = {}\nself._executor = j.tools.executor.getSSHBased(addr=config.machine_ip, port=22, login=config.machine_login, passwd=config.machine_password)\nself._cuisine = j.tools.cuisine.get(self._executor)\nself._cuisine.core.sudomode = True\nself._get_remote_nodes_script = \"\\n ... | <|body_start_0|>
self._config = config
self.result = {}
self._executor = j.tools.executor.getSSHBased(addr=config.machine_ip, port=22, login=config.machine_login, passwd=config.machine_password)
self._cuisine = j.tools.cuisine.get(self._executor)
self._cuisine.core.sudomode = Tru... | Monitoring service class | MonitoringService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonitoringService:
"""Monitoring service class"""
def __init__(self, config):
"""Initialize new instance with specific configurations @param config: Configuration object, contianing all the required configurations for the monitoring service @type config: obj"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_024642 | 5,386 | permissive | [
{
"docstring": "Initialize new instance with specific configurations @param config: Configuration object, contianing all the required configurations for the monitoring service @type config: obj",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Retreives a list of... | 4 | null | Implement the Python class `MonitoringService` described below.
Class description:
Monitoring service class
Method signatures and docstrings:
- def __init__(self, config): Initialize new instance with specific configurations @param config: Configuration object, contianing all the required configurations for the monit... | Implement the Python class `MonitoringService` described below.
Class description:
Monitoring service class
Method signatures and docstrings:
- def __init__(self, config): Initialize new instance with specific configurations @param config: Configuration object, contianing all the required configurations for the monit... | f80ac9b1ab99b833ee7adb17700dcf4ef35f3734 | <|skeleton|>
class MonitoringService:
"""Monitoring service class"""
def __init__(self, config):
"""Initialize new instance with specific configurations @param config: Configuration object, contianing all the required configurations for the monitoring service @type config: obj"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MonitoringService:
"""Monitoring service class"""
def __init__(self, config):
"""Initialize new instance with specific configurations @param config: Configuration object, contianing all the required configurations for the monitoring service @type config: obj"""
self._config = config
... | the_stack_v2_python_sparse | tools/monitor_js7_services.py | sokovnich/jumpscale_core8 | train | 0 |
6806e0d3dcfae4849b8586447c1c77d7c28763f6 | [
"exp_value = datetime.now()\nobj = DateTime(exp_value)\nself.assertEqual(exp_value, obj.icpw_value)",
"exp_value = datetime.now()\nobj0 = DateTime(exp_value)\nobj1 = DateTime(exp_value)\nself.assertEqual(obj0, obj1)",
"exp_value = datetime.now()\ndifferent_value = exp_value + timedelta(seconds=1)\nobj0 = DateTi... | <|body_start_0|>
exp_value = datetime.now()
obj = DateTime(exp_value)
self.assertEqual(exp_value, obj.icpw_value)
<|end_body_0|>
<|body_start_1|>
exp_value = datetime.now()
obj0 = DateTime(exp_value)
obj1 = DateTime(exp_value)
self.assertEqual(obj0, obj1)
<|end_b... | DateTimeTester | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DateTimeTester:
def test_value(self):
"""Test retrieving the value of a DateTime."""
<|body_0|>
def test_eq(self):
"""Test that DateTime's with the same value compare equal."""
<|body_1|>
def test_ne(self):
"""Test that DateTime's with different ... | stack_v2_sparse_classes_36k_train_024643 | 42,194 | permissive | [
{
"docstring": "Test retrieving the value of a DateTime.",
"name": "test_value",
"signature": "def test_value(self)"
},
{
"docstring": "Test that DateTime's with the same value compare equal.",
"name": "test_eq",
"signature": "def test_eq(self)"
},
{
"docstring": "Test that DateT... | 4 | stack_v2_sparse_classes_30k_train_007875 | Implement the Python class `DateTimeTester` described below.
Class description:
Implement the DateTimeTester class.
Method signatures and docstrings:
- def test_value(self): Test retrieving the value of a DateTime.
- def test_eq(self): Test that DateTime's with the same value compare equal.
- def test_ne(self): Test ... | Implement the Python class `DateTimeTester` described below.
Class description:
Implement the DateTimeTester class.
Method signatures and docstrings:
- def test_value(self): Test retrieving the value of a DateTime.
- def test_eq(self): Test that DateTime's with the same value compare equal.
- def test_ne(self): Test ... | a626f881d55c307bd857d0ff980cc526f2b18de2 | <|skeleton|>
class DateTimeTester:
def test_value(self):
"""Test retrieving the value of a DateTime."""
<|body_0|>
def test_eq(self):
"""Test that DateTime's with the same value compare equal."""
<|body_1|>
def test_ne(self):
"""Test that DateTime's with different ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DateTimeTester:
def test_value(self):
"""Test retrieving the value of a DateTime."""
exp_value = datetime.now()
obj = DateTime(exp_value)
self.assertEqual(exp_value, obj.icpw_value)
def test_eq(self):
"""Test that DateTime's with the same value compare equal."""
... | the_stack_v2_python_sparse | icypaw/test_types.py | sandialabs/IcyPaw | train | 0 | |
d12db512da688a2928fa71a337a3ac5ea6c14b3c | [
"response = self.client.get('/version/')\nself.assertEqual(response.status_code, 200)\nVERSION(version_number='1.01', update_date='2020-1-20', announcement='第一次', download_address='22/21').save()\nresponse = self.client.get('/version/')\nself.assertEqual(response.status_code, 200)",
"data = {'version_number': '1.... | <|body_start_0|>
response = self.client.get('/version/')
self.assertEqual(response.status_code, 200)
VERSION(version_number='1.01', update_date='2020-1-20', announcement='第一次', download_address='22/21').save()
response = self.client.get('/version/')
self.assertEqual(response.stat... | VersionInformationTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VersionInformationTests:
def test_get_200(self):
"""检测返回状态码为200的get请求 1.数据库中无数据 2.数据库中有数据"""
<|body_0|>
def test_post_200(self):
"""检测返回状态码为200的post请求 1.成功插入相应版本"""
<|body_1|>
def test_post_400(self):
"""检测返回状态码为400的post请求 1.版本号已存在 2.参数数量不对 3.参数名... | stack_v2_sparse_classes_36k_train_024644 | 2,293 | no_license | [
{
"docstring": "检测返回状态码为200的get请求 1.数据库中无数据 2.数据库中有数据",
"name": "test_get_200",
"signature": "def test_get_200(self)"
},
{
"docstring": "检测返回状态码为200的post请求 1.成功插入相应版本",
"name": "test_post_200",
"signature": "def test_post_200(self)"
},
{
"docstring": "检测返回状态码为400的post请求 1.版本号已存在 ... | 3 | stack_v2_sparse_classes_30k_train_001060 | Implement the Python class `VersionInformationTests` described below.
Class description:
Implement the VersionInformationTests class.
Method signatures and docstrings:
- def test_get_200(self): 检测返回状态码为200的get请求 1.数据库中无数据 2.数据库中有数据
- def test_post_200(self): 检测返回状态码为200的post请求 1.成功插入相应版本
- def test_post_400(self): 检测... | Implement the Python class `VersionInformationTests` described below.
Class description:
Implement the VersionInformationTests class.
Method signatures and docstrings:
- def test_get_200(self): 检测返回状态码为200的get请求 1.数据库中无数据 2.数据库中有数据
- def test_post_200(self): 检测返回状态码为200的post请求 1.成功插入相应版本
- def test_post_400(self): 检测... | 7dfa07283d4130b931a92c80bf4f499f97a33b62 | <|skeleton|>
class VersionInformationTests:
def test_get_200(self):
"""检测返回状态码为200的get请求 1.数据库中无数据 2.数据库中有数据"""
<|body_0|>
def test_post_200(self):
"""检测返回状态码为200的post请求 1.成功插入相应版本"""
<|body_1|>
def test_post_400(self):
"""检测返回状态码为400的post请求 1.版本号已存在 2.参数数量不对 3.参数名... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VersionInformationTests:
def test_get_200(self):
"""检测返回状态码为200的get请求 1.数据库中无数据 2.数据库中有数据"""
response = self.client.get('/version/')
self.assertEqual(response.status_code, 200)
VERSION(version_number='1.01', update_date='2020-1-20', announcement='第一次', download_address='22/21')... | the_stack_v2_python_sparse | version_information/tests.py | SE2020-TopUnderstanding/BUAA-Campus-Tools-Backend | train | 7 | |
6f2301e3e6bd43e8a82926349a880ca4b23fdc3b | [
"def override_open(open_path, *_other):\n return open_path\nmocker.patch('builtins.open', side_effect=override_open)\npath = '/Users/some_user/some_dir/some_file.file'\noutput = get_requests_kwargs(file_path=path)\nexpected_output = {'files': [('file', ('iocs.json', path, 'application/json'))]}\nassert output ==... | <|body_start_0|>
def override_open(open_path, *_other):
return open_path
mocker.patch('builtins.open', side_effect=override_open)
path = '/Users/some_user/some_dir/some_file.file'
output = get_requests_kwargs(file_path=path)
expected_output = {'files': [('file', ('ioc... | TestGetRequestsKwargs | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGetRequestsKwargs:
def test_with_file(self, mocker):
"""Given: - file to upload Then: - Verify output format."""
<|body_0|>
def test_with_json(self):
"""Given: - simple json Then: - the json ready to send"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_024645 | 41,271 | permissive | [
{
"docstring": "Given: - file to upload Then: - Verify output format.",
"name": "test_with_file",
"signature": "def test_with_file(self, mocker)"
},
{
"docstring": "Given: - simple json Then: - the json ready to send",
"name": "test_with_json",
"signature": "def test_with_json(self)"
}... | 2 | stack_v2_sparse_classes_30k_train_020918 | Implement the Python class `TestGetRequestsKwargs` described below.
Class description:
Implement the TestGetRequestsKwargs class.
Method signatures and docstrings:
- def test_with_file(self, mocker): Given: - file to upload Then: - Verify output format.
- def test_with_json(self): Given: - simple json Then: - the jso... | Implement the Python class `TestGetRequestsKwargs` described below.
Class description:
Implement the TestGetRequestsKwargs class.
Method signatures and docstrings:
- def test_with_file(self, mocker): Given: - file to upload Then: - Verify output format.
- def test_with_json(self): Given: - simple json Then: - the jso... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestGetRequestsKwargs:
def test_with_file(self, mocker):
"""Given: - file to upload Then: - Verify output format."""
<|body_0|>
def test_with_json(self):
"""Given: - simple json Then: - the json ready to send"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestGetRequestsKwargs:
def test_with_file(self, mocker):
"""Given: - file to upload Then: - Verify output format."""
def override_open(open_path, *_other):
return open_path
mocker.patch('builtins.open', side_effect=override_open)
path = '/Users/some_user/some_dir/so... | the_stack_v2_python_sparse | Packs/CortexXDR/Integrations/XDR_iocs/XDR_iocs_test.py | demisto/content | train | 1,023 | |
c81e772c94b36600d0f712b93667c044826d5abf | [
"logging.info('Initializing dwu fp16 optimizer')\nself.since_last_invalid = 0\nself.loss_scale = loss_scale\nself.dls_downscale = dls_downscale\nself.dls_upscale = dls_upscale\nself.dls_upscale_interval = dls_upscale_interval\nself.world_size = utils.get_world_size()\nself.fp16_model = fp16_model",
"scaling_facto... | <|body_start_0|>
logging.info('Initializing dwu fp16 optimizer')
self.since_last_invalid = 0
self.loss_scale = loss_scale
self.dls_downscale = dls_downscale
self.dls_upscale = dls_upscale
self.dls_upscale_interval = dls_upscale_interval
self.world_size = utils.get... | Distributed weight update mixed precision optimizer with dynamic loss scaling and backoff. https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html#scalefactor | DwuFp16Optimizer | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DwuFp16Optimizer:
"""Distributed weight update mixed precision optimizer with dynamic loss scaling and backoff. https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html#scalefactor"""
def __init__(self, fp16_model, loss_scale=1024, dls_downscale=2, dls_upscale=2, dls_upsc... | stack_v2_sparse_classes_36k_train_024646 | 12,553 | permissive | [
{
"docstring": "Constructor for the DwuFp16Optimizer. :param fp16_model: model (previously casted to half) :param loss_scale: initial loss scale :param dls_downscale: loss downscale factor, loss scale is divided by this factor when NaN/INF occurs in the gradients :param dls_upscale: loss upscale factor, loss sc... | 2 | null | Implement the Python class `DwuFp16Optimizer` described below.
Class description:
Distributed weight update mixed precision optimizer with dynamic loss scaling and backoff. https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html#scalefactor
Method signatures and docstrings:
- def __init__(self, f... | Implement the Python class `DwuFp16Optimizer` described below.
Class description:
Distributed weight update mixed precision optimizer with dynamic loss scaling and backoff. https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html#scalefactor
Method signatures and docstrings:
- def __init__(self, f... | e017c9359f66e2d814c6990d1ffa56654a73f5b0 | <|skeleton|>
class DwuFp16Optimizer:
"""Distributed weight update mixed precision optimizer with dynamic loss scaling and backoff. https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html#scalefactor"""
def __init__(self, fp16_model, loss_scale=1024, dls_downscale=2, dls_upscale=2, dls_upsc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DwuFp16Optimizer:
"""Distributed weight update mixed precision optimizer with dynamic loss scaling and backoff. https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html#scalefactor"""
def __init__(self, fp16_model, loss_scale=1024, dls_downscale=2, dls_upscale=2, dls_upscale_interval=... | the_stack_v2_python_sparse | Inspur/benchmarks/gnmt/implementations/implementation_closed/seq2seq/train/fp_optimizers.py | piyushghai/training_results_v0.7 | train | 0 |
b0417402595575e935d41f33c6092bb380993fb5 | [
"super().__init__()\ninitialize(self, init_type)\nencoder = SpeedySpeechEncoder(vocab_size, tone_size, encoder_hidden_size, encoder_kernel_size, encoder_dilations, spk_num)\nduration_predictor = DurationPredictor(duration_predictor_hidden_size)\ndecoder = SpeedySpeechDecoder(decoder_hidden_size, decoder_output_size... | <|body_start_0|>
super().__init__()
initialize(self, init_type)
encoder = SpeedySpeechEncoder(vocab_size, tone_size, encoder_hidden_size, encoder_kernel_size, encoder_dilations, spk_num)
duration_predictor = DurationPredictor(duration_predictor_hidden_size)
decoder = SpeedySpeech... | SpeedySpeech | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpeedySpeech:
def __init__(self, vocab_size, encoder_hidden_size: int=128, encoder_kernel_size: int=3, encoder_dilations: List[int]=[1, 3, 9, 27, 1, 3, 9, 27, 1, 1], duration_predictor_hidden_size: int=128, decoder_hidden_size: int=128, decoder_output_size: int=80, decoder_kernel_size: int=3, de... | stack_v2_sparse_classes_36k_train_024647 | 15,439 | permissive | [
{
"docstring": "Initialize SpeedySpeech module. Args: vocab_size (int): Dimension of the inputs. encoder_hidden_size (int): Number of encoder hidden units. encoder_kernel_size (int): Kernel size of encoder. encoder_dilations (List[int]): Dilations of encoder. duration_predictor_hidden_size (int): Number of dura... | 3 | null | Implement the Python class `SpeedySpeech` described below.
Class description:
Implement the SpeedySpeech class.
Method signatures and docstrings:
- def __init__(self, vocab_size, encoder_hidden_size: int=128, encoder_kernel_size: int=3, encoder_dilations: List[int]=[1, 3, 9, 27, 1, 3, 9, 27, 1, 1], duration_predictor... | Implement the Python class `SpeedySpeech` described below.
Class description:
Implement the SpeedySpeech class.
Method signatures and docstrings:
- def __init__(self, vocab_size, encoder_hidden_size: int=128, encoder_kernel_size: int=3, encoder_dilations: List[int]=[1, 3, 9, 27, 1, 3, 9, 27, 1, 1], duration_predictor... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class SpeedySpeech:
def __init__(self, vocab_size, encoder_hidden_size: int=128, encoder_kernel_size: int=3, encoder_dilations: List[int]=[1, 3, 9, 27, 1, 3, 9, 27, 1, 1], duration_predictor_hidden_size: int=128, decoder_hidden_size: int=128, decoder_output_size: int=80, decoder_kernel_size: int=3, de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpeedySpeech:
def __init__(self, vocab_size, encoder_hidden_size: int=128, encoder_kernel_size: int=3, encoder_dilations: List[int]=[1, 3, 9, 27, 1, 3, 9, 27, 1, 1], duration_predictor_hidden_size: int=128, decoder_hidden_size: int=128, decoder_output_size: int=80, decoder_kernel_size: int=3, decoder_dilation... | the_stack_v2_python_sparse | paddlespeech/t2s/models/speedyspeech/speedyspeech.py | anniyanvr/DeepSpeech-1 | train | 0 | |
587d070a75f5f7c30eb435099c134272250066ab | [
"super().__init__(input_name=input_name, output_names=[output_name])\nself.min_value = min_value\nself.max_value = max_value",
"with tf.name_scope('Clip'):\n input = input[self.input_name]\n result = tf.clip_by_value(input, self.min_value, self.max_value)\n return ([result], self.output_names)"
] | <|body_start_0|>
super().__init__(input_name=input_name, output_names=[output_name])
self.min_value = min_value
self.max_value = max_value
<|end_body_0|>
<|body_start_1|>
with tf.name_scope('Clip'):
input = input[self.input_name]
result = tf.clip_by_value(input, ... | The ClipByValue clips the input values to the given range. :Attributes: min_value: (Integer) The min_value of the dataset. max_value: (Integer) The max_value of the dataset. | ClipByValue | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClipByValue:
"""The ClipByValue clips the input values to the given range. :Attributes: min_value: (Integer) The min_value of the dataset. max_value: (Integer) The max_value of the dataset."""
def __init__(self, min_value=0.0, max_value=1.0, input_name='image', output_name='image'):
... | stack_v2_sparse_classes_36k_train_024648 | 1,509 | permissive | [
{
"docstring": "Constructor, initialize member variables. :param max_value : The allowed min_value. :param max_value : The allowed max_value. :param input_name: (String) The name of the input to apply this operation. \"image\" by default. :param output_name: (String) The name of the output where this operation ... | 2 | stack_v2_sparse_classes_30k_train_006151 | Implement the Python class `ClipByValue` described below.
Class description:
The ClipByValue clips the input values to the given range. :Attributes: min_value: (Integer) The min_value of the dataset. max_value: (Integer) The max_value of the dataset.
Method signatures and docstrings:
- def __init__(self, min_value=0.... | Implement the Python class `ClipByValue` described below.
Class description:
The ClipByValue clips the input values to the given range. :Attributes: min_value: (Integer) The min_value of the dataset. max_value: (Integer) The max_value of the dataset.
Method signatures and docstrings:
- def __init__(self, min_value=0.... | 6907ae5781765f56a8492bfba594bfb3b9987f29 | <|skeleton|>
class ClipByValue:
"""The ClipByValue clips the input values to the given range. :Attributes: min_value: (Integer) The min_value of the dataset. max_value: (Integer) The max_value of the dataset."""
def __init__(self, min_value=0.0, max_value=1.0, input_name='image', output_name='image'):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClipByValue:
"""The ClipByValue clips the input values to the given range. :Attributes: min_value: (Integer) The min_value of the dataset. max_value: (Integer) The max_value of the dataset."""
def __init__(self, min_value=0.0, max_value=1.0, input_name='image', output_name='image'):
"""Constructo... | the_stack_v2_python_sparse | Preprocessing_Component/Preprocessing/ClipByValue.py | BonifazStuhr/OFM | train | 0 |
c75f973a3205155925e4538aa1611d10b3548397 | [
"self.client = Client()\nself.form_url = reverse('index')\nself.form_url_II = reverse('create')",
"response = self.client.get(self.form_url)\nself.assertEqual(response.status_code, 200)\nself.assertTemplateUsed(response, 'index.html')"
] | <|body_start_0|>
self.client = Client()
self.form_url = reverse('index')
self.form_url_II = reverse('create')
<|end_body_0|>
<|body_start_1|>
response = self.client.get(self.form_url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'index.ht... | Class with unittests for views. | TestViews | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestViews:
"""Class with unittests for views."""
def setUp(self):
"""Set up for tests."""
<|body_0|>
def test_GET_index(self):
"""GET method for index, tests."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.client = Client()
self.fo... | stack_v2_sparse_classes_36k_train_024649 | 709 | no_license | [
{
"docstring": "Set up for tests.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "GET method for index, tests.",
"name": "test_GET_index",
"signature": "def test_GET_index(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010129 | Implement the Python class `TestViews` described below.
Class description:
Class with unittests for views.
Method signatures and docstrings:
- def setUp(self): Set up for tests.
- def test_GET_index(self): GET method for index, tests. | Implement the Python class `TestViews` described below.
Class description:
Class with unittests for views.
Method signatures and docstrings:
- def setUp(self): Set up for tests.
- def test_GET_index(self): GET method for index, tests.
<|skeleton|>
class TestViews:
"""Class with unittests for views."""
def s... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class TestViews:
"""Class with unittests for views."""
def setUp(self):
"""Set up for tests."""
<|body_0|>
def test_GET_index(self):
"""GET method for index, tests."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestViews:
"""Class with unittests for views."""
def setUp(self):
"""Set up for tests."""
self.client = Client()
self.form_url = reverse('index')
self.form_url_II = reverse('create')
def test_GET_index(self):
"""GET method for index, tests."""
response... | the_stack_v2_python_sparse | Django/Django_three_projects/urlshortner/shortner/test_views.py | JakubKazimierski/PythonPortfolio | train | 9 |
dd84e62865f80f66725d134e0ee1b28e43abdd51 | [
"self.b = np.array(b)\nself.a = np.array(a)\nself.b /= self.a[0]\nself.a /= self.a[0]\nself.zi = np.zeros(max(len(a), len(b)) - 1)",
"if isinstance(samples, (float, int)):\n samples = np.array([samples])\nfilt_output, self.zi = lfilter(self.b, self.a, samples, zi=self.zi)\nreturn filt_output"
] | <|body_start_0|>
self.b = np.array(b)
self.a = np.array(a)
self.b /= self.a[0]
self.a /= self.a[0]
self.zi = np.zeros(max(len(a), len(b)) - 1)
<|end_body_0|>
<|body_start_1|>
if isinstance(samples, (float, int)):
samples = np.array([samples])
filt_out... | Filter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Filter:
def __init__(self, b=[], a=[1.0]):
"""Constructor for Filter Parameters ---------- b : array_like The numerator coefficient vector in a 1-D sequence. a : array_like The denominator coefficient vector in a 1-D sequence. If ``a[0]`` is not 1, then both `a` and `b` are normalized by... | stack_v2_sparse_classes_36k_train_024650 | 1,459 | permissive | [
{
"docstring": "Constructor for Filter Parameters ---------- b : array_like The numerator coefficient vector in a 1-D sequence. a : array_like The denominator coefficient vector in a 1-D sequence. If ``a[0]`` is not 1, then both `a` and `b` are normalized by ``a[0]``. Returns ------- Filter instance",
"name... | 2 | stack_v2_sparse_classes_30k_train_000359 | Implement the Python class `Filter` described below.
Class description:
Implement the Filter class.
Method signatures and docstrings:
- def __init__(self, b=[], a=[1.0]): Constructor for Filter Parameters ---------- b : array_like The numerator coefficient vector in a 1-D sequence. a : array_like The denominator coef... | Implement the Python class `Filter` described below.
Class description:
Implement the Filter class.
Method signatures and docstrings:
- def __init__(self, b=[], a=[1.0]): Constructor for Filter Parameters ---------- b : array_like The numerator coefficient vector in a 1-D sequence. a : array_like The denominator coef... | a0e296aa663b49e767c9ebb274defb54b301eb12 | <|skeleton|>
class Filter:
def __init__(self, b=[], a=[1.0]):
"""Constructor for Filter Parameters ---------- b : array_like The numerator coefficient vector in a 1-D sequence. a : array_like The denominator coefficient vector in a 1-D sequence. If ``a[0]`` is not 1, then both `a` and `b` are normalized by... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Filter:
def __init__(self, b=[], a=[1.0]):
"""Constructor for Filter Parameters ---------- b : array_like The numerator coefficient vector in a 1-D sequence. a : array_like The denominator coefficient vector in a 1-D sequence. If ``a[0]`` is not 1, then both `a` and `b` are normalized by ``a[0]``. Ret... | the_stack_v2_python_sparse | riglib/filter.py | carmenalab/brain-python-interface | train | 9 | |
35ffb7ba55af55c8357602ac0c8f9ebc7a3aa44e | [
"params = {'channel_id': channel_id, 'onBehalfOfContentOwner': on_behalf_of_content_owner, **kwargs}\nmedia_upload = MediaUpload(client=self._client, resource='watermarks/set', media=media, params=params, body=body.to_dict_ignore_none())\nreturn media_upload",
"params = {'channelId': channel_id, 'onBehalfOfConten... | <|body_start_0|>
params = {'channel_id': channel_id, 'onBehalfOfContentOwner': on_behalf_of_content_owner, **kwargs}
media_upload = MediaUpload(client=self._client, resource='watermarks/set', media=media, params=params, body=body.to_dict_ignore_none())
return media_upload
<|end_body_0|>
<|body_... | WatermarksResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WatermarksResource:
def set(self, channel_id: str, body: Union[dict, Watermark], media: Media, on_behalf_of_content_owner: Optional[str]=None, **kwargs: Optional[dict]) -> MediaUpload:
"""Args: channel_id: Specifies the YouTube channel ID for which the watermark is being provided. body: ... | stack_v2_sparse_classes_36k_train_024651 | 3,937 | permissive | [
{
"docstring": "Args: channel_id: Specifies the YouTube channel ID for which the watermark is being provided. body: Provide watermark data in the request body. You can give dataclass or just a dict with data. media: Media for watermark image. on_behalf_of_content_owner: The onBehalfOfContentOwner parameter indi... | 2 | null | Implement the Python class `WatermarksResource` described below.
Class description:
Implement the WatermarksResource class.
Method signatures and docstrings:
- def set(self, channel_id: str, body: Union[dict, Watermark], media: Media, on_behalf_of_content_owner: Optional[str]=None, **kwargs: Optional[dict]) -> MediaU... | Implement the Python class `WatermarksResource` described below.
Class description:
Implement the WatermarksResource class.
Method signatures and docstrings:
- def set(self, channel_id: str, body: Union[dict, Watermark], media: Media, on_behalf_of_content_owner: Optional[str]=None, **kwargs: Optional[dict]) -> MediaU... | 1ed2f67a55b8df75c5fab9aacd7d9ff4d460812a | <|skeleton|>
class WatermarksResource:
def set(self, channel_id: str, body: Union[dict, Watermark], media: Media, on_behalf_of_content_owner: Optional[str]=None, **kwargs: Optional[dict]) -> MediaUpload:
"""Args: channel_id: Specifies the YouTube channel ID for which the watermark is being provided. body: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WatermarksResource:
def set(self, channel_id: str, body: Union[dict, Watermark], media: Media, on_behalf_of_content_owner: Optional[str]=None, **kwargs: Optional[dict]) -> MediaUpload:
"""Args: channel_id: Specifies the YouTube channel ID for which the watermark is being provided. body: Provide waterm... | the_stack_v2_python_sparse | pyyoutube/resources/watermarks.py | sns-sdks/python-youtube | train | 249 | |
38ab5443af84ed1a5195ebc64e2445448c1f7464 | [
"if central_node_fqdn is None:\n self.fqdn = getfqdn_env()\nelse:\n self.fqdn = central_node_fqdn\nself.disable_tls = disable_tls\nself.cert_chain = cert_chain\nself.agg_certificate = agg_certificate\nself.agg_private_key = agg_private_key",
"self.col_data_paths = col_data_paths\nwith open('./data.yaml', 'w... | <|body_start_0|>
if central_node_fqdn is None:
self.fqdn = getfqdn_env()
else:
self.fqdn = central_node_fqdn
self.disable_tls = disable_tls
self.cert_chain = cert_chain
self.agg_certificate = agg_certificate
self.agg_private_key = agg_private_key
<... | Federation class. Federation entity exists to keep information about collaborator related settings, their local data and network setting to enable communication in federation. | Federation | [
"LicenseRef-scancode-protobuf",
"MPL-2.0",
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Federation:
"""Federation class. Federation entity exists to keep information about collaborator related settings, their local data and network setting to enable communication in federation."""
def __init__(self, central_node_fqdn=None, disable_tls=False, cert_chain=None, agg_certificate=Non... | stack_v2_sparse_classes_36k_train_024652 | 1,724 | permissive | [
{
"docstring": "Initialize federation. Federation API class should be initialized with the aggregator node FQDN and encryption settings. One may disable mTLS in trusted environments or provide paths to a certificate chain to CA, aggregator certificate and pricate key to enable mTLS.",
"name": "__init__",
... | 2 | null | Implement the Python class `Federation` described below.
Class description:
Federation class. Federation entity exists to keep information about collaborator related settings, their local data and network setting to enable communication in federation.
Method signatures and docstrings:
- def __init__(self, central_nod... | Implement the Python class `Federation` described below.
Class description:
Federation class. Federation entity exists to keep information about collaborator related settings, their local data and network setting to enable communication in federation.
Method signatures and docstrings:
- def __init__(self, central_nod... | bd73b749a9ea1b92dbcdd07e639752101d769fc0 | <|skeleton|>
class Federation:
"""Federation class. Federation entity exists to keep information about collaborator related settings, their local data and network setting to enable communication in federation."""
def __init__(self, central_node_fqdn=None, disable_tls=False, cert_chain=None, agg_certificate=Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Federation:
"""Federation class. Federation entity exists to keep information about collaborator related settings, their local data and network setting to enable communication in federation."""
def __init__(self, central_node_fqdn=None, disable_tls=False, cert_chain=None, agg_certificate=None, agg_privat... | the_stack_v2_python_sparse | openfl/interface/interactive_api/federation.py | PDuckworth/openfl | train | 0 |
770c3e0c20234fad7c9c757e094da8e742e41e2a | [
"super().__init__(nb_channels, name, rate, system_rate)\nif isinstance(channel_names, str):\n channel_names = [channel_names]\nif channel_names:\n if nb_channels != len(channel_names):\n raise ValueError('The number of channels is not equal to the number of channel names.')\nelse:\n channel_names = ... | <|body_start_0|>
super().__init__(nb_channels, name, rate, system_rate)
if isinstance(channel_names, str):
channel_names = [channel_names]
if channel_names:
if nb_channels != len(channel_names):
raise ValueError('The number of channels is not equal to the ... | This class is used to store the available devices. | Device | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Device:
"""This class is used to store the available devices."""
def __init__(self, device_type: DeviceType=DeviceType.Emg, nb_channels: int=1, name: str=None, rate: float=2000, system_rate: float=100, channel_names: Union[list, str]=None):
"""Initialize the device class. A device is... | stack_v2_sparse_classes_36k_train_024653 | 14,244 | permissive | [
{
"docstring": "Initialize the device class. A device is an electronic device that can be used to measure a parameter (e.g. EMG, treadmill, etc.). Parameters ---------- device_type: DeviceType Type of the device. nb_channels: int Number of channels of the device. name: str Name of the device. rate: float Rate o... | 4 | stack_v2_sparse_classes_30k_train_002140 | Implement the Python class `Device` described below.
Class description:
This class is used to store the available devices.
Method signatures and docstrings:
- def __init__(self, device_type: DeviceType=DeviceType.Emg, nb_channels: int=1, name: str=None, rate: float=2000, system_rate: float=100, channel_names: Union[l... | Implement the Python class `Device` described below.
Class description:
This class is used to store the available devices.
Method signatures and docstrings:
- def __init__(self, device_type: DeviceType=DeviceType.Emg, nb_channels: int=1, name: str=None, rate: float=2000, system_rate: float=100, channel_names: Union[l... | 1f09785605ed5e4eaa78bd203ec118c3b2794732 | <|skeleton|>
class Device:
"""This class is used to store the available devices."""
def __init__(self, device_type: DeviceType=DeviceType.Emg, nb_channels: int=1, name: str=None, rate: float=2000, system_rate: float=100, channel_names: Union[list, str]=None):
"""Initialize the device class. A device is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Device:
"""This class is used to store the available devices."""
def __init__(self, device_type: DeviceType=DeviceType.Emg, nb_channels: int=1, name: str=None, rate: float=2000, system_rate: float=100, channel_names: Union[list, str]=None):
"""Initialize the device class. A device is an electroni... | the_stack_v2_python_sparse | biosiglive/interfaces/param.py | aceglia/biosiglive | train | 6 |
6944c738e108175e6c7a35cda0a120ffcf5e1c54 | [
"self.attr_flags = attr_flags\nself.dest_value = dest_value\nself.ldap_name = ldap_name\nself.same_value = same_value\nself.source_value = source_value\nself.status = status",
"if dictionary is None:\n return None\nattr_flags = dictionary.get('attrFlags')\ndest_value = cohesity_management_sdk.models.compare_ad... | <|body_start_0|>
self.attr_flags = attr_flags
self.dest_value = dest_value
self.ldap_name = ldap_name
self.same_value = same_value
self.source_value = source_value
self.status = status
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None... | Implementation of the 'CompareADObjectsResult_ADAttribute' model. TODO: type description here. Attributes: attr_flags (int): Object result flags of type ADAttributeFlags. dest_value (CompareADObjectsResult_ADAttributeValue): Destination attribute value if dest value exists (!ADAttributeFlags.kNotFound) and is different... | CompareADObjectsResult_ADAttribute | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompareADObjectsResult_ADAttribute:
"""Implementation of the 'CompareADObjectsResult_ADAttribute' model. TODO: type description here. Attributes: attr_flags (int): Object result flags of type ADAttributeFlags. dest_value (CompareADObjectsResult_ADAttributeValue): Destination attribute value if de... | stack_v2_sparse_classes_36k_train_024654 | 3,784 | permissive | [
{
"docstring": "Constructor for the CompareADObjectsResult_ADAttribute class",
"name": "__init__",
"signature": "def __init__(self, attr_flags=None, dest_value=None, ldap_name=None, same_value=None, source_value=None, status=None)"
},
{
"docstring": "Creates an instance of this model from a dict... | 2 | stack_v2_sparse_classes_30k_train_003488 | Implement the Python class `CompareADObjectsResult_ADAttribute` described below.
Class description:
Implementation of the 'CompareADObjectsResult_ADAttribute' model. TODO: type description here. Attributes: attr_flags (int): Object result flags of type ADAttributeFlags. dest_value (CompareADObjectsResult_ADAttributeVa... | Implement the Python class `CompareADObjectsResult_ADAttribute` described below.
Class description:
Implementation of the 'CompareADObjectsResult_ADAttribute' model. TODO: type description here. Attributes: attr_flags (int): Object result flags of type ADAttributeFlags. dest_value (CompareADObjectsResult_ADAttributeVa... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CompareADObjectsResult_ADAttribute:
"""Implementation of the 'CompareADObjectsResult_ADAttribute' model. TODO: type description here. Attributes: attr_flags (int): Object result flags of type ADAttributeFlags. dest_value (CompareADObjectsResult_ADAttributeValue): Destination attribute value if de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompareADObjectsResult_ADAttribute:
"""Implementation of the 'CompareADObjectsResult_ADAttribute' model. TODO: type description here. Attributes: attr_flags (int): Object result flags of type ADAttributeFlags. dest_value (CompareADObjectsResult_ADAttributeValue): Destination attribute value if dest value exis... | the_stack_v2_python_sparse | cohesity_management_sdk/models/compare_ad_objects_result_ad_attribute.py | cohesity/management-sdk-python | train | 24 |
9e24943be8af28db2bbb5f7466475a61ca292dce | [
"try:\n playbook_file = open(resource, 'r')\nexcept (IOError, OSError) as e:\n logger.error('Could not load workflow from {0}. Reason: {1}'.format(resource, format_exception_message(e)))\n return None\nelse:\n with playbook_file:\n workflow_loaded = playbook_file.read()\n try:\n ... | <|body_start_0|>
try:
playbook_file = open(resource, 'r')
except (IOError, OSError) as e:
logger.error('Could not load workflow from {0}. Reason: {1}'.format(resource, format_exception_message(e)))
return None
else:
with playbook_file:
... | JsonPlaybookLoader | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonPlaybookLoader:
def load_workflow(resource, workflow_name):
"""Loads a workflow from a file. Args: resource (str): Path to the workflow. workflow_name (str): Name of the workflow to load. Returns: True on success, False otherwise."""
<|body_0|>
def load_playbook(resource... | stack_v2_sparse_classes_36k_train_024655 | 4,183 | permissive | [
{
"docstring": "Loads a workflow from a file. Args: resource (str): Path to the workflow. workflow_name (str): Name of the workflow to load. Returns: True on success, False otherwise.",
"name": "load_workflow",
"signature": "def load_workflow(resource, workflow_name)"
},
{
"docstring": "Loads a ... | 3 | stack_v2_sparse_classes_30k_train_017746 | Implement the Python class `JsonPlaybookLoader` described below.
Class description:
Implement the JsonPlaybookLoader class.
Method signatures and docstrings:
- def load_workflow(resource, workflow_name): Loads a workflow from a file. Args: resource (str): Path to the workflow. workflow_name (str): Name of the workflo... | Implement the Python class `JsonPlaybookLoader` described below.
Class description:
Implement the JsonPlaybookLoader class.
Method signatures and docstrings:
- def load_workflow(resource, workflow_name): Loads a workflow from a file. Args: resource (str): Path to the workflow. workflow_name (str): Name of the workflo... | 18cd8b6d10241955bea5422947af9cf67f73aead | <|skeleton|>
class JsonPlaybookLoader:
def load_workflow(resource, workflow_name):
"""Loads a workflow from a file. Args: resource (str): Path to the workflow. workflow_name (str): Name of the workflow to load. Returns: True on success, False otherwise."""
<|body_0|>
def load_playbook(resource... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JsonPlaybookLoader:
def load_workflow(resource, workflow_name):
"""Loads a workflow from a file. Args: resource (str): Path to the workflow. workflow_name (str): Name of the workflow to load. Returns: True on success, False otherwise."""
try:
playbook_file = open(resource, 'r')
... | the_stack_v2_python_sparse | core/jsonplaybookloader.py | JustinTervala/WALKOFF | train | 0 | |
b6abac0b1daae06eb47287e2b31101d9783c7605 | [
"instance = self.instance\nif instance.status == common_constant.TASK_STATUS.ONGOING:\n raise serializers.ValidationError(generate_error('start delta could not be updated for ongoing task'))\ndelta_time = None\nif instance.parent_task and instance.parent_task.status == common_constant.TASK_STATUS.COMPLETE:\n ... | <|body_start_0|>
instance = self.instance
if instance.status == common_constant.TASK_STATUS.ONGOING:
raise serializers.ValidationError(generate_error('start delta could not be updated for ongoing task'))
delta_time = None
if instance.parent_task and instance.parent_task.statu... | TaskUpdateSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskUpdateSerializer:
def validate_start_delta(self, value):
"""validates that start delta could not be updated for ongoing task and if parent task is completed."""
<|body_0|>
def validate_assignee(self, assignee):
"""override to verify that user can not update assig... | stack_v2_sparse_classes_36k_train_024656 | 18,075 | no_license | [
{
"docstring": "validates that start delta could not be updated for ongoing task and if parent task is completed.",
"name": "validate_start_delta",
"signature": "def validate_start_delta(self, value)"
},
{
"docstring": "override to verify that user can not update assignee if user is only assigne... | 3 | stack_v2_sparse_classes_30k_train_005333 | Implement the Python class `TaskUpdateSerializer` described below.
Class description:
Implement the TaskUpdateSerializer class.
Method signatures and docstrings:
- def validate_start_delta(self, value): validates that start delta could not be updated for ongoing task and if parent task is completed.
- def validate_as... | Implement the Python class `TaskUpdateSerializer` described below.
Class description:
Implement the TaskUpdateSerializer class.
Method signatures and docstrings:
- def validate_start_delta(self, value): validates that start delta could not be updated for ongoing task and if parent task is completed.
- def validate_as... | bedb1d7cf25188619d4afc748d17b7ffe20b6992 | <|skeleton|>
class TaskUpdateSerializer:
def validate_start_delta(self, value):
"""validates that start delta could not be updated for ongoing task and if parent task is completed."""
<|body_0|>
def validate_assignee(self, assignee):
"""override to verify that user can not update assig... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskUpdateSerializer:
def validate_start_delta(self, value):
"""validates that start delta could not be updated for ongoing task and if parent task is completed."""
instance = self.instance
if instance.status == common_constant.TASK_STATUS.ONGOING:
raise serializers.Validat... | the_stack_v2_python_sparse | apps/workflow/serializers.py | arao/workflow-api | train | 0 | |
c451311e6f6218386062a9bc709980723e3158df | [
"dec = 0\ni = 0\nif not isinstance(bin_no, int):\n try:\n bin_no = int(bin_no)\n except:\n raise TypeError\nwhile bin_no > 0:\n dec += bin_no % 10 * 2 ** i\n bin_no //= 10\n i += 1\nreturn dec",
"if dec_no > 0:\n return str(bin(dec_no)[2:].zfill(bit_rep))\nreturn '-' + str(bin(dec_... | <|body_start_0|>
dec = 0
i = 0
if not isinstance(bin_no, int):
try:
bin_no = int(bin_no)
except:
raise TypeError
while bin_no > 0:
dec += bin_no % 10 * 2 ** i
bin_no //= 10
i += 1
return d... | Converter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Converter:
def binToDec(cls, bin_no):
"""@param bin_no: an integer or str representation of a binary number @return: an integer value of the binary number passed"""
<|body_0|>
def decToBin(cls, dec_no, bit_rep):
"""@param dec_no: an integer value @param bit_rep: bit ... | stack_v2_sparse_classes_36k_train_024657 | 3,022 | no_license | [
{
"docstring": "@param bin_no: an integer or str representation of a binary number @return: an integer value of the binary number passed",
"name": "binToDec",
"signature": "def binToDec(cls, bin_no)"
},
{
"docstring": "@param dec_no: an integer value @param bit_rep: bit representation amount @re... | 4 | null | Implement the Python class `Converter` described below.
Class description:
Implement the Converter class.
Method signatures and docstrings:
- def binToDec(cls, bin_no): @param bin_no: an integer or str representation of a binary number @return: an integer value of the binary number passed
- def decToBin(cls, dec_no, ... | Implement the Python class `Converter` described below.
Class description:
Implement the Converter class.
Method signatures and docstrings:
- def binToDec(cls, bin_no): @param bin_no: an integer or str representation of a binary number @return: an integer value of the binary number passed
- def decToBin(cls, dec_no, ... | ade665584f509382684a5e319d2560c5745682a7 | <|skeleton|>
class Converter:
def binToDec(cls, bin_no):
"""@param bin_no: an integer or str representation of a binary number @return: an integer value of the binary number passed"""
<|body_0|>
def decToBin(cls, dec_no, bit_rep):
"""@param dec_no: an integer value @param bit_rep: bit ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Converter:
def binToDec(cls, bin_no):
"""@param bin_no: an integer or str representation of a binary number @return: an integer value of the binary number passed"""
dec = 0
i = 0
if not isinstance(bin_no, int):
try:
bin_no = int(bin_no)
e... | the_stack_v2_python_sparse | learning_python/problems/numbers_problems/currency_converter.py | vandanagarg/practice_python | train | 1 | |
1174ca5ef6d34fe241daf5d1c8a5ae07858c1242 | [
"m, n = (len(matrix), len(matrix[0]))\nq = [(matrix[0][0], 0, 0)]\nans = None\nfor _ in range(k):\n ans, i, j = heapq.heappop(q)\n if j + 1 < n:\n heapq.heappush(q, (matrix[i][j + 1], i, j + 1))\n if j == 0 and i + 1 < m:\n heapq.heappush(q, (matrix[i + 1][j], i + 1, j))\nreturn ans",
"lo, ... | <|body_start_0|>
m, n = (len(matrix), len(matrix[0]))
q = [(matrix[0][0], 0, 0)]
ans = None
for _ in range(k):
ans, i, j = heapq.heappop(q)
if j + 1 < n:
heapq.heappush(q, (matrix[i][j + 1], i, j + 1))
if j == 0 and i + 1 < m:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallestHeap(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_0|>
def kthSmallest(self, matrix, k):
"""Heap of list :type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_1|>
def countLower(... | stack_v2_sparse_classes_36k_train_024658 | 2,192 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type k: int :rtype: int",
"name": "kthSmallestHeap",
"signature": "def kthSmallestHeap(self, matrix, k)"
},
{
"docstring": "Heap of list :type matrix: List[List[int]] :type k: int :rtype: int",
"name": "kthSmallest",
"signature": "def kthSma... | 3 | stack_v2_sparse_classes_30k_train_007848 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallestHeap(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: int
- def kthSmallest(self, matrix, k): Heap of list :type matrix: List[List[int]] :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallestHeap(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: int
- def kthSmallest(self, matrix, k): Heap of list :type matrix: List[List[int]] :type ... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def kthSmallestHeap(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_0|>
def kthSmallest(self, matrix, k):
"""Heap of list :type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_1|>
def countLower(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kthSmallestHeap(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
m, n = (len(matrix), len(matrix[0]))
q = [(matrix[0][0], 0, 0)]
ans = None
for _ in range(k):
ans, i, j = heapq.heappop(q)
if j + 1 < n:
... | the_stack_v2_python_sparse | K/KthSmallestElementinaSortedMatrix.py | bssrdf/pyleet | train | 2 | |
ea1d26246f8b62aa32ba472c0cb190c7434f78c0 | [
"@lru_cache(None)\ndef dp(i, j):\n if i == len(nums1) or j == len(nums2):\n return 0\n if nums1[i] == nums2[j]:\n return 1 + dp(i + 1, j + 1)\n return 0\nreturn max((dp(i, j) for i in range(len(nums1)) for j in range(len(nums2))))",
"dp = [[0] * (len(nums2) + 1) for _ in range(len(nums1) + ... | <|body_start_0|>
@lru_cache(None)
def dp(i, j):
if i == len(nums1) or j == len(nums2):
return 0
if nums1[i] == nums2[j]:
return 1 + dp(i + 1, j + 1)
return 0
return max((dp(i, j) for i in range(len(nums1)) for j in range(len(num... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)"""
<|body_0|>
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""08/12/2021 01:32 DP bot... | stack_v2_sparse_classes_36k_train_024659 | 7,237 | no_license | [
{
"docstring": "09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)",
"name": "findLength",
"signature": "def findLength(self, nums1: List[int], nums2: List[int]) -> int"
},
{
"docstring": "08/12/2021 01:32 DP bottom up",
"name": "findLength",
"signature":... | 4 | stack_v2_sparse_classes_30k_train_000919 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLength(self, nums1: List[int], nums2: List[int]) -> int: 09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)
- def findLength(self, nums1:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLength(self, nums1: List[int], nums2: List[int]) -> int: 09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)
- def findLength(self, nums1:... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)"""
<|body_0|>
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""08/12/2021 01:32 DP bot... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)"""
@lru_cache(None)
def dp(i, j):
if i == len(nums1) or j == len(nums2):
return 0
if... | the_stack_v2_python_sparse | leetcode/solved/718_Maximum_Length_of_Repeated_Subarray/solution.py | sungminoh/algorithms | train | 0 | |
c03f60a45a26b16fd0ba163d1bf9dd43a53c21b1 | [
"self.value = value\nself.next = next_cell\nself.prev = prev_cell",
"print(self.value, end=' ')\nif self.next != None:\n self.next.__print_without_iterator_forward()\nelse:\n print()",
"print(self.value, end=' ')\nif self.prev != None:\n self.prev.__print_without_iterator_reversed()\nelse:\n print()... | <|body_start_0|>
self.value = value
self.next = next_cell
self.prev = prev_cell
<|end_body_0|>
<|body_start_1|>
print(self.value, end=' ')
if self.next != None:
self.next.__print_without_iterator_forward()
else:
print()
<|end_body_1|>
<|body_star... | Double-linked cells | Cell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cell:
"""Double-linked cells"""
def __init__(self, value, next_cell, prev_cell):
"""Creates a new cell with the specified values, and the links to the next and previous cells (if any). :param value: A value :type value: Any :param next_cell: The successor of this cell, if any or None... | stack_v2_sparse_classes_36k_train_024660 | 10,145 | no_license | [
{
"docstring": "Creates a new cell with the specified values, and the links to the next and previous cells (if any). :param value: A value :type value: Any :param next_cell: The successor of this cell, if any or None otherwise :type next_cell: Cell :param prev_cell: The predecessor of this cell, if any or None ... | 3 | stack_v2_sparse_classes_30k_train_010992 | Implement the Python class `Cell` described below.
Class description:
Double-linked cells
Method signatures and docstrings:
- def __init__(self, value, next_cell, prev_cell): Creates a new cell with the specified values, and the links to the next and previous cells (if any). :param value: A value :type value: Any :pa... | Implement the Python class `Cell` described below.
Class description:
Double-linked cells
Method signatures and docstrings:
- def __init__(self, value, next_cell, prev_cell): Creates a new cell with the specified values, and the links to the next and previous cells (if any). :param value: A value :type value: Any :pa... | 753e6cf2ddc6e95265b1c2ab5c8b3685c36d29e7 | <|skeleton|>
class Cell:
"""Double-linked cells"""
def __init__(self, value, next_cell, prev_cell):
"""Creates a new cell with the specified values, and the links to the next and previous cells (if any). :param value: A value :type value: Any :param next_cell: The successor of this cell, if any or None... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cell:
"""Double-linked cells"""
def __init__(self, value, next_cell, prev_cell):
"""Creates a new cell with the specified values, and the links to the next and previous cells (if any). :param value: A value :type value: Any :param next_cell: The successor of this cell, if any or None otherwise :t... | the_stack_v2_python_sparse | L2/Algo structure de données/TP3/src/listiterator.py | BenjaminDOUCHET/Travail-FIL | train | 0 |
bf221a3d3e7ce7eb491cec9c43bdbb43ed36e4f5 | [
"self.timeout = timeout\ntry:\n self.pre_snap = self.mapping.learn_ops(device=uut, abstract=abstract, steps=steps, timeout=timeout)\nexcept Exception as e:\n self.errored(\"Section failed due to: '{e}'\".format(e=e))\nfor stp in steps.details:\n if stp.result.name == 'skipped':\n self.skipped('Canno... | <|body_start_0|>
self.timeout = timeout
try:
self.pre_snap = self.mapping.learn_ops(device=uut, abstract=abstract, steps=steps, timeout=timeout)
except Exception as e:
self.errored("Section failed due to: '{e}'".format(e=e))
for stp in steps.details:
i... | Trigger class for Modify action | TriggerModify | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriggerModify:
"""Trigger class for Modify action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`... | stack_v2_sparse_classes_36k_train_024661 | 5,499 | permissive | [
{
"docstring": "Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object timeout (`timeout obj`): Timeout Object Returns: None Raises: pyATS Res... | 6 | stack_v2_sparse_classes_30k_train_019765 | Implement the Python class `TriggerModify` described below.
Class description:
Trigger class for Modify action
Method signatures and docstrings:
- def verify_prerequisite(self, uut, abstract, steps, timeout): Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next te... | Implement the Python class `TriggerModify` described below.
Class description:
Trigger class for Modify action
Method signatures and docstrings:
- def verify_prerequisite(self, uut, abstract, steps, timeout): Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next te... | e42e51475cddcb10f5c7814d0fe892ac865742ba | <|skeleton|>
class TriggerModify:
"""Trigger class for Modify action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TriggerModify:
"""Trigger class for Modify action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): Abstract o... | the_stack_v2_python_sparse | pkgs/sdk-pkg/src/genie/libs/sdk/triggers/modify/modify.py | CiscoTestAutomation/genielibs | train | 109 |
63b9ee0995fde029fb25fc0d11e86cc8c016b7ca | [
"AxisFormat.__init__(self, 'jets')\nself._axes['tracktpt'] = 0\nself._axes['jetpt'] = 1\nself._axes['tracketa'] = 2\nself._axes['trackphi'] = 3\nself._axes['vertexz'] = 4\nself._axes['mbtrigger'] = 5",
"newobj = AxisFormatJetTHnSparse()\nnewobj._Deepcopy(other, memo)\nreturn newobj",
"newobj = AxisFormatJetTHnS... | <|body_start_0|>
AxisFormat.__init__(self, 'jets')
self._axes['tracktpt'] = 0
self._axes['jetpt'] = 1
self._axes['tracketa'] = 2
self._axes['trackphi'] = 3
self._axes['vertexz'] = 4
self._axes['mbtrigger'] = 5
<|end_body_0|>
<|body_start_1|>
newobj = Axis... | Axis format for jet-based track THnSparse | AxisFormatJetTHnSparse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxisFormatJetTHnSparse:
"""Axis format for jet-based track THnSparse"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __deepcopy__(self, other, memo):
"""Deep copy constructor"""
<|body_1|>
def __copy__(self, other):
"""Shallow copy co... | stack_v2_sparse_classes_36k_train_024662 | 7,138 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Deep copy constructor",
"name": "__deepcopy__",
"signature": "def __deepcopy__(self, other, memo)"
},
{
"docstring": "Shallow copy constructor",
"name": "__copy__",
"sig... | 3 | null | Implement the Python class `AxisFormatJetTHnSparse` described below.
Class description:
Axis format for jet-based track THnSparse
Method signatures and docstrings:
- def __init__(self): Constructor
- def __deepcopy__(self, other, memo): Deep copy constructor
- def __copy__(self, other): Shallow copy constructor | Implement the Python class `AxisFormatJetTHnSparse` described below.
Class description:
Axis format for jet-based track THnSparse
Method signatures and docstrings:
- def __init__(self): Constructor
- def __deepcopy__(self, other, memo): Deep copy constructor
- def __copy__(self, other): Shallow copy constructor
<|sk... | 5df28b2b415e78e81273b0d9bf5c1b99feda3348 | <|skeleton|>
class AxisFormatJetTHnSparse:
"""Axis format for jet-based track THnSparse"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __deepcopy__(self, other, memo):
"""Deep copy constructor"""
<|body_1|>
def __copy__(self, other):
"""Shallow copy co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AxisFormatJetTHnSparse:
"""Axis format for jet-based track THnSparse"""
def __init__(self):
"""Constructor"""
AxisFormat.__init__(self, 'jets')
self._axes['tracktpt'] = 0
self._axes['jetpt'] = 1
self._axes['tracketa'] = 2
self._axes['trackphi'] = 3
... | the_stack_v2_python_sparse | PWGJE/EMCALJetTasks/Tracks/analysis/base/struct/JetTHnSparse.py | alisw/AliPhysics | train | 129 |
1a626ca2792e24235b8194e7009cc965ac169a4f | [
"self.num_map = {}\nfor i in range(len(nums)):\n if nums[i] not in self.num_map:\n self.num_map[nums[i]] = [i]\n else:\n self.num_map[nums[i]].append(i)",
"if target in self.num_map:\n high = len(self.num_map[target])\n import numpy as np\n index = np.random.randint(0, high)\n retu... | <|body_start_0|>
self.num_map = {}
for i in range(len(nums)):
if nums[i] not in self.num_map:
self.num_map[nums[i]] = [i]
else:
self.num_map[nums[i]].append(i)
<|end_body_0|>
<|body_start_1|>
if target in self.num_map:
high = l... | Solution_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_1:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def pick(self, target):
""":type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.num_map = {}
for i in range(len(nums)):
if... | stack_v2_sparse_classes_36k_train_024663 | 1,800 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type target: int :rtype: int",
"name": "pick",
"signature": "def pick(self, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002549 | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def pick(self, target): :type target: int :rtype: int | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def pick(self, target): :type target: int :rtype: int
<|skeleton|>
class Solution_1:
def __init__(self, nums):
... | 176cc1db3291843fb068f06d0180766dd8c3122c | <|skeleton|>
class Solution_1:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def pick(self, target):
""":type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution_1:
def __init__(self, nums):
""":type nums: List[int]"""
self.num_map = {}
for i in range(len(nums)):
if nums[i] not in self.num_map:
self.num_map[nums[i]] = [i]
else:
self.num_map[nums[i]].append(i)
def pick(self, t... | the_stack_v2_python_sparse | 2019/sampling/random_pick_index_398.py | yehongyu/acode | train | 0 | |
392e13a14c9614d39a6ae478afd18406c5ce23eb | [
"print('Received GET on resource /books')\nargs = query_parser.parse_args()\nlist_of_books = BookChecker.get_books(args)\nreturn (list_of_books, 200)",
"print('Received POST on resource /book')\nrequest_body = request.get_json()\na_book = BookChecker.create_book(request_body)\nreturn (a_book, 201)"
] | <|body_start_0|>
print('Received GET on resource /books')
args = query_parser.parse_args()
list_of_books = BookChecker.get_books(args)
return (list_of_books, 200)
<|end_body_0|>
<|body_start_1|>
print('Received POST on resource /book')
request_body = request.get_json()
... | Books | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Books:
def get(self):
"""Queries the books resource based on URL query string parameters. If no query string is provided all books are returned. Valid query arguments are: title, (author) first_name, (author) last_name, (author) middle_name, publish_date_start, publish_date_end, subject,... | stack_v2_sparse_classes_36k_train_024664 | 14,158 | no_license | [
{
"docstring": "Queries the books resource based on URL query string parameters. If no query string is provided all books are returned. Valid query arguments are: title, (author) first_name, (author) last_name, (author) middle_name, publish_date_start, publish_date_end, subject, genre. :return: JSON List of boo... | 2 | stack_v2_sparse_classes_30k_train_003420 | Implement the Python class `Books` described below.
Class description:
Implement the Books class.
Method signatures and docstrings:
- def get(self): Queries the books resource based on URL query string parameters. If no query string is provided all books are returned. Valid query arguments are: title, (author) first_... | Implement the Python class `Books` described below.
Class description:
Implement the Books class.
Method signatures and docstrings:
- def get(self): Queries the books resource based on URL query string parameters. If no query string is provided all books are returned. Valid query arguments are: title, (author) first_... | 4c3fdf41a43a56c253faecacac5f9d977d9c99be | <|skeleton|>
class Books:
def get(self):
"""Queries the books resource based on URL query string parameters. If no query string is provided all books are returned. Valid query arguments are: title, (author) first_name, (author) last_name, (author) middle_name, publish_date_start, publish_date_end, subject,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Books:
def get(self):
"""Queries the books resource based on URL query string parameters. If no query string is provided all books are returned. Valid query arguments are: title, (author) first_name, (author) last_name, (author) middle_name, publish_date_start, publish_date_end, subject, genre. :retur... | the_stack_v2_python_sparse | apis/books_api.py | neu-seattle-cs5500-fall18/book-library-web-service-scrumptious | train | 0 | |
c3c730f01c8ccb09158a25cc6620d1f7888bbf36 | [
"if not board:\n return False\nfor i in range(len(board)):\n for j in range(len(board[0])):\n if self.dfs(board, i, j, word):\n return True\nreturn False",
"if len(word) == 0:\n return True\nif i < 0 or i >= len(board) or j < 0 or (j >= len(board[0])) or (board[i][j] != word[0]):\n r... | <|body_start_0|>
if not board:
return False
for i in range(len(board)):
for j in range(len(board[0])):
if self.dfs(board, i, j, word):
return True
return False
<|end_body_0|>
<|body_start_1|>
if len(word) == 0:
retu... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def exist(self, board, word):
""":type board: List[List[str]] :type word: str :rtype: bool"""
<|body_0|>
def dfs(self, board, i, j, word):
"""Depth-First-Search :param board: :param i: :param j: :param word: :return:"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_024665 | 1,433 | permissive | [
{
"docstring": ":type board: List[List[str]] :type word: str :rtype: bool",
"name": "exist",
"signature": "def exist(self, board, word)"
},
{
"docstring": "Depth-First-Search :param board: :param i: :param j: :param word: :return:",
"name": "dfs",
"signature": "def dfs(self, board, i, j,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def exist(self, board, word): :type board: List[List[str]] :type word: str :rtype: bool
- def dfs(self, board, i, j, word): Depth-First-Search :param board: :param i: :param j: :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def exist(self, board, word): :type board: List[List[str]] :type word: str :rtype: bool
- def dfs(self, board, i, j, word): Depth-First-Search :param board: :param i: :param j: :... | 6ddba1f3b86c40639a8203cbc3373d52301c1b1f | <|skeleton|>
class Solution:
def exist(self, board, word):
""":type board: List[List[str]] :type word: str :rtype: bool"""
<|body_0|>
def dfs(self, board, i, j, word):
"""Depth-First-Search :param board: :param i: :param j: :param word: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def exist(self, board, word):
""":type board: List[List[str]] :type word: str :rtype: bool"""
if not board:
return False
for i in range(len(board)):
for j in range(len(board[0])):
if self.dfs(board, i, j, word):
retu... | the_stack_v2_python_sparse | algorithms/python/leetcode/WordSearch.py | ytjia/leetcode | train | 0 | |
970ea3ef0d83e584527da0923ddac7120cb5c062 | [
"from zope.component.hooks import getSite\nportal = getSite()\nresults = []\nkeys = [result for result in portal.uid_catalog.searchResults(portal_type='SimpleVocabularyTerm', sort_on='Title') if 'category1' in result.getPath()]\nfor value in keys:\n results.append({'id': value.id, 'title': value.Title})\nreturn ... | <|body_start_0|>
from zope.component.hooks import getSite
portal = getSite()
results = []
keys = [result for result in portal.uid_catalog.searchResults(portal_type='SimpleVocabularyTerm', sort_on='Title') if 'category1' in result.getPath()]
for value in keys:
results.... | Overrides static.pt in the rendering of the portlet. | Renderer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Renderer:
"""Overrides static.pt in the rendering of the portlet."""
def mostrarEtiquetesCategory1(self):
"""Categories Servei"""
<|body_0|>
def mostrarEtiquetesCategory2(self):
"""Categories Servei PPS"""
<|body_1|>
def mostrarEtiquetesCategory3(sel... | stack_v2_sparse_classes_36k_train_024666 | 2,840 | no_license | [
{
"docstring": "Categories Servei",
"name": "mostrarEtiquetesCategory1",
"signature": "def mostrarEtiquetesCategory1(self)"
},
{
"docstring": "Categories Servei PPS",
"name": "mostrarEtiquetesCategory2",
"signature": "def mostrarEtiquetesCategory2(self)"
},
{
"docstring": "By Cat... | 4 | stack_v2_sparse_classes_30k_train_008844 | Implement the Python class `Renderer` described below.
Class description:
Overrides static.pt in the rendering of the portlet.
Method signatures and docstrings:
- def mostrarEtiquetesCategory1(self): Categories Servei
- def mostrarEtiquetesCategory2(self): Categories Servei PPS
- def mostrarEtiquetesCategory3(self): ... | Implement the Python class `Renderer` described below.
Class description:
Overrides static.pt in the rendering of the portlet.
Method signatures and docstrings:
- def mostrarEtiquetesCategory1(self): Categories Servei
- def mostrarEtiquetesCategory2(self): Categories Servei PPS
- def mostrarEtiquetesCategory3(self): ... | b21e765ae29b5fea532c0871187fac06f2c4cee2 | <|skeleton|>
class Renderer:
"""Overrides static.pt in the rendering of the portlet."""
def mostrarEtiquetesCategory1(self):
"""Categories Servei"""
<|body_0|>
def mostrarEtiquetesCategory2(self):
"""Categories Servei PPS"""
<|body_1|>
def mostrarEtiquetesCategory3(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Renderer:
"""Overrides static.pt in the rendering of the portlet."""
def mostrarEtiquetesCategory1(self):
"""Categories Servei"""
from zope.component.hooks import getSite
portal = getSite()
results = []
keys = [result for result in portal.uid_catalog.searchResults(... | the_stack_v2_python_sparse | src/notes/kbtic/portlets/etiquetesADS.py | UPCnet/notes.kbtic | train | 0 |
08182f71ff655a78b624cd0c406e0b6411767cb0 | [
"super(OAuth2UserAccountClient, self).__init__(cache_key_base=refresh_token, auth_uri=auth_uri, token_uri=token_uri, access_token_cache=access_token_cache, datetime_strategy=datetime_strategy, disable_ssl_certificate_validation=disable_ssl_certificate_validation, proxy_host=proxy_host, proxy_port=proxy_port, proxy_... | <|body_start_0|>
super(OAuth2UserAccountClient, self).__init__(cache_key_base=refresh_token, auth_uri=auth_uri, token_uri=token_uri, access_token_cache=access_token_cache, datetime_strategy=datetime_strategy, disable_ssl_certificate_validation=disable_ssl_certificate_validation, proxy_host=proxy_host, proxy_por... | An OAuth2 client. | OAuth2UserAccountClient | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OAuth2UserAccountClient:
"""An OAuth2 client."""
def __init__(self, token_uri, client_id, client_secret, refresh_token, auth_uri=None, access_token_cache=None, datetime_strategy=datetime.datetime, disable_ssl_certificate_validation=False, proxy_host=None, proxy_port=None, proxy_user=None, pr... | stack_v2_sparse_classes_36k_train_024667 | 29,065 | permissive | [
{
"docstring": "Creates an OAuth2UserAccountClient. Args: token_uri: The URI used to refresh access tokens. client_id: The OAuth2 client ID of this client. client_secret: The OAuth2 client secret of this client. refresh_token: The token used to refresh the access token. auth_uri: The URI for OAuth2 authorizatio... | 3 | stack_v2_sparse_classes_30k_train_006380 | Implement the Python class `OAuth2UserAccountClient` described below.
Class description:
An OAuth2 client.
Method signatures and docstrings:
- def __init__(self, token_uri, client_id, client_secret, refresh_token, auth_uri=None, access_token_cache=None, datetime_strategy=datetime.datetime, disable_ssl_certificate_val... | Implement the Python class `OAuth2UserAccountClient` described below.
Class description:
An OAuth2 client.
Method signatures and docstrings:
- def __init__(self, token_uri, client_id, client_secret, refresh_token, auth_uri=None, access_token_cache=None, datetime_strategy=datetime.datetime, disable_ssl_certificate_val... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class OAuth2UserAccountClient:
"""An OAuth2 client."""
def __init__(self, token_uri, client_id, client_secret, refresh_token, auth_uri=None, access_token_cache=None, datetime_strategy=datetime.datetime, disable_ssl_certificate_validation=False, proxy_host=None, proxy_port=None, proxy_user=None, pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OAuth2UserAccountClient:
"""An OAuth2 client."""
def __init__(self, token_uri, client_id, client_secret, refresh_token, auth_uri=None, access_token_cache=None, datetime_strategy=datetime.datetime, disable_ssl_certificate_validation=False, proxy_host=None, proxy_port=None, proxy_user=None, proxy_pass=None... | the_stack_v2_python_sparse | third_party/gsutil/third_party/gcs-oauth2-boto-plugin/gcs_oauth2_boto_plugin/oauth2_client.py | catapult-project/catapult | train | 2,032 |
b99a58428fdcda9e25724fc41a2d71a79cd01961 | [
"if data is not None:\n if not isinstance(data, pd.DataFrame):\n raise ValueError('data should be a Pandas DataFrame')\n data = data.copy()\n if budget < 1:\n raise ValueError('budget parameter should be a positive integer')\n if not 0 < conf < 1:\n raise ValueError('conf should be ... | <|body_start_0|>
if data is not None:
if not isinstance(data, pd.DataFrame):
raise ValueError('data should be a Pandas DataFrame')
data = data.copy()
if budget < 1:
raise ValueError('budget parameter should be a positive integer')
i... | A place holder for a training set and a holdout set | DataSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSource:
"""A place holder for a training set and a holdout set"""
def __init__(self, data, budget=1, conf=0.95, train_size=0.5, random_state=0):
"""Prepares a dataset for FairTest investigations. Encodes categorical features as numbers and separates the data into a training set a... | stack_v2_sparse_classes_36k_train_024668 | 4,368 | permissive | [
{
"docstring": "Prepares a dataset for FairTest investigations. Encodes categorical features as numbers and separates the data into a training set and a holdout set. Parameters ---------- data : the dataset to use budget : the maximal number of adaptive investigations that will be performed conf : overall famil... | 2 | null | Implement the Python class `DataSource` described below.
Class description:
A place holder for a training set and a holdout set
Method signatures and docstrings:
- def __init__(self, data, budget=1, conf=0.95, train_size=0.5, random_state=0): Prepares a dataset for FairTest investigations. Encodes categorical feature... | Implement the Python class `DataSource` described below.
Class description:
A place holder for a training set and a holdout set
Method signatures and docstrings:
- def __init__(self, data, budget=1, conf=0.95, train_size=0.5, random_state=0): Prepares a dataset for FairTest investigations. Encodes categorical feature... | 8696051c9276f127ab8b2f437850f845ff0ca786 | <|skeleton|>
class DataSource:
"""A place holder for a training set and a holdout set"""
def __init__(self, data, budget=1, conf=0.95, train_size=0.5, random_state=0):
"""Prepares a dataset for FairTest investigations. Encodes categorical features as numbers and separates the data into a training set a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataSource:
"""A place holder for a training set and a holdout set"""
def __init__(self, data, budget=1, conf=0.95, train_size=0.5, random_state=0):
"""Prepares a dataset for FairTest investigations. Encodes categorical features as numbers and separates the data into a training set and a holdout ... | the_stack_v2_python_sparse | src/fairtest/holdout.py | columbia/fairtest | train | 48 |
7e77df16a663ed6ff725875b8d2746d7cd9ba258 | [
"try:\n entry = session.query(db.RememberEntry).filter(db.RememberEntry.id == rejected_entry_id).one()\nexcept NoResultFound:\n raise NotFoundError('rejected entry ID %d not found' % rejected_entry_id)\nreturn jsonify(rejected_entry_to_dict(entry))",
"try:\n entry = session.query(db.RememberEntry).filter... | <|body_start_0|>
try:
entry = session.query(db.RememberEntry).filter(db.RememberEntry.id == rejected_entry_id).one()
except NoResultFound:
raise NotFoundError('rejected entry ID %d not found' % rejected_entry_id)
return jsonify(rejected_entry_to_dict(entry))
<|end_body_0|... | RejectedEntry | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RejectedEntry:
def get(self, rejected_entry_id, session=None):
"""Returns a rejected entry"""
<|body_0|>
def delete(self, rejected_entry_id, session=None):
"""Deletes a rejected entry"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_024669 | 5,092 | permissive | [
{
"docstring": "Returns a rejected entry",
"name": "get",
"signature": "def get(self, rejected_entry_id, session=None)"
},
{
"docstring": "Deletes a rejected entry",
"name": "delete",
"signature": "def delete(self, rejected_entry_id, session=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021189 | Implement the Python class `RejectedEntry` described below.
Class description:
Implement the RejectedEntry class.
Method signatures and docstrings:
- def get(self, rejected_entry_id, session=None): Returns a rejected entry
- def delete(self, rejected_entry_id, session=None): Deletes a rejected entry | Implement the Python class `RejectedEntry` described below.
Class description:
Implement the RejectedEntry class.
Method signatures and docstrings:
- def get(self, rejected_entry_id, session=None): Returns a rejected entry
- def delete(self, rejected_entry_id, session=None): Deletes a rejected entry
<|skeleton|>
cla... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class RejectedEntry:
def get(self, rejected_entry_id, session=None):
"""Returns a rejected entry"""
<|body_0|>
def delete(self, rejected_entry_id, session=None):
"""Deletes a rejected entry"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RejectedEntry:
def get(self, rejected_entry_id, session=None):
"""Returns a rejected entry"""
try:
entry = session.query(db.RememberEntry).filter(db.RememberEntry.id == rejected_entry_id).one()
except NoResultFound:
raise NotFoundError('rejected entry ID %d not ... | the_stack_v2_python_sparse | flexget/components/rejected/api.py | BrutuZ/Flexget | train | 1 | |
a64e7210b5ff743d9436c637ae933bc1ca56e0eb | [
"super().__init__(raster_mode, dwell_time, total_time, dwell_time_live)\nself.step_count_x = step_count_x\nself.step_count_y = step_count_y\nself.step_size_x = step_size_x\nself.step_size_y = step_size_y\nself.frame_count = frame_count\nself.position = position",
"try:\n location = next(iter(self.positions.key... | <|body_start_0|>
super().__init__(raster_mode, dwell_time, total_time, dwell_time_live)
self.step_count_x = step_count_x
self.step_count_y = step_count_y
self.step_size_x = step_size_x
self.step_size_y = step_size_y
self.frame_count = frame_count
self.position = p... | AcquisitionRasterXY | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AcquisitionRasterXY:
def __init__(self, step_count_x, step_count_y, step_size_x=None, step_size_y=None, frame_count=None, position=None, raster_mode=None, dwell_time=None, total_time=None, dwell_time_live=None):
"""Defines the position and duration of a two-dimensional X/Y raster over th... | stack_v2_sparse_classes_36k_train_024670 | 15,189 | permissive | [
{
"docstring": "Defines the position and duration of a two-dimensional X/Y raster over the specimen. :arg step_count_x: number of steps in x direction (required) :arg step_count_y: number of steps in y direction (required) :arg step_size_x: dimension of each step in x direction (optional) :arg step_size_y: dime... | 3 | null | Implement the Python class `AcquisitionRasterXY` described below.
Class description:
Implement the AcquisitionRasterXY class.
Method signatures and docstrings:
- def __init__(self, step_count_x, step_count_y, step_size_x=None, step_size_y=None, frame_count=None, position=None, raster_mode=None, dwell_time=None, total... | Implement the Python class `AcquisitionRasterXY` described below.
Class description:
Implement the AcquisitionRasterXY class.
Method signatures and docstrings:
- def __init__(self, step_count_x, step_count_y, step_size_x=None, step_size_y=None, frame_count=None, position=None, raster_mode=None, dwell_time=None, total... | 0081ea29127c72e8a0511a9f8fc58d0fe098b801 | <|skeleton|>
class AcquisitionRasterXY:
def __init__(self, step_count_x, step_count_y, step_size_x=None, step_size_y=None, frame_count=None, position=None, raster_mode=None, dwell_time=None, total_time=None, dwell_time_live=None):
"""Defines the position and duration of a two-dimensional X/Y raster over th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AcquisitionRasterXY:
def __init__(self, step_count_x, step_count_y, step_size_x=None, step_size_y=None, frame_count=None, position=None, raster_mode=None, dwell_time=None, total_time=None, dwell_time_live=None):
"""Defines the position and duration of a two-dimensional X/Y raster over the specimen. :a... | the_stack_v2_python_sparse | pyhmsa/spec/condition/acquisition.py | pyhmsa/pyhmsa | train | 2 | |
fc46f7c2efb9fbed80c3289deed05e8919a94f5d | [
"if not isinstance(obj, INDEXABLE):\n raise Exception('Invalid index object')\nif not obj.name:\n return\nct = ContentType.objects.get_for_model(obj)\ntry:\n idx = self.get(obj_ct=ct, obj_id=getattr(obj, obj.id_field))\nexcept ObjectDoesNotExist:\n idx = self.model(obj=obj)\nidx.name = obj.name\nidx.typ... | <|body_start_0|>
if not isinstance(obj, INDEXABLE):
raise Exception('Invalid index object')
if not obj.name:
return
ct = ContentType.objects.get_for_model(obj)
try:
idx = self.get(obj_ct=ct, obj_id=getattr(obj, obj.id_field))
except ObjectDoesN... | IndexManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexManager:
def add(self, obj):
"""Adds an object to the index. If the index already exists for this object, it is updated. If it does not exist, it is created. :param obj: the object to add to the index :return: the index instance"""
<|body_0|>
def remove(self, obj):
... | stack_v2_sparse_classes_36k_train_024671 | 2,697 | no_license | [
{
"docstring": "Adds an object to the index. If the index already exists for this object, it is updated. If it does not exist, it is created. :param obj: the object to add to the index :return: the index instance",
"name": "add",
"signature": "def add(self, obj)"
},
{
"docstring": "Removes an ob... | 2 | null | Implement the Python class `IndexManager` described below.
Class description:
Implement the IndexManager class.
Method signatures and docstrings:
- def add(self, obj): Adds an object to the index. If the index already exists for this object, it is updated. If it does not exist, it is created. :param obj: the object t... | Implement the Python class `IndexManager` described below.
Class description:
Implement the IndexManager class.
Method signatures and docstrings:
- def add(self, obj): Adds an object to the index. If the index already exists for this object, it is updated. If it does not exist, it is created. :param obj: the object t... | b6d476159783761c5c774447808b382c2ea7e8e0 | <|skeleton|>
class IndexManager:
def add(self, obj):
"""Adds an object to the index. If the index already exists for this object, it is updated. If it does not exist, it is created. :param obj: the object to add to the index :return: the index instance"""
<|body_0|>
def remove(self, obj):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IndexManager:
def add(self, obj):
"""Adds an object to the index. If the index already exists for this object, it is updated. If it does not exist, it is created. :param obj: the object to add to the index :return: the index instance"""
if not isinstance(obj, INDEXABLE):
raise Exce... | the_stack_v2_python_sparse | search/models.py | info3g/hikstar-celery | train | 0 | |
bd0d8156285e2d0f305af1f34a88ceea8c976356 | [
"connection_kwargs = kwargs.copy()\nself.sock: Optional[socket.socket] = None\nif timeout is not None:\n if isinstance(timeout, urllib3.Timeout):\n try:\n connection_kwargs['timeout'] = float(timeout.total)\n except TypeError:\n pass\n connection_kwargs['timeout'] = timeout... | <|body_start_0|>
connection_kwargs = kwargs.copy()
self.sock: Optional[socket.socket] = None
if timeout is not None:
if isinstance(timeout, urllib3.Timeout):
try:
connection_kwargs['timeout'] = float(timeout.total)
except TypeError:... | Specialization of HTTPConnection to use a UNIX domain sockets. | UDSConnection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UDSConnection:
"""Specialization of HTTPConnection to use a UNIX domain sockets."""
def __init__(self, host: str, port: int, timeout: Union[float, urllib3.Timeout, None]=None, strict=False, **kwargs):
"""Initialize connection to UNIX domain socket for HTTP client. Args: host: Ignored... | stack_v2_sparse_classes_36k_train_024672 | 5,919 | permissive | [
{
"docstring": "Initialize connection to UNIX domain socket for HTTP client. Args: host: Ignored. port: Ignored. timeout: Time to allow for operation. strict: Ignored. Keyword Args: uds: Full address of a Podman service UNIX domain socket. Required.",
"name": "__init__",
"signature": "def __init__(self,... | 2 | stack_v2_sparse_classes_30k_train_005400 | Implement the Python class `UDSConnection` described below.
Class description:
Specialization of HTTPConnection to use a UNIX domain sockets.
Method signatures and docstrings:
- def __init__(self, host: str, port: int, timeout: Union[float, urllib3.Timeout, None]=None, strict=False, **kwargs): Initialize connection t... | Implement the Python class `UDSConnection` described below.
Class description:
Specialization of HTTPConnection to use a UNIX domain sockets.
Method signatures and docstrings:
- def __init__(self, host: str, port: int, timeout: Union[float, urllib3.Timeout, None]=None, strict=False, **kwargs): Initialize connection t... | c7356dcff7d15fd0da61e9ffb226e789c2d7d9c4 | <|skeleton|>
class UDSConnection:
"""Specialization of HTTPConnection to use a UNIX domain sockets."""
def __init__(self, host: str, port: int, timeout: Union[float, urllib3.Timeout, None]=None, strict=False, **kwargs):
"""Initialize connection to UNIX domain socket for HTTP client. Args: host: Ignored... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UDSConnection:
"""Specialization of HTTPConnection to use a UNIX domain sockets."""
def __init__(self, host: str, port: int, timeout: Union[float, urllib3.Timeout, None]=None, strict=False, **kwargs):
"""Initialize connection to UNIX domain socket for HTTP client. Args: host: Ignored. port: Ignor... | the_stack_v2_python_sparse | podman/api/uds.py | containers/podman-py | train | 190 |
102dbea9c66eb1151dfda385912b58c0d0e2a23f | [
"self.agent_id = agent_id\nself.agent_args = agent_known_args\nself.non_agent_args = non_agent_known_args\nself.command_args = command_known_args\nself.arg_groups = [(vars(agent_known_args), {**agent_args, **xagents.agents[agent_id]['module'].cli_args}, self.agent_args), (vars(non_agent_known_args), {**non_agent_ar... | <|body_start_0|>
self.agent_id = agent_id
self.agent_args = agent_known_args
self.non_agent_args = non_agent_known_args
self.command_args = command_known_args
self.arg_groups = [(vars(agent_known_args), {**agent_args, **xagents.agents[agent_id]['module'].cli_args}, self.agent_arg... | Objective function wrapper class. | Objective | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Objective:
"""Objective function wrapper class."""
def __init__(self, agent_id, agent_known_args, non_agent_known_args, command_known_args):
"""Initialize objective function parameters. Args: agent_id: One of the agent ids available in xagents.agents agent_known_args: argparse.Namesp... | stack_v2_sparse_classes_36k_train_024673 | 5,623 | permissive | [
{
"docstring": "Initialize objective function parameters. Args: agent_id: One of the agent ids available in xagents.agents agent_known_args: argparse.Namespace, containing options passed to agent. non_agent_known_args: argparse.Namespace, containing options passed to environments, optimizer and other non-agent ... | 3 | stack_v2_sparse_classes_30k_train_012467 | Implement the Python class `Objective` described below.
Class description:
Objective function wrapper class.
Method signatures and docstrings:
- def __init__(self, agent_id, agent_known_args, non_agent_known_args, command_known_args): Initialize objective function parameters. Args: agent_id: One of the agent ids avai... | Implement the Python class `Objective` described below.
Class description:
Objective function wrapper class.
Method signatures and docstrings:
- def __init__(self, agent_id, agent_known_args, non_agent_known_args, command_known_args): Initialize objective function parameters. Args: agent_id: One of the agent ids avai... | 73ad38b07e2b2bca7487f0a5ac5a49e4f3f0dc35 | <|skeleton|>
class Objective:
"""Objective function wrapper class."""
def __init__(self, agent_id, agent_known_args, non_agent_known_args, command_known_args):
"""Initialize objective function parameters. Args: agent_id: One of the agent ids available in xagents.agents agent_known_args: argparse.Namesp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Objective:
"""Objective function wrapper class."""
def __init__(self, agent_id, agent_known_args, non_agent_known_args, command_known_args):
"""Initialize objective function parameters. Args: agent_id: One of the agent ids available in xagents.agents agent_known_args: argparse.Namespace, containi... | the_stack_v2_python_sparse | xagents/utils/tuning.py | ClarityCoders/xagents | train | 0 |
207076fd8ab3146cfe118ccec53b72566d9f2ea9 | [
"litLinkTable = {}\nlitLs = cmds.ls(type='light')\nif litLs:\n for lit in litLs:\n ilObjLs = cmds.ls(cmds.lightlink(query=True, light=lit), type='mesh')\n litLinkTable[lit] = ilObjLs\nreturn litLinkTable",
"for lit in info.keys():\n ilObjLs = cmds.ls(cmds.lightlink(query=True, light=lit), type... | <|body_start_0|>
litLinkTable = {}
litLs = cmds.ls(type='light')
if litLs:
for lit in litLs:
ilObjLs = cmds.ls(cmds.lightlink(query=True, light=lit), type='mesh')
litLinkTable[lit] = ilObjLs
return litLinkTable
<|end_body_0|>
<|body_start_1|>
... | Light link information class. Save light link information and create light link from saved information. | LightLinkInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LightLinkInfo:
"""Light link information class. Save light link information and create light link from saved information."""
def getSceneLitLnkInfo(self):
"""Get current scene light links information."""
<|body_0|>
def relinkLit(self, info):
"""Relink lights with... | stack_v2_sparse_classes_36k_train_024674 | 5,415 | no_license | [
{
"docstring": "Get current scene light links information.",
"name": "getSceneLitLnkInfo",
"signature": "def getSceneLitLnkInfo(self)"
},
{
"docstring": "Relink lights with information.",
"name": "relinkLit",
"signature": "def relinkLit(self, info)"
}
] | 2 | null | Implement the Python class `LightLinkInfo` described below.
Class description:
Light link information class. Save light link information and create light link from saved information.
Method signatures and docstrings:
- def getSceneLitLnkInfo(self): Get current scene light links information.
- def relinkLit(self, info... | Implement the Python class `LightLinkInfo` described below.
Class description:
Light link information class. Save light link information and create light link from saved information.
Method signatures and docstrings:
- def getSceneLitLnkInfo(self): Get current scene light links information.
- def relinkLit(self, info... | bd98679cbab869a0c96eac34cb2f199dfbf8fee8 | <|skeleton|>
class LightLinkInfo:
"""Light link information class. Save light link information and create light link from saved information."""
def getSceneLitLnkInfo(self):
"""Get current scene light links information."""
<|body_0|>
def relinkLit(self, info):
"""Relink lights with... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LightLinkInfo:
"""Light link information class. Save light link information and create light link from saved information."""
def getSceneLitLnkInfo(self):
"""Get current scene light links information."""
litLinkTable = {}
litLs = cmds.ls(type='light')
if litLs:
... | the_stack_v2_python_sparse | python/tak_saveSceneInfo.py | jasonbrackman/scripts | train | 0 |
154a7b9d972ed9033495f161d622f4b10c38aa3a | [
"if args is None:\n args = []\nif context is None:\n context = {}\nif not context.get('closed', False):\n args.append(('state', '=', 'draft'))\nreturn super(account_period, self).name_search(cr, uid, name, args=args, operator='ilike', context=context, limit=limit)",
"if self.search(cr, uid, [('id', 'in',... | <|body_start_0|>
if args is None:
args = []
if context is None:
context = {}
if not context.get('closed', False):
args.append(('state', '=', 'draft'))
return super(account_period, self).name_search(cr, uid, name, args=args, operator='ilike', context=co... | account_period | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_period:
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
"""Inherit name_search method to display only open period unless order close period by sending closed=True in context @return: super name_search"""
<|body_0|>
def acti... | stack_v2_sparse_classes_36k_train_024675 | 16,800 | no_license | [
{
"docstring": "Inherit name_search method to display only open period unless order close period by sending closed=True in context @return: super name_search",
"name": "name_search",
"signature": "def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_021033 | Implement the Python class `account_period` described below.
Class description:
Implement the account_period class.
Method signatures and docstrings:
- def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100): Inherit name_search method to display only open period unless order close ... | Implement the Python class `account_period` described below.
Class description:
Implement the account_period class.
Method signatures and docstrings:
- def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100): Inherit name_search method to display only open period unless order close ... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class account_period:
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
"""Inherit name_search method to display only open period unless order close period by sending closed=True in context @return: super name_search"""
<|body_0|>
def acti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class account_period:
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
"""Inherit name_search method to display only open period unless order close period by sending closed=True in context @return: super name_search"""
if args is None:
args = []... | the_stack_v2_python_sparse | v_7/Dongola/wafi/account_custom_wafi/account_custom(old).py | musabahmed/baba | train | 0 | |
6ccf18ebf2598d6546c289edf100209f458c6335 | [
"settings_file = current_app.config.get('GAME_SETTINGS_FILE')\nif not settings_file:\n raise RuntimeError('GAME_SETTINGS_FILE is not set')\nsettings_file = os.path.join(os.path.dirname(current_app.instance_path), 'kingdom_api', settings_file)\nif not os.path.isfile(settings_file):\n raise RuntimeError(f'Confi... | <|body_start_0|>
settings_file = current_app.config.get('GAME_SETTINGS_FILE')
if not settings_file:
raise RuntimeError('GAME_SETTINGS_FILE is not set')
settings_file = os.path.join(os.path.dirname(current_app.instance_path), 'kingdom_api', settings_file)
if not os.path.isfile... | Basic Settings logic. | SettingsService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SettingsService:
"""Basic Settings logic."""
def load_game_conf(cls) -> dict:
"""Load game configuration. :return: dict of settings"""
<|body_0|>
def initialize(cls, settings: Settings) -> Settings:
"""Init settings at the start from configuration. :param setting... | stack_v2_sparse_classes_36k_train_024676 | 2,351 | no_license | [
{
"docstring": "Load game configuration. :return: dict of settings",
"name": "load_game_conf",
"signature": "def load_game_conf(cls) -> dict"
},
{
"docstring": "Init settings at the start from configuration. :param settings: Settings model :return: Settings model - filled with data",
"name":... | 2 | stack_v2_sparse_classes_30k_train_021387 | Implement the Python class `SettingsService` described below.
Class description:
Basic Settings logic.
Method signatures and docstrings:
- def load_game_conf(cls) -> dict: Load game configuration. :return: dict of settings
- def initialize(cls, settings: Settings) -> Settings: Init settings at the start from configur... | Implement the Python class `SettingsService` described below.
Class description:
Basic Settings logic.
Method signatures and docstrings:
- def load_game_conf(cls) -> dict: Load game configuration. :return: dict of settings
- def initialize(cls, settings: Settings) -> Settings: Init settings at the start from configur... | 48408f43cbbeed035ed30c29c8c8f13c8886e949 | <|skeleton|>
class SettingsService:
"""Basic Settings logic."""
def load_game_conf(cls) -> dict:
"""Load game configuration. :return: dict of settings"""
<|body_0|>
def initialize(cls, settings: Settings) -> Settings:
"""Init settings at the start from configuration. :param setting... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SettingsService:
"""Basic Settings logic."""
def load_game_conf(cls) -> dict:
"""Load game configuration. :return: dict of settings"""
settings_file = current_app.config.get('GAME_SETTINGS_FILE')
if not settings_file:
raise RuntimeError('GAME_SETTINGS_FILE is not set')... | the_stack_v2_python_sparse | kingdom_api/services/settings.py | AlexKupreev/kingdom-api | train | 0 |
ba7a65cb8068625aa203abf9a37da0fbd72d49af | [
"logging.info('=============测试关注=============')\nl = CloudDPage(self.driver)\nself.assertTrue(l.login_cloudD())\nl.blogPostAttention()\ntime.sleep(3)\nself.assertTrue(l.check_blogPostAttention())",
"logging.info('=============测试点赞=============')\nl = CloudDPage(self.driver)\nself.assertTrue(l.login_cloudD())\nl.b... | <|body_start_0|>
logging.info('=============测试关注=============')
l = CloudDPage(self.driver)
self.assertTrue(l.login_cloudD())
l.blogPostAttention()
time.sleep(3)
self.assertTrue(l.check_blogPostAttention())
<|end_body_0|>
<|body_start_1|>
logging.info('==========... | TestCloudDPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCloudDPage:
def test_blogPostAttention(self):
"""测试关注 :return:"""
<|body_0|>
def test_blogPostLike(self):
"""测试点赞 :return:"""
<|body_1|>
def test_blogPostRely(self):
"""测试回复 :return:"""
<|body_2|>
def test_blogPostRelyDel(self):
... | stack_v2_sparse_classes_36k_train_024677 | 2,335 | no_license | [
{
"docstring": "测试关注 :return:",
"name": "test_blogPostAttention",
"signature": "def test_blogPostAttention(self)"
},
{
"docstring": "测试点赞 :return:",
"name": "test_blogPostLike",
"signature": "def test_blogPostLike(self)"
},
{
"docstring": "测试回复 :return:",
"name": "test_blogPo... | 5 | stack_v2_sparse_classes_30k_train_010262 | Implement the Python class `TestCloudDPage` described below.
Class description:
Implement the TestCloudDPage class.
Method signatures and docstrings:
- def test_blogPostAttention(self): 测试关注 :return:
- def test_blogPostLike(self): 测试点赞 :return:
- def test_blogPostRely(self): 测试回复 :return:
- def test_blogPostRelyDel(s... | Implement the Python class `TestCloudDPage` described below.
Class description:
Implement the TestCloudDPage class.
Method signatures and docstrings:
- def test_blogPostAttention(self): 测试关注 :return:
- def test_blogPostLike(self): 测试点赞 :return:
- def test_blogPostRely(self): 测试回复 :return:
- def test_blogPostRelyDel(s... | d2b7819fd3687e0a011988fefab3e6fd70bb014a | <|skeleton|>
class TestCloudDPage:
def test_blogPostAttention(self):
"""测试关注 :return:"""
<|body_0|>
def test_blogPostLike(self):
"""测试点赞 :return:"""
<|body_1|>
def test_blogPostRely(self):
"""测试回复 :return:"""
<|body_2|>
def test_blogPostRelyDel(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCloudDPage:
def test_blogPostAttention(self):
"""测试关注 :return:"""
logging.info('=============测试关注=============')
l = CloudDPage(self.driver)
self.assertTrue(l.login_cloudD())
l.blogPostAttention()
time.sleep(3)
self.assertTrue(l.check_blogPostAttenti... | the_stack_v2_python_sparse | care_user/test_case/test_cloudDPage.py | vothin/code | train | 0 | |
92df0d6fcf88658ed8b0f11e8dd703ae2a8f47b0 | [
"super().__init__(f'Substation Assembly Line {num}')\nself.assigned = assigned\nself.takt_time = takt_time\nself.attach_time = attach_time\nself.target = target",
"if self.env is None:\n raise AgentNotRegistered(self)\nelse:\n payload = {**kwargs, 'agent': str(self), 'action': action, 'duration': float(dura... | <|body_start_0|>
super().__init__(f'Substation Assembly Line {num}')
self.assigned = assigned
self.takt_time = takt_time
self.attach_time = attach_time
self.target = target
<|end_body_0|>
<|body_start_1|>
if self.env is None:
raise AgentNotRegistered(self)
... | Substation Assembly Line Class. | SubstationAssemblyLine | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubstationAssemblyLine:
"""Substation Assembly Line Class."""
def __init__(self, assigned, takt_time, attach_time, target, num):
"""Creates an instance of `SubstructureAssemblyLine`. Parameters ---------- assigned : list List of assigned tasks. Can be shared with other assembly lines... | stack_v2_sparse_classes_36k_train_024678 | 9,221 | permissive | [
{
"docstring": "Creates an instance of `SubstructureAssemblyLine`. Parameters ---------- assigned : list List of assigned tasks. Can be shared with other assembly lines. takt_time : int | float Hours required to produce one substructure. attach_time : int | float Hours required to attach a topside to the substr... | 4 | stack_v2_sparse_classes_30k_train_015643 | Implement the Python class `SubstationAssemblyLine` described below.
Class description:
Substation Assembly Line Class.
Method signatures and docstrings:
- def __init__(self, assigned, takt_time, attach_time, target, num): Creates an instance of `SubstructureAssemblyLine`. Parameters ---------- assigned : list List o... | Implement the Python class `SubstationAssemblyLine` described below.
Class description:
Substation Assembly Line Class.
Method signatures and docstrings:
- def __init__(self, assigned, takt_time, attach_time, target, num): Creates an instance of `SubstructureAssemblyLine`. Parameters ---------- assigned : list List o... | d7270ebe1c554293a9d36730d67ab555c071cb17 | <|skeleton|>
class SubstationAssemblyLine:
"""Substation Assembly Line Class."""
def __init__(self, assigned, takt_time, attach_time, target, num):
"""Creates an instance of `SubstructureAssemblyLine`. Parameters ---------- assigned : list List of assigned tasks. Can be shared with other assembly lines... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubstationAssemblyLine:
"""Substation Assembly Line Class."""
def __init__(self, assigned, takt_time, attach_time, target, num):
"""Creates an instance of `SubstructureAssemblyLine`. Parameters ---------- assigned : list List of assigned tasks. Can be shared with other assembly lines. takt_time :... | the_stack_v2_python_sparse | wisdem/orbit/phases/install/oss_install/floating.py | WISDEM/WISDEM | train | 120 |
ad4e5e6f9f09161cc32a61674e5ff59c058574e2 | [
"self.k = k\nself.heap = nums[:]\nheapq.heapify(self.heap)\nwhile len(self.heap) > self.k:\n heapq.heappop(self.heap)",
"if len(self.heap) < self.k:\n heapq.heappush(self.heap, val)\nelif self.heap[0] < val:\n heapq.heapreplace(self.heap, val)\nreturn self.heap[0]"
] | <|body_start_0|>
self.k = k
self.heap = nums[:]
heapq.heapify(self.heap)
while len(self.heap) > self.k:
heapq.heappop(self.heap)
<|end_body_0|>
<|body_start_1|>
if len(self.heap) < self.k:
heapq.heappush(self.heap, val)
elif self.heap[0] < val:
... | https://github.com/python/cpython/blob/3.7/Lib/heapq.py 使用内置结构 heapq, 其提供对基于堆的优先级队列的支持, heappushpop(L, e) O(log n) 但较分别调用 push & pop 效率高 heapreplace(L, e) O(log n) 较分别调用 pop & push 效率高 nlargest(k, iter) O(n + k log n) k 为 iter 长度 nsmallest(k, iter) O(n + k log n) k 为 iter 长度 heapify(L) 使用自底向上的堆构造算法, 时间复杂度 O(n) def pare... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
"""https://github.com/python/cpython/blob/3.7/Lib/heapq.py 使用内置结构 heapq, 其提供对基于堆的优先级队列的支持, heappushpop(L, e) O(log n) 但较分别调用 push & pop 效率高 heapreplace(L, e) O(log n) 较分别调用 pop & push 效率高 nlargest(k, iter) O(n + k log n) k 为 iter 长度 nsmallest(k, iter) O(n + k log n) k 为 iter 长度 heapif... | stack_v2_sparse_classes_36k_train_024679 | 3,578 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015349 | Implement the Python class `KthLargest` described below.
Class description:
https://github.com/python/cpython/blob/3.7/Lib/heapq.py 使用内置结构 heapq, 其提供对基于堆的优先级队列的支持, heappushpop(L, e) O(log n) 但较分别调用 push & pop 效率高 heapreplace(L, e) O(log n) 较分别调用 pop & push 效率高 nlargest(k, iter) O(n + k log n) k 为 iter 长度 nsmallest(k, ... | Implement the Python class `KthLargest` described below.
Class description:
https://github.com/python/cpython/blob/3.7/Lib/heapq.py 使用内置结构 heapq, 其提供对基于堆的优先级队列的支持, heappushpop(L, e) O(log n) 但较分别调用 push & pop 效率高 heapreplace(L, e) O(log n) 较分别调用 pop & push 效率高 nlargest(k, iter) O(n + k log n) k 为 iter 长度 nsmallest(k, ... | 2539c8e7ce7e603c960e3d8971adc472fba1dbb3 | <|skeleton|>
class KthLargest:
"""https://github.com/python/cpython/blob/3.7/Lib/heapq.py 使用内置结构 heapq, 其提供对基于堆的优先级队列的支持, heappushpop(L, e) O(log n) 但较分别调用 push & pop 效率高 heapreplace(L, e) O(log n) 较分别调用 pop & push 效率高 nlargest(k, iter) O(n + k log n) k 为 iter 长度 nsmallest(k, iter) O(n + k log n) k 为 iter 长度 heapif... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
"""https://github.com/python/cpython/blob/3.7/Lib/heapq.py 使用内置结构 heapq, 其提供对基于堆的优先级队列的支持, heappushpop(L, e) O(log n) 但较分别调用 push & pop 效率高 heapreplace(L, e) O(log n) 较分别调用 pop & push 效率高 nlargest(k, iter) O(n + k log n) k 为 iter 长度 nsmallest(k, iter) O(n + k log n) k 为 iter 长度 heapify(L) 使用自底向上的堆... | the_stack_v2_python_sparse | Heap/easy/703_kth_largest_element_in_a_stream.py | e1ijah1/LeetCode | train | 0 |
dc28b701e66aaf098b1136534a57ef08fc43b090 | [
"super(sensei, self).__init__(**kwargs)\nself.__branch = kwargs.pop('branch', 'v2.1.1')\nself.__catalyst = kwargs.pop('catalyst', '')\nself.__cmake_opts = kwargs.pop('cmake_opts', ['-DENABLE_SENSEI=ON'])\nself.__libsim = kwargs.pop('libsim', '')\nself.__miniapps = kwargs.pop('miniapps', False)\nself.__ospackages = ... | <|body_start_0|>
super(sensei, self).__init__(**kwargs)
self.__branch = kwargs.pop('branch', 'v2.1.1')
self.__catalyst = kwargs.pop('catalyst', '')
self.__cmake_opts = kwargs.pop('cmake_opts', ['-DENABLE_SENSEI=ON'])
self.__libsim = kwargs.pop('libsim', '')
self.__miniapp... | The `sensei` building block configures, builds, and installs the [SENSEI](https://sensei-insitu.org) component. The [CMake](#cmake) building block should be installed prior to this building block. In most cases, one or both of the [Catalyst](#catalyst) or [Libsim](#libsim) building blocks should be installed. If GPU re... | sensei | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sensei:
"""The `sensei` building block configures, builds, and installs the [SENSEI](https://sensei-insitu.org) component. The [CMake](#cmake) building block should be installed prior to this building block. In most cases, one or both of the [Catalyst](#catalyst) or [Libsim](#libsim) building blo... | stack_v2_sparse_classes_36k_train_024680 | 6,256 | permissive | [
{
"docstring": "Initialize building block",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Setup cmake options based on users parameters",
"name": "__cmake",
"signature": "def __cmake(self)"
},
{
"docstring": "Generate the set of instructions t... | 3 | null | Implement the Python class `sensei` described below.
Class description:
The `sensei` building block configures, builds, and installs the [SENSEI](https://sensei-insitu.org) component. The [CMake](#cmake) building block should be installed prior to this building block. In most cases, one or both of the [Catalyst](#cata... | Implement the Python class `sensei` described below.
Class description:
The `sensei` building block configures, builds, and installs the [SENSEI](https://sensei-insitu.org) component. The [CMake](#cmake) building block should be installed prior to this building block. In most cases, one or both of the [Catalyst](#cata... | 60fd2a51c171258a6b3f93c2523101cb7018ba1b | <|skeleton|>
class sensei:
"""The `sensei` building block configures, builds, and installs the [SENSEI](https://sensei-insitu.org) component. The [CMake](#cmake) building block should be installed prior to this building block. In most cases, one or both of the [Catalyst](#catalyst) or [Libsim](#libsim) building blo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class sensei:
"""The `sensei` building block configures, builds, and installs the [SENSEI](https://sensei-insitu.org) component. The [CMake](#cmake) building block should be installed prior to this building block. In most cases, one or both of the [Catalyst](#catalyst) or [Libsim](#libsim) building blocks should be... | the_stack_v2_python_sparse | hpccm/building_blocks/sensei.py | NVIDIA/hpc-container-maker | train | 419 |
a8fc1baf24d2e757b9fa77bc2a4630e897be0027 | [
"def dfs(root, temp_str=''):\n if root is None:\n temp_str += 'None,'\n else:\n temp_str += str(root.val) + ','\n temp_str = dfs(root.left, temp_str)\n temp_str = dfs(root.right, temp_str)\n return temp_str\nreturn dfs(root)",
"def rdeserialize(l):\n \"\"\" a recursive help... | <|body_start_0|>
def dfs(root, temp_str=''):
if root is None:
temp_str += 'None,'
else:
temp_str += str(root.val) + ','
temp_str = dfs(root.left, temp_str)
temp_str = dfs(root.right, temp_str)
return temp_str
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_024681 | 2,666 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 7965e8232d604edb40871cf46520b168a8be2834 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def dfs(root, temp_str=''):
if root is None:
temp_str += 'None,'
else:
temp_str += str(root.val) + ','
temp_str = ... | the_stack_v2_python_sparse | leetcode/hard/297_Serialize_and_Deserialize_Binary_Tree.py | ambarish710/python_concepts | train | 0 | |
11f0321734533b80e436ddf4c66e86a5f3869ec7 | [
"print()\nprint('-+- ' * 40)\nlog.debug('ROUTE class : %s', self.__class__.__name__)\nuser_email = get_jwt_identity()\nlog.info(\"...'{}' is renewing its password...\".format(user_email))\nsent_token = get_raw_jwt()\nlog.debug('sent_token : \\n %s', pformat(sent_token))\nuser = mongo_users.find_one({'infos.email': ... | <|body_start_0|>
print()
print('-+- ' * 40)
log.debug('ROUTE class : %s', self.__class__.__name__)
user_email = get_jwt_identity()
log.info("...'{}' is renewing its password...".format(user_email))
sent_token = get_raw_jwt()
log.debug('sent_token : \n %s', pformat... | ResetPassword | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetPassword:
def get(self):
"""Open a link (GET) to allow the user to reset its password > --- needs : a valid fresh renew_pwd_access_token (f.e. received by email, with a short expiration date) >>> returns : msg, a new reset_pwd_access_token"""
<|body_0|>
def post(self):
... | stack_v2_sparse_classes_36k_train_024682 | 7,869 | permissive | [
{
"docstring": "Open a link (GET) to allow the user to reset its password > --- needs : a valid fresh renew_pwd_access_token (f.e. received by email, with a short expiration date) >>> returns : msg, a new reset_pwd_access_token",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Upd... | 2 | null | Implement the Python class `ResetPassword` described below.
Class description:
Implement the ResetPassword class.
Method signatures and docstrings:
- def get(self): Open a link (GET) to allow the user to reset its password > --- needs : a valid fresh renew_pwd_access_token (f.e. received by email, with a short expira... | Implement the Python class `ResetPassword` described below.
Class description:
Implement the ResetPassword class.
Method signatures and docstrings:
- def get(self): Open a link (GET) to allow the user to reset its password > --- needs : a valid fresh renew_pwd_access_token (f.e. received by email, with a short expira... | 08ba9151069f2f633461f5166b1954fdeac7854a | <|skeleton|>
class ResetPassword:
def get(self):
"""Open a link (GET) to allow the user to reset its password > --- needs : a valid fresh renew_pwd_access_token (f.e. received by email, with a short expiration date) >>> returns : msg, a new reset_pwd_access_token"""
<|body_0|>
def post(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResetPassword:
def get(self):
"""Open a link (GET) to allow the user to reset its password > --- needs : a valid fresh renew_pwd_access_token (f.e. received by email, with a short expiration date) >>> returns : msg, a new reset_pwd_access_token"""
print()
print('-+- ' * 40)
log... | the_stack_v2_python_sparse | solidata_api/api/api_auth/endpoint_user_password.py | entrepreneur-interet-general/solidata_backend | train | 9 | |
0586967e90cb734d840a8c89f86cc74603c0013d | [
"parser.add_argument('--network-project', help=' The project owning the subnetworks returned. This field is translated\\n into the expression `networkProjectId=[PROJECT_ID]` and ANDed to\\n the `--filter` flag value.\\n\\n Defaults to the *--project* value.\\n')\ndisplay_format = 'table(... | <|body_start_0|>
parser.add_argument('--network-project', help=' The project owning the subnetworks returned. This field is translated\n into the expression `networkProjectId=[PROJECT_ID]` and ANDed to\n the `--filter` flag value.\n\n Defaults to the *--project* value.\n')
di... | List subnets usable for cluster creation in a specific project. Usability of subnetworks for cluster creation is dependent on the IAM policy of the project's Google Kubernetes Engine Service Account. Use the `--project` flag to evaluate subnet usability in different projects. This list may differ from the list returned... | ListUsable | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListUsable:
"""List subnets usable for cluster creation in a specific project. Usability of subnetworks for cluster creation is dependent on the IAM policy of the project's Google Kubernetes Engine Service Account. Use the `--project` flag to evaluate subnet usability in different projects. This ... | stack_v2_sparse_classes_36k_train_024683 | 4,850 | permissive | [
{
"docstring": "Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the... | 2 | null | Implement the Python class `ListUsable` described below.
Class description:
List subnets usable for cluster creation in a specific project. Usability of subnetworks for cluster creation is dependent on the IAM policy of the project's Google Kubernetes Engine Service Account. Use the `--project` flag to evaluate subnet... | Implement the Python class `ListUsable` described below.
Class description:
List subnets usable for cluster creation in a specific project. Usability of subnetworks for cluster creation is dependent on the IAM policy of the project's Google Kubernetes Engine Service Account. Use the `--project` flag to evaluate subnet... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class ListUsable:
"""List subnets usable for cluster creation in a specific project. Usability of subnetworks for cluster creation is dependent on the IAM policy of the project's Google Kubernetes Engine Service Account. Use the `--project` flag to evaluate subnet usability in different projects. This ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListUsable:
"""List subnets usable for cluster creation in a specific project. Usability of subnetworks for cluster creation is dependent on the IAM policy of the project's Google Kubernetes Engine Service Account. Use the `--project` flag to evaluate subnet usability in different projects. This list may diff... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/container/subnets/list_usable.py | bopopescu/socialliteapp | train | 0 |
746638f87eb30cc5239e458a67dd3eeee3c69083 | [
"missing_fields = [field for field in fields if getattr(object_to_check, field) is None]\nif len(missing_fields) > 0:\n raise ValueError(f'The fields {str(missing_fields)} on the {object_to_check.__class__.__name__} are set to None, please ensure that you have provided them directly, via a secrets file or enviro... | <|body_start_0|>
missing_fields = [field for field in fields if getattr(object_to_check, field) is None]
if len(missing_fields) > 0:
raise ValueError(f'The fields {str(missing_fields)} on the {object_to_check.__class__.__name__} are set to None, please ensure that you have provided them dire... | The ApiClientBuilder is responsible for building a lusid.ApiClient. This includes obtaining an access token from Okta or using the provided token. Any validation on the inputs required to build a lusid.ApiClient is the responsibility of this ApiClientBuilder. | ApiClientBuilder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiClientBuilder:
"""The ApiClientBuilder is responsible for building a lusid.ApiClient. This includes obtaining an access token from Okta or using the provided token. Any validation on the inputs required to build a lusid.ApiClient is the responsibility of this ApiClientBuilder."""
def __ch... | stack_v2_sparse_classes_36k_train_024684 | 6,434 | permissive | [
{
"docstring": "This function checks that the provided fields on an object are populated with values other than None :param object_to_check: The object to check the fields (a.k.a attributes) of :param list[str] fields: The fields to check on the object :return: None",
"name": "__check_required_fields",
... | 3 | null | Implement the Python class `ApiClientBuilder` described below.
Class description:
The ApiClientBuilder is responsible for building a lusid.ApiClient. This includes obtaining an access token from Okta or using the provided token. Any validation on the inputs required to build a lusid.ApiClient is the responsibility of ... | Implement the Python class `ApiClientBuilder` described below.
Class description:
The ApiClientBuilder is responsible for building a lusid.ApiClient. This includes obtaining an access token from Okta or using the provided token. Any validation on the inputs required to build a lusid.ApiClient is the responsibility of ... | 32fedc00ce5a37a6fe3bd9b9962570a8a9348e48 | <|skeleton|>
class ApiClientBuilder:
"""The ApiClientBuilder is responsible for building a lusid.ApiClient. This includes obtaining an access token from Okta or using the provided token. Any validation on the inputs required to build a lusid.ApiClient is the responsibility of this ApiClientBuilder."""
def __ch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApiClientBuilder:
"""The ApiClientBuilder is responsible for building a lusid.ApiClient. This includes obtaining an access token from Okta or using the provided token. Any validation on the inputs required to build a lusid.ApiClient is the responsibility of this ApiClientBuilder."""
def __check_required_... | the_stack_v2_python_sparse | sdk/lusid/utilities/api_client_builder.py | finbourne/lusid-sdk-python | train | 11 |
c0a84d248aba6460574fb7b491e6624406a26b81 | [
"cmd = 'cp ' + test_tif_file + ' /var/tmp/'\nos.system(cmd)\npayload = {'uuid': test_export_cm_layer_uuid, 'type': 'raster'}\nexpected_status = 200\noutput = requests.post(url, json=payload)\nassert output.status_code == expected_status\ncmd = 'rm /var/tmp/' + test_export_cm_layer_uuid + '.tif'\nos.system(cmd)",
... | <|body_start_0|>
cmd = 'cp ' + test_tif_file + ' /var/tmp/'
os.system(cmd)
payload = {'uuid': test_export_cm_layer_uuid, 'type': 'raster'}
expected_status = 200
output = requests.post(url, json=payload)
assert output.status_code == expected_status
cmd = 'rm /var/t... | TestExportCMLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestExportCMLayer:
def test_post(self):
"""this test will pass the upload/export/cmLayer method"""
<|body_0|>
def test_port_wrong_parameters(self):
"""this test will fail because the wrong parameters are given"""
<|body_1|>
def test_post_wrong_layer(self... | stack_v2_sparse_classes_36k_train_024685 | 1,487 | permissive | [
{
"docstring": "this test will pass the upload/export/cmLayer method",
"name": "test_post",
"signature": "def test_post(self)"
},
{
"docstring": "this test will fail because the wrong parameters are given",
"name": "test_port_wrong_parameters",
"signature": "def test_port_wrong_parameter... | 3 | stack_v2_sparse_classes_30k_train_006019 | Implement the Python class `TestExportCMLayer` described below.
Class description:
Implement the TestExportCMLayer class.
Method signatures and docstrings:
- def test_post(self): this test will pass the upload/export/cmLayer method
- def test_port_wrong_parameters(self): this test will fail because the wrong paramete... | Implement the Python class `TestExportCMLayer` described below.
Class description:
Implement the TestExportCMLayer class.
Method signatures and docstrings:
- def test_post(self): this test will pass the upload/export/cmLayer method
- def test_port_wrong_parameters(self): this test will fail because the wrong paramete... | ba1e287dbc63e34bf9feb80b65b02c1db93ce91c | <|skeleton|>
class TestExportCMLayer:
def test_post(self):
"""this test will pass the upload/export/cmLayer method"""
<|body_0|>
def test_port_wrong_parameters(self):
"""this test will fail because the wrong parameters are given"""
<|body_1|>
def test_post_wrong_layer(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestExportCMLayer:
def test_post(self):
"""this test will pass the upload/export/cmLayer method"""
cmd = 'cp ' + test_tif_file + ' /var/tmp/'
os.system(cmd)
payload = {'uuid': test_export_cm_layer_uuid, 'type': 'raster'}
expected_status = 200
output = requests.p... | the_stack_v2_python_sparse | pytest_suit/routes/uploads/test_exportCMLayer.py | HotMaps/Hotmaps-toolbox-service | train | 4 | |
23bc0ca01e64c290b8674090e87202de9702dcb1 | [
"self.getProp('coordSpace').setDefault('torig', self)\nself.coordSpace = 'torig'\nvertFiles = [overlay.dataSource] + fslfs.relatedGeometryFiles(overlay.dataSource)\nvdataFiles = [None] + fslfs.relatedVertexDataFiles(overlay.dataSource)\nself.getProp('vertexSet').setChoices(vertFiles, instance=self)\nself.getProp('v... | <|body_start_0|>
self.getProp('coordSpace').setDefault('torig', self)
self.coordSpace = 'torig'
vertFiles = [overlay.dataSource] + fslfs.relatedGeometryFiles(overlay.dataSource)
vdataFiles = [None] + fslfs.relatedVertexDataFiles(overlay.dataSource)
self.getProp('vertexSet').setCh... | The :class:`FreesurferOpts` class, which contains settings for displaying a :class:`.FreesurferMesh` overlay. Freesurfer surface vertices are defined in a coordinate system which differs from the world coordinate system of the source image. This class customises some behaviour of the :class:`.MeshOpts` class so that th... | FreesurferOpts | [
"BSD-3-Clause",
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FreesurferOpts:
"""The :class:`FreesurferOpts` class, which contains settings for displaying a :class:`.FreesurferMesh` overlay. Freesurfer surface vertices are defined in a coordinate system which differs from the world coordinate system of the source image. This class customises some behaviour ... | stack_v2_sparse_classes_36k_train_024686 | 3,185 | permissive | [
{
"docstring": "Create a ``FreesurferOpts`` instance. All arguments are passed to the :class:`.MeshOpts` constructor.",
"name": "__init__",
"signature": "def __init__(self, overlay, *args, **kwargs)"
},
{
"docstring": "Overrides :meth:`.MeshOpts.getTransform`. If the :attr:`.MeshOpts.coordSpace`... | 3 | null | Implement the Python class `FreesurferOpts` described below.
Class description:
The :class:`FreesurferOpts` class, which contains settings for displaying a :class:`.FreesurferMesh` overlay. Freesurfer surface vertices are defined in a coordinate system which differs from the world coordinate system of the source image... | Implement the Python class `FreesurferOpts` described below.
Class description:
The :class:`FreesurferOpts` class, which contains settings for displaying a :class:`.FreesurferMesh` overlay. Freesurfer surface vertices are defined in a coordinate system which differs from the world coordinate system of the source image... | 46ccb4fe2b2346eb57576247f49714032b61307a | <|skeleton|>
class FreesurferOpts:
"""The :class:`FreesurferOpts` class, which contains settings for displaying a :class:`.FreesurferMesh` overlay. Freesurfer surface vertices are defined in a coordinate system which differs from the world coordinate system of the source image. This class customises some behaviour ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FreesurferOpts:
"""The :class:`FreesurferOpts` class, which contains settings for displaying a :class:`.FreesurferMesh` overlay. Freesurfer surface vertices are defined in a coordinate system which differs from the world coordinate system of the source image. This class customises some behaviour of the :class... | the_stack_v2_python_sparse | fsleyes/displaycontext/freesurferopts.py | sanjayankur31/fsleyes | train | 1 |
3e08e3929994d565f7766d1b9bbe5ec7b38bc323 | [
"token = ICalToken.objects.get_or_create(user=request.user)[0]\npath = request.get_full_path()\ndata = {'result': {'calendars': [{'name': 'events', 'description': 'Calendar with all events on Abakus.no.', 'path': f'{path}events/'}, {'name': 'personal', 'description': 'Calendar with your favorite events & meetings.'... | <|body_start_0|>
token = ICalToken.objects.get_or_create(user=request.user)[0]
path = request.get_full_path()
data = {'result': {'calendars': [{'name': 'events', 'description': 'Calendar with all events on Abakus.no.', 'path': f'{path}events/'}, {'name': 'personal', 'description': 'Calendar with... | API Endpoint to get ICalendar files for different kinds of events and meetings. usage: [events/?token=yourtoken](events/?token=yourtoken) | ICalViewset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ICalViewset:
"""API Endpoint to get ICalendar files for different kinds of events and meetings. usage: [events/?token=yourtoken](events/?token=yourtoken)"""
def list(self, request):
"""List all the different icals."""
<|body_0|>
def personal(self, request):
"""Pe... | stack_v2_sparse_classes_36k_train_024687 | 6,167 | permissive | [
{
"docstring": "List all the different icals.",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Personal ical route.",
"name": "personal",
"signature": "def personal(self, request)"
},
{
"docstring": "Registration ical route.",
"name": "registrations... | 4 | null | Implement the Python class `ICalViewset` described below.
Class description:
API Endpoint to get ICalendar files for different kinds of events and meetings. usage: [events/?token=yourtoken](events/?token=yourtoken)
Method signatures and docstrings:
- def list(self, request): List all the different icals.
- def person... | Implement the Python class `ICalViewset` described below.
Class description:
API Endpoint to get ICalendar files for different kinds of events and meetings. usage: [events/?token=yourtoken](events/?token=yourtoken)
Method signatures and docstrings:
- def list(self, request): List all the different icals.
- def person... | 2c1909fd84fe3b3e0a9d3792c4bcc51089ad5a87 | <|skeleton|>
class ICalViewset:
"""API Endpoint to get ICalendar files for different kinds of events and meetings. usage: [events/?token=yourtoken](events/?token=yourtoken)"""
def list(self, request):
"""List all the different icals."""
<|body_0|>
def personal(self, request):
"""Pe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ICalViewset:
"""API Endpoint to get ICalendar files for different kinds of events and meetings. usage: [events/?token=yourtoken](events/?token=yourtoken)"""
def list(self, request):
"""List all the different icals."""
token = ICalToken.objects.get_or_create(user=request.user)[0]
p... | the_stack_v2_python_sparse | lego/apps/ical/viewsets.py | webkom/lego | train | 53 |
038390badd9017767bbab6e168fdcfd4446050af | [
"mpl_style = MatplotlibStyle(curve.style)\nx = curve.xs\ny = curve.ys\n[line] = axes.plot(x, y, mpl_style.line_color, linewidth=mpl_style.line_width, linestyle=mpl_style.line_style)\nif mpl_style.fill_color or mpl_style.fill_pattern:\n [line] = plt.fill(x, y, mpl_style.fill_color, edgecolor=mpl_style.line_color,... | <|body_start_0|>
mpl_style = MatplotlibStyle(curve.style)
x = curve.xs
y = curve.ys
[line] = axes.plot(x, y, mpl_style.line_color, linewidth=mpl_style.line_width, linestyle=mpl_style.line_style)
if mpl_style.fill_color or mpl_style.fill_pattern:
[line] = plt.fill(x, y... | MatplotlibCurve | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatplotlibCurve:
def plot(self, curve: ps.Curve, axes: plt.Axes) -> None:
"""Draw a curve with coordinates x and y (arrays)."""
<|body_0|>
def _plot_arrow(self, x, y, dx, dy, style: Style, axes: plt.Axes):
"""Draw arrow (dx,dy) at (x,y). `style` is '->', '<-' or '<->... | stack_v2_sparse_classes_36k_train_024688 | 3,750 | permissive | [
{
"docstring": "Draw a curve with coordinates x and y (arrays).",
"name": "plot",
"signature": "def plot(self, curve: ps.Curve, axes: plt.Axes) -> None"
},
{
"docstring": "Draw arrow (dx,dy) at (x,y). `style` is '->', '<-' or '<->'.",
"name": "_plot_arrow",
"signature": "def _plot_arrow(... | 2 | stack_v2_sparse_classes_30k_train_001834 | Implement the Python class `MatplotlibCurve` described below.
Class description:
Implement the MatplotlibCurve class.
Method signatures and docstrings:
- def plot(self, curve: ps.Curve, axes: plt.Axes) -> None: Draw a curve with coordinates x and y (arrays).
- def _plot_arrow(self, x, y, dx, dy, style: Style, axes: p... | Implement the Python class `MatplotlibCurve` described below.
Class description:
Implement the MatplotlibCurve class.
Method signatures and docstrings:
- def plot(self, curve: ps.Curve, axes: plt.Axes) -> None: Draw a curve with coordinates x and y (arrays).
- def _plot_arrow(self, x, y, dx, dy, style: Style, axes: p... | 13d64b9abb0b5fc78eeb62aaa11bf378f9225a09 | <|skeleton|>
class MatplotlibCurve:
def plot(self, curve: ps.Curve, axes: plt.Axes) -> None:
"""Draw a curve with coordinates x and y (arrays)."""
<|body_0|>
def _plot_arrow(self, x, y, dx, dy, style: Style, axes: plt.Axes):
"""Draw arrow (dx,dy) at (x,y). `style` is '->', '<-' or '<->... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MatplotlibCurve:
def plot(self, curve: ps.Curve, axes: plt.Axes) -> None:
"""Draw a curve with coordinates x and y (arrays)."""
mpl_style = MatplotlibStyle(curve.style)
x = curve.xs
y = curve.ys
[line] = axes.plot(x, y, mpl_style.line_color, linewidth=mpl_style.line_wid... | the_stack_v2_python_sparse | pysketcher/backend/matplotlib/_matplotlib_curve.py | ffernandoalves/pysketcher | train | 0 | |
ef7dca91aee565f74bda816faac028eb4f4feab4 | [
"if head == None:\n return None\ndic = {}\ndummy = head\nwhile dummy != None:\n dic[dummy] = RandomListNode(dummy.label)\n dummy = dummy.next\ndummy = head\nwhile dummy != None:\n dic[dummy].next = dic.get(dummy.next)\n dic[dummy].random = dic.get(dummy.random)\n dummy = dummy.next\nreturn dic.get... | <|body_start_0|>
if head == None:
return None
dic = {}
dummy = head
while dummy != None:
dic[dummy] = RandomListNode(dummy.label)
dummy = dummy.next
dummy = head
while dummy != None:
dic[dummy].next = dic.get(dummy.next)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def copyRandomList(self, head):
""":type head: RandomListNode :rtype: RandomListNode"""
<|body_0|>
def copyRandomList(self, head):
""":type head: RandomListNode :rtype: RandomListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if head... | stack_v2_sparse_classes_36k_train_024689 | 1,676 | no_license | [
{
"docstring": ":type head: RandomListNode :rtype: RandomListNode",
"name": "copyRandomList",
"signature": "def copyRandomList(self, head)"
},
{
"docstring": ":type head: RandomListNode :rtype: RandomListNode",
"name": "copyRandomList",
"signature": "def copyRandomList(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020284 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def copyRandomList(self, head): :type head: RandomListNode :rtype: RandomListNode
- def copyRandomList(self, head): :type head: RandomListNode :rtype: RandomListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def copyRandomList(self, head): :type head: RandomListNode :rtype: RandomListNode
- def copyRandomList(self, head): :type head: RandomListNode :rtype: RandomListNode
<|skeleton|... | 10798e5b9c33c3f177594ea17cf0398fc117f0a1 | <|skeleton|>
class Solution:
def copyRandomList(self, head):
""":type head: RandomListNode :rtype: RandomListNode"""
<|body_0|>
def copyRandomList(self, head):
""":type head: RandomListNode :rtype: RandomListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def copyRandomList(self, head):
""":type head: RandomListNode :rtype: RandomListNode"""
if head == None:
return None
dic = {}
dummy = head
while dummy != None:
dic[dummy] = RandomListNode(dummy.label)
dummy = dummy.next
... | the_stack_v2_python_sparse | copy-list-with-random-node/copyListWithRandomNode.py | NanXiangPU/leetcode | train | 0 | |
32c298e5ded2679b9a1fdd8818cffd275b4c9e2d | [
"sport = kwargs['sport']\nif sport in VALID_SPORTS:\n return super().dispatch(request, *args, **kwargs)\nelse:\n raise Http404()",
"sport = self.kwargs['sport']\nq = Player.objects.filter(sport=sport, is_available=True)\nreturn q"
] | <|body_start_0|>
sport = kwargs['sport']
if sport in VALID_SPORTS:
return super().dispatch(request, *args, **kwargs)
else:
raise Http404()
<|end_body_0|>
<|body_start_1|>
sport = self.kwargs['sport']
q = Player.objects.filter(sport=sport, is_available=Tru... | PlayerListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayerListView:
def dispatch(self, request, *args, **kwargs):
"""Return 404 if sport is not supported."""
<|body_0|>
def get_queryset(self):
"""Return a list of available players for the sport in question."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_024690 | 10,305 | no_license | [
{
"docstring": "Return 404 if sport is not supported.",
"name": "dispatch",
"signature": "def dispatch(self, request, *args, **kwargs)"
},
{
"docstring": "Return a list of available players for the sport in question.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013120 | Implement the Python class `PlayerListView` described below.
Class description:
Implement the PlayerListView class.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Return 404 if sport is not supported.
- def get_queryset(self): Return a list of available players for the sport in ques... | Implement the Python class `PlayerListView` described below.
Class description:
Implement the PlayerListView class.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Return 404 if sport is not supported.
- def get_queryset(self): Return a list of available players for the sport in ques... | e85b251f04a1b3c0b722c79eed7706803e5c461a | <|skeleton|>
class PlayerListView:
def dispatch(self, request, *args, **kwargs):
"""Return 404 if sport is not supported."""
<|body_0|>
def get_queryset(self):
"""Return a list of available players for the sport in question."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlayerListView:
def dispatch(self, request, *args, **kwargs):
"""Return 404 if sport is not supported."""
sport = kwargs['sport']
if sport in VALID_SPORTS:
return super().dispatch(request, *args, **kwargs)
else:
raise Http404()
def get_queryset(self... | the_stack_v2_python_sparse | hittalaget/players/views.py | joakimekman/hittalaget | train | 0 | |
9aaf978ec754c2c6b80211935fafbe0723deeb84 | [
"if not root:\n return '#@'\nres = str(root.val) + '@'\nreturn res + self.serialize(root.left) + self.serialize(root.right)",
"nodes = data.split('@')\n\ndef helper(l: List[str]):\n if not nodes:\n return None\n if l[0] == '#':\n l.pop(0)\n return None\n cur = TreeNode(int(l[0]))\... | <|body_start_0|>
if not root:
return '#@'
res = str(root.val) + '@'
return res + self.serialize(root.left) + self.serialize(root.right)
<|end_body_0|>
<|body_start_1|>
nodes = data.split('@')
def helper(l: List[str]):
if not nodes:
return... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_024691 | 1,360 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 1233137cfb1196019e8d95407c2b8f18b6d6d2f8 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '#@'
res = str(root.val) + '@'
return res + self.serialize(root.left) + self.serialize(root.right)
def deserialize(self, data):
... | the_stack_v2_python_sparse | 297.二叉树的序列化与反序列化.py | ChaosNyaruko/leetcode_cn | train | 0 | |
571d48ad9b6e3b54a1d1c0b0f2dcef5252f92ca9 | [
"from collections import Counter\nmapping = Counter(answers)\nret = 0\nfor idx, val in mapping.items():\n ret += val if val % (idx + 1) == 0 else (val // (idx + 1) + 1) * (idx + 1)\nreturn ret",
"from collections import Counter\ndic = Counter(answers)\nreturn sum([math.ceil(dic[i] / (i + 1)) * (i + 1) for i in... | <|body_start_0|>
from collections import Counter
mapping = Counter(answers)
ret = 0
for idx, val in mapping.items():
ret += val if val % (idx + 1) == 0 else (val // (idx + 1) + 1) * (idx + 1)
return ret
<|end_body_0|>
<|body_start_1|>
from collections import ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numRabbits(self, answers):
""":type answers: List[int] :rtype: int"""
<|body_0|>
def numRabbits(self, answers):
""":type answers: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from collections import Counter
... | stack_v2_sparse_classes_36k_train_024692 | 1,697 | no_license | [
{
"docstring": ":type answers: List[int] :rtype: int",
"name": "numRabbits",
"signature": "def numRabbits(self, answers)"
},
{
"docstring": ":type answers: List[int] :rtype: int",
"name": "numRabbits",
"signature": "def numRabbits(self, answers)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numRabbits(self, answers): :type answers: List[int] :rtype: int
- def numRabbits(self, answers): :type answers: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numRabbits(self, answers): :type answers: List[int] :rtype: int
- def numRabbits(self, answers): :type answers: List[int] :rtype: int
<|skeleton|>
class Solution:
def n... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def numRabbits(self, answers):
""":type answers: List[int] :rtype: int"""
<|body_0|>
def numRabbits(self, answers):
""":type answers: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numRabbits(self, answers):
""":type answers: List[int] :rtype: int"""
from collections import Counter
mapping = Counter(answers)
ret = 0
for idx, val in mapping.items():
ret += val if val % (idx + 1) == 0 else (val // (idx + 1) + 1) * (idx + 1)... | the_stack_v2_python_sparse | code/781#Rabbits in Forest.py | EachenKuang/LeetCode | train | 28 | |
91257403a677e0b43a69877e47486942f19b07c4 | [
"self._buf = record\nself.mandatory_header = _unpack_from_buf(self._buf, 0, UF_MANDATORY_HEADER)\nself.optional_header = None\nif self.mandatory_header['offset_optional_header'] != 0:\n offset = (self.mandatory_header['offset_optional_header'] - 1) * 2\n self.optional_header = _unpack_from_buf(self._buf, offs... | <|body_start_0|>
self._buf = record
self.mandatory_header = _unpack_from_buf(self._buf, 0, UF_MANDATORY_HEADER)
self.optional_header = None
if self.mandatory_header['offset_optional_header'] != 0:
offset = (self.mandatory_header['offset_optional_header'] - 1) * 2
... | A class for reading data from a single ray (record) in a UF file. Parameters ---------- record : str Byte string containing the binary data for a UF ray. Attributes ---------- mandatory_header : dic Mandatory header. optional_header : dic or None Optional header or None if no optional header exists in the record. data_... | UFRay | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UFRay:
"""A class for reading data from a single ray (record) in a UF file. Parameters ---------- record : str Byte string containing the binary data for a UF ray. Attributes ---------- mandatory_header : dic Mandatory header. optional_header : dic or None Optional header or None if no optional h... | stack_v2_sparse_classes_36k_train_024693 | 19,352 | permissive | [
{
"docstring": "Initalize the object.",
"name": "__init__",
"signature": "def __init__(self, record)"
},
{
"docstring": "Return array of raw data for a particular field in the ray. Field header is appended to the list in the field_headers attribute.",
"name": "get_field_data",
"signature... | 4 | null | Implement the Python class `UFRay` described below.
Class description:
A class for reading data from a single ray (record) in a UF file. Parameters ---------- record : str Byte string containing the binary data for a UF ray. Attributes ---------- mandatory_header : dic Mandatory header. optional_header : dic or None O... | Implement the Python class `UFRay` described below.
Class description:
A class for reading data from a single ray (record) in a UF file. Parameters ---------- record : str Byte string containing the binary data for a UF ray. Attributes ---------- mandatory_header : dic Mandatory header. optional_header : dic or None O... | 172bbcf1cf3bcdb953c76ebae72c27c95dc2e606 | <|skeleton|>
class UFRay:
"""A class for reading data from a single ray (record) in a UF file. Parameters ---------- record : str Byte string containing the binary data for a UF ray. Attributes ---------- mandatory_header : dic Mandatory header. optional_header : dic or None Optional header or None if no optional h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UFRay:
"""A class for reading data from a single ray (record) in a UF file. Parameters ---------- record : str Byte string containing the binary data for a UF ray. Attributes ---------- mandatory_header : dic Mandatory header. optional_header : dic or None Optional header or None if no optional header exists ... | the_stack_v2_python_sparse | pyart/io/uffile.py | ARM-DOE/pyart | train | 455 |
05887a895e44078942e2495e3c1e38435ea68d7d | [
"if value:\n try:\n value = Migration.objects.get(uid=value)\n except Migration.DoesNotExist:\n message = 'Failed to get the parent migration'\n logger.exception(message)\n raise serializers.ValidationError(message)\nreturn value",
"pre_deploy_steps = validated_data.pop('pre_depl... | <|body_start_0|>
if value:
try:
value = Migration.objects.get(uid=value)
except Migration.DoesNotExist:
message = 'Failed to get the parent migration'
logger.exception(message)
raise serializers.ValidationError(message)
... | Migration serializer. | MigrationSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MigrationSerializer:
"""Migration serializer."""
def validate_parent(self, value):
"""Validate parent field."""
<|body_0|>
def create(self, validated_data):
"""Create or update the instance due to unique key on case."""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_024694 | 15,874 | permissive | [
{
"docstring": "Validate parent field.",
"name": "validate_parent",
"signature": "def validate_parent(self, value)"
},
{
"docstring": "Create or update the instance due to unique key on case.",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012371 | Implement the Python class `MigrationSerializer` described below.
Class description:
Migration serializer.
Method signatures and docstrings:
- def validate_parent(self, value): Validate parent field.
- def create(self, validated_data): Create or update the instance due to unique key on case. | Implement the Python class `MigrationSerializer` described below.
Class description:
Migration serializer.
Method signatures and docstrings:
- def validate_parent(self, value): Validate parent field.
- def create(self, validated_data): Create or update the instance due to unique key on case.
<|skeleton|>
class Migra... | 5c32aab78e48b5249fd458d9c837596a75698968 | <|skeleton|>
class MigrationSerializer:
"""Migration serializer."""
def validate_parent(self, value):
"""Validate parent field."""
<|body_0|>
def create(self, validated_data):
"""Create or update the instance due to unique key on case."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MigrationSerializer:
"""Migration serializer."""
def validate_parent(self, value):
"""Validate parent field."""
if value:
try:
value = Migration.objects.get(uid=value)
except Migration.DoesNotExist:
message = 'Failed to get the paren... | the_stack_v2_python_sparse | pdt/api/serializers.py | AbdulRahmanAlHamali/pdt | train | 0 |
69f20c1bd252d23204a55c3cfae2d780b8588aaa | [
"self.name = scenario.name\nself.num_vehicles = env.vehicles.num_vehicles\nself.env = env\nself.vehicles = scenario.vehicles\nself.cfg = scenario.cfg\nlogging.info(' Starting experiment' + str(self.name) + ' at ' + str(datetime.datetime.utcnow()))\nlogging.info('initializing environment.')",
"if rl_actions is Non... | <|body_start_0|>
self.name = scenario.name
self.num_vehicles = env.vehicles.num_vehicles
self.env = env
self.vehicles = scenario.vehicles
self.cfg = scenario.cfg
logging.info(' Starting experiment' + str(self.name) + ' at ' + str(datetime.datetime.utcnow()))
loggi... | SumoExperiment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SumoExperiment:
def __init__(self, env, scenario):
"""This class acts as a runner for a scenario and environment. Attributes ---------- env: Environment type the environment object the simulator will run scenario: Scenario type the scenario object the simulator will run"""
<|body... | stack_v2_sparse_classes_36k_train_024695 | 1,588 | permissive | [
{
"docstring": "This class acts as a runner for a scenario and environment. Attributes ---------- env: Environment type the environment object the simulator will run scenario: Scenario type the scenario object the simulator will run",
"name": "__init__",
"signature": "def __init__(self, env, scenario)"
... | 2 | stack_v2_sparse_classes_30k_train_017088 | Implement the Python class `SumoExperiment` described below.
Class description:
Implement the SumoExperiment class.
Method signatures and docstrings:
- def __init__(self, env, scenario): This class acts as a runner for a scenario and environment. Attributes ---------- env: Environment type the environment object the ... | Implement the Python class `SumoExperiment` described below.
Class description:
Implement the SumoExperiment class.
Method signatures and docstrings:
- def __init__(self, env, scenario): This class acts as a runner for a scenario and environment. Attributes ---------- env: Environment type the environment object the ... | f3f6d7e9c64f6b641a464a716c7f38ca00388805 | <|skeleton|>
class SumoExperiment:
def __init__(self, env, scenario):
"""This class acts as a runner for a scenario and environment. Attributes ---------- env: Environment type the environment object the simulator will run scenario: Scenario type the scenario object the simulator will run"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SumoExperiment:
def __init__(self, env, scenario):
"""This class acts as a runner for a scenario and environment. Attributes ---------- env: Environment type the environment object the simulator will run scenario: Scenario type the scenario object the simulator will run"""
self.name = scenario... | the_stack_v2_python_sparse | flow/core/experiment.py | mark-koren/flow | train | 0 | |
354b66be0bbce27f4b4d1003731c28a14b30ffd6 | [
"base_pkgs = FL_PACKAGES\nmodule_names = FL_MODULES\nadmin_config_file_path = workspace.get_admin_startup_file_path()\nJsonConfigurator.__init__(self, config_file_name=admin_config_file_path, base_pkgs=base_pkgs, module_names=module_names, exclude_libs=True)\nself.workspace = workspace\nself.admin_config_file_path ... | <|body_start_0|>
base_pkgs = FL_PACKAGES
module_names = FL_MODULES
admin_config_file_path = workspace.get_admin_startup_file_path()
JsonConfigurator.__init__(self, config_file_name=admin_config_file_path, base_pkgs=base_pkgs, module_names=module_names, exclude_libs=True)
self.wor... | FL Admin Client startup configurator. | FLAdminClientStarterConfigurator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FLAdminClientStarterConfigurator:
"""FL Admin Client startup configurator."""
def __init__(self, workspace: Workspace):
"""Uses the json configuration to start the FL admin client. Args: workspace: the workspace object"""
<|body_0|>
def process_config_element(self, confi... | stack_v2_sparse_classes_36k_train_024696 | 17,853 | permissive | [
{
"docstring": "Uses the json configuration to start the FL admin client. Args: workspace: the workspace object",
"name": "__init__",
"signature": "def __init__(self, workspace: Workspace)"
},
{
"docstring": "Process config element. Args: config_ctx: config context node: element node",
"name... | 3 | null | Implement the Python class `FLAdminClientStarterConfigurator` described below.
Class description:
FL Admin Client startup configurator.
Method signatures and docstrings:
- def __init__(self, workspace: Workspace): Uses the json configuration to start the FL admin client. Args: workspace: the workspace object
- def pr... | Implement the Python class `FLAdminClientStarterConfigurator` described below.
Class description:
FL Admin Client startup configurator.
Method signatures and docstrings:
- def __init__(self, workspace: Workspace): Uses the json configuration to start the FL admin client. Args: workspace: the workspace object
- def pr... | 1433290c203bd23f34c29e11795ce592bc067888 | <|skeleton|>
class FLAdminClientStarterConfigurator:
"""FL Admin Client startup configurator."""
def __init__(self, workspace: Workspace):
"""Uses the json configuration to start the FL admin client. Args: workspace: the workspace object"""
<|body_0|>
def process_config_element(self, confi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FLAdminClientStarterConfigurator:
"""FL Admin Client startup configurator."""
def __init__(self, workspace: Workspace):
"""Uses the json configuration to start the FL admin client. Args: workspace: the workspace object"""
base_pkgs = FL_PACKAGES
module_names = FL_MODULES
a... | the_stack_v2_python_sparse | nvflare/private/fed/app/fl_conf.py | NVIDIA/NVFlare | train | 442 |
7ffd33b939f3a5b844b815b020636e3abd713048 | [
"super(BinaryExtractorTask, self).__init__(*args, **kwargs)\nself.json_path = None\nself.binary_extraction_dir = None",
"if not os.path.exists(self.json_path):\n raise TurbiniaException('The file {0:s} was not found. Please ensure you have Plaso version 20191203 or greater deployed'.format(self.json_path))\nwi... | <|body_start_0|>
super(BinaryExtractorTask, self).__init__(*args, **kwargs)
self.json_path = None
self.binary_extraction_dir = None
<|end_body_0|>
<|body_start_1|>
if not os.path.exists(self.json_path):
raise TurbiniaException('The file {0:s} was not found. Please ensure you... | Extract binaries out of evidence and provide JSON file with hashes. Attributes: json_path(str): path to output JSON file. binary_extraction_dir(str): path to extraction directory. | BinaryExtractorTask | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryExtractorTask:
"""Extract binaries out of evidence and provide JSON file with hashes. Attributes: json_path(str): path to output JSON file. binary_extraction_dir(str): path to extraction directory."""
def __init__(self, *args, **kwargs):
"""Initializes BinaryExtractorTask."""
... | stack_v2_sparse_classes_36k_train_024697 | 4,102 | permissive | [
{
"docstring": "Initializes BinaryExtractorTask.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Checks counts for extracted binaries and hashes. Returns: Tuple( binary_cnt(int): Number of extracted binaries. hash_cnt(int): Number of extracted hashes. ... | 3 | stack_v2_sparse_classes_30k_train_008907 | Implement the Python class `BinaryExtractorTask` described below.
Class description:
Extract binaries out of evidence and provide JSON file with hashes. Attributes: json_path(str): path to output JSON file. binary_extraction_dir(str): path to extraction directory.
Method signatures and docstrings:
- def __init__(self... | Implement the Python class `BinaryExtractorTask` described below.
Class description:
Extract binaries out of evidence and provide JSON file with hashes. Attributes: json_path(str): path to output JSON file. binary_extraction_dir(str): path to extraction directory.
Method signatures and docstrings:
- def __init__(self... | e73717549c6919e869ce4963449c36f227e3ccd6 | <|skeleton|>
class BinaryExtractorTask:
"""Extract binaries out of evidence and provide JSON file with hashes. Attributes: json_path(str): path to output JSON file. binary_extraction_dir(str): path to extraction directory."""
def __init__(self, *args, **kwargs):
"""Initializes BinaryExtractorTask."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinaryExtractorTask:
"""Extract binaries out of evidence and provide JSON file with hashes. Attributes: json_path(str): path to output JSON file. binary_extraction_dir(str): path to extraction directory."""
def __init__(self, *args, **kwargs):
"""Initializes BinaryExtractorTask."""
super(... | the_stack_v2_python_sparse | turbinia/workers/binary_extractor.py | Ash515/turbinia | train | 6 |
39e15bd2f7acfdcc823bf03daa15d8743fc78c1d | [
"dp = {}\n\ndef find(i, j):\n if (i, j) not in dp:\n if i == j:\n return nums[i]\n dp[i, j] = max(nums[i] - find(i + 1, j), nums[j] - find(i, j - 1))\n return dp[i, j]\nreturn find(0, len(nums) - 1) >= 0",
"if len(nums) % 2 == 0:\n return True\ndp = list(nums)\nfor j in xrange(1,... | <|body_start_0|>
dp = {}
def find(i, j):
if (i, j) not in dp:
if i == j:
return nums[i]
dp[i, j] = max(nums[i] - find(i + 1, j), nums[j] - find(i, j - 1))
return dp[i, j]
return find(0, len(nums) - 1) >= 0
<|end_body_0|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def PredictTheWinner(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def PredictTheWinner2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
def PredictTheWinner3(self, nums):
""":type nums: List[int] :rt... | stack_v2_sparse_classes_36k_train_024698 | 1,660 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "PredictTheWinner",
"signature": "def PredictTheWinner(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "PredictTheWinner2",
"signature": "def PredictTheWinner2(self, nums)"
},
{
"docstring":... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def PredictTheWinner(self, nums): :type nums: List[int] :rtype: bool
- def PredictTheWinner2(self, nums): :type nums: List[int] :rtype: bool
- def PredictTheWinner3(self, nums): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def PredictTheWinner(self, nums): :type nums: List[int] :rtype: bool
- def PredictTheWinner2(self, nums): :type nums: List[int] :rtype: bool
- def PredictTheWinner3(self, nums): ... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def PredictTheWinner(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def PredictTheWinner2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
def PredictTheWinner3(self, nums):
""":type nums: List[int] :rt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def PredictTheWinner(self, nums):
""":type nums: List[int] :rtype: bool"""
dp = {}
def find(i, j):
if (i, j) not in dp:
if i == j:
return nums[i]
dp[i, j] = max(nums[i] - find(i + 1, j), nums[j] - find(i, j - 1)... | the_stack_v2_python_sparse | 486. Predict the Winner/winner.py | Macielyoung/LeetCode | train | 1 | |
ac0b4069aaddb2b98353d623801f7800b2545b9f | [
"index = (y >> 3) * framebuf.stride + x\noffset = y & 7\nframebuf.buf[index] = framebuf.buf[index] & ~(1 << offset) | (color != 0) << offset",
"index = (y >> 3) * framebuf.stride + x\noffset = y & 7\nreturn framebuf.buf[index] >> offset & 1",
"while height > 0:\n index = (y >> 3) * framebuf.stride + x\n o... | <|body_start_0|>
index = (y >> 3) * framebuf.stride + x
offset = y & 7
framebuf.buf[index] = framebuf.buf[index] & ~(1 << offset) | (color != 0) << offset
<|end_body_0|>
<|body_start_1|>
index = (y >> 3) * framebuf.stride + x
offset = y & 7
return framebuf.buf[index] >> ... | MVLSBFormat | MVLSBFormat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MVLSBFormat:
"""MVLSBFormat"""
def set_pixel(framebuf, x, y, color):
"""Set a given pixel to a color."""
<|body_0|>
def get_pixel(framebuf, x, y):
"""Get the color of a given pixel"""
<|body_1|>
def fill_rect(framebuf, x, y, width, height, color):
... | stack_v2_sparse_classes_36k_train_024699 | 10,632 | no_license | [
{
"docstring": "Set a given pixel to a color.",
"name": "set_pixel",
"signature": "def set_pixel(framebuf, x, y, color)"
},
{
"docstring": "Get the color of a given pixel",
"name": "get_pixel",
"signature": "def get_pixel(framebuf, x, y)"
},
{
"docstring": "Draw a rectangle at th... | 3 | stack_v2_sparse_classes_30k_train_013882 | Implement the Python class `MVLSBFormat` described below.
Class description:
MVLSBFormat
Method signatures and docstrings:
- def set_pixel(framebuf, x, y, color): Set a given pixel to a color.
- def get_pixel(framebuf, x, y): Get the color of a given pixel
- def fill_rect(framebuf, x, y, width, height, color): Draw a... | Implement the Python class `MVLSBFormat` described below.
Class description:
MVLSBFormat
Method signatures and docstrings:
- def set_pixel(framebuf, x, y, color): Set a given pixel to a color.
- def get_pixel(framebuf, x, y): Get the color of a given pixel
- def fill_rect(framebuf, x, y, width, height, color): Draw a... | 78cdde343961ba4a2f1b9e0833540f1b20b18bfc | <|skeleton|>
class MVLSBFormat:
"""MVLSBFormat"""
def set_pixel(framebuf, x, y, color):
"""Set a given pixel to a color."""
<|body_0|>
def get_pixel(framebuf, x, y):
"""Get the color of a given pixel"""
<|body_1|>
def fill_rect(framebuf, x, y, width, height, color):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MVLSBFormat:
"""MVLSBFormat"""
def set_pixel(framebuf, x, y, color):
"""Set a given pixel to a color."""
index = (y >> 3) * framebuf.stride + x
offset = y & 7
framebuf.buf[index] = framebuf.buf[index] & ~(1 << offset) | (color != 0) << offset
def get_pixel(framebuf, x... | the_stack_v2_python_sparse | led_matrix/framebuf.py | ben-64/led_matrix | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.