blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
69687f30b83f26d9974865f4999b4110701369ae | [
"self.ole_version = None\nself.format_id = None\nself.class_name = None\nself.topic_name = None\nself.item_name = None\nself.data = None\nself.data_size = None",
"self.ole_version, data = read_uint32(data)\nself.format_id, data = read_uint32(data)\nlog.debug('OLE version=%08X - Format ID=%08X' % (self.ole_version... | <|body_start_0|>
self.ole_version = None
self.format_id = None
self.class_name = None
self.topic_name = None
self.item_name = None
self.data = None
self.data_size = None
<|end_body_0|>
<|body_start_1|>
self.ole_version, data = read_uint32(data)
se... | OLE 1.0 Object see MS-OLEDS 2.2 OLE1.0 Format Structures | OleObject | [
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OleObject:
"""OLE 1.0 Object see MS-OLEDS 2.2 OLE1.0 Format Structures"""
def __init__(self, bindata=None):
"""Constructor for OleObject. If bindata is provided, it will be parsed using the parse() method. :param bindata: bytes, OLE 1.0 Object structure containing an OLE object"""
... | stack_v2_sparse_classes_75kplus_train_002900 | 18,572 | permissive | [
{
"docstring": "Constructor for OleObject. If bindata is provided, it will be parsed using the parse() method. :param bindata: bytes, OLE 1.0 Object structure containing an OLE object",
"name": "__init__",
"signature": "def __init__(self, bindata=None)"
},
{
"docstring": "Parse binary data conta... | 2 | stack_v2_sparse_classes_30k_train_034945 | Implement the Python class `OleObject` described below.
Class description:
OLE 1.0 Object see MS-OLEDS 2.2 OLE1.0 Format Structures
Method signatures and docstrings:
- def __init__(self, bindata=None): Constructor for OleObject. If bindata is provided, it will be parsed using the parse() method. :param bindata: bytes... | Implement the Python class `OleObject` described below.
Class description:
OLE 1.0 Object see MS-OLEDS 2.2 OLE1.0 Format Structures
Method signatures and docstrings:
- def __init__(self, bindata=None): Constructor for OleObject. If bindata is provided, it will be parsed using the parse() method. :param bindata: bytes... | 6e44429b912216455446aaee06336b6d28859bfb | <|skeleton|>
class OleObject:
"""OLE 1.0 Object see MS-OLEDS 2.2 OLE1.0 Format Structures"""
def __init__(self, bindata=None):
"""Constructor for OleObject. If bindata is provided, it will be parsed using the parse() method. :param bindata: bytes, OLE 1.0 Object structure containing an OLE object"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OleObject:
"""OLE 1.0 Object see MS-OLEDS 2.2 OLE1.0 Format Structures"""
def __init__(self, bindata=None):
"""Constructor for OleObject. If bindata is provided, it will be parsed using the parse() method. :param bindata: bytes, OLE 1.0 Object structure containing an OLE object"""
self.ol... | the_stack_v2_python_sparse | fame/env/lib/python2.7/site-packages/oletools/oleobj.py | MaikSoriano/TFM | train | 1 |
4b9208117e9582f217238dcde22b44d6a950c131 | [
"self.min_length = min_length\nself.max_length = max_length\nself.seed = seed\nsuper().__init__()",
"track: MidiTrack = mid.tracks[track_index]\nif 'chord_track' in kwargs and kwargs['chord_track'] is not None:\n chord_track_ind = kwargs['chord_track']\n chord_track = mid.tracks[chord_track_ind]\nelse:\n ... | <|body_start_0|>
self.min_length = min_length
self.max_length = max_length
self.seed = seed
super().__init__()
<|end_body_0|>
<|body_start_1|>
track: MidiTrack = mid.tracks[track_index]
if 'chord_track' in kwargs and kwargs['chord_track'] is not None:
chord_t... | RandomSegmenter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomSegmenter:
def __init__(self, seed: Optional[int], min_length: float=1, max_length: float=2):
"""A ``Segmenter`` which is similar to ``TimeSegmenter``, but extracts random length ``NoteSegments`` instead of fixed length ones. Args: seed: The random seed used to determine segment le... | stack_v2_sparse_classes_75kplus_train_002901 | 3,056 | no_license | [
{
"docstring": "A ``Segmenter`` which is similar to ``TimeSegmenter``, but extracts random length ``NoteSegments`` instead of fixed length ones. Args: seed: The random seed used to determine segment lengths. If None, uses the Numpy default random seed. min_length: The minimum length of each segment (in seconds)... | 2 | stack_v2_sparse_classes_30k_train_025066 | Implement the Python class `RandomSegmenter` described below.
Class description:
Implement the RandomSegmenter class.
Method signatures and docstrings:
- def __init__(self, seed: Optional[int], min_length: float=1, max_length: float=2): A ``Segmenter`` which is similar to ``TimeSegmenter``, but extracts random length... | Implement the Python class `RandomSegmenter` described below.
Class description:
Implement the RandomSegmenter class.
Method signatures and docstrings:
- def __init__(self, seed: Optional[int], min_length: float=1, max_length: float=2): A ``Segmenter`` which is similar to ``TimeSegmenter``, but extracts random length... | f78b35274f49f6ae54ca7bc02691ab5db45eda36 | <|skeleton|>
class RandomSegmenter:
def __init__(self, seed: Optional[int], min_length: float=1, max_length: float=2):
"""A ``Segmenter`` which is similar to ``TimeSegmenter``, but extracts random length ``NoteSegments`` instead of fixed length ones. Args: seed: The random seed used to determine segment le... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomSegmenter:
def __init__(self, seed: Optional[int], min_length: float=1, max_length: float=2):
"""A ``Segmenter`` which is similar to ``TimeSegmenter``, but extracts random length ``NoteSegments`` instead of fixed length ones. Args: seed: The random seed used to determine segment lengths. If None... | the_stack_v2_python_sparse | project/algorithms/core/random_segmenter.py | jamesb456/final-year-project | train | 0 | |
e9d6bf29e95de9f1a19e079e0ea82c64db2a0f49 | [
"self.sagemaker_session = sagemaker_session\nself.s3_base_uri = s3_base_uri\nself.s3_kms_key = s3_kms_key\nself.hmac_key = hmac_key",
"logger.info(f'Serializing function code to {s3_path_join(self.s3_base_uri, FUNCTION_FOLDER)}')\nserialization.serialize_func_to_s3(func=func, sagemaker_session=self.sagemaker_sess... | <|body_start_0|>
self.sagemaker_session = sagemaker_session
self.s3_base_uri = s3_base_uri
self.s3_kms_key = s3_kms_key
self.hmac_key = hmac_key
<|end_body_0|>
<|body_start_1|>
logger.info(f'Serializing function code to {s3_path_join(self.s3_base_uri, FUNCTION_FOLDER)}')
... | Class representing a remote function stored in S3. | StoredFunction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoredFunction:
"""Class representing a remote function stored in S3."""
def __init__(self, sagemaker_session: Session, s3_base_uri: str, hmac_key: str, s3_kms_key: str=None):
"""Construct a StoredFunction object. Args: sagemaker_session: (sagemaker.session.Session): The underlying s... | stack_v2_sparse_classes_75kplus_train_002902 | 4,332 | permissive | [
{
"docstring": "Construct a StoredFunction object. Args: sagemaker_session: (sagemaker.session.Session): The underlying sagemaker session which AWS service calls are delegated to. s3_base_uri: the base uri to which serialized artifacts will be uploaded. s3_kms_key: KMS key used to encrypt artifacts uploaded to ... | 3 | null | Implement the Python class `StoredFunction` described below.
Class description:
Class representing a remote function stored in S3.
Method signatures and docstrings:
- def __init__(self, sagemaker_session: Session, s3_base_uri: str, hmac_key: str, s3_kms_key: str=None): Construct a StoredFunction object. Args: sagemak... | Implement the Python class `StoredFunction` described below.
Class description:
Class representing a remote function stored in S3.
Method signatures and docstrings:
- def __init__(self, sagemaker_session: Session, s3_base_uri: str, hmac_key: str, s3_kms_key: str=None): Construct a StoredFunction object. Args: sagemak... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class StoredFunction:
"""Class representing a remote function stored in S3."""
def __init__(self, sagemaker_session: Session, s3_base_uri: str, hmac_key: str, s3_kms_key: str=None):
"""Construct a StoredFunction object. Args: sagemaker_session: (sagemaker.session.Session): The underlying s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StoredFunction:
"""Class representing a remote function stored in S3."""
def __init__(self, sagemaker_session: Session, s3_base_uri: str, hmac_key: str, s3_kms_key: str=None):
"""Construct a StoredFunction object. Args: sagemaker_session: (sagemaker.session.Session): The underlying sagemaker sess... | the_stack_v2_python_sparse | src/sagemaker/remote_function/core/stored_function.py | aws/sagemaker-python-sdk | train | 2,050 |
2a75b94e95bab6a40f675beb210a45e024bbb728 | [
"dummy = ListNode(0)\ndummy.next = head\npre = dummy\nwhile pre.next and pre.next.next:\n n1 = pre.next\n n2 = n1.next\n tmp = n2.next\n pre.next = n2\n n2.next = n1\n n1.next = tmp\n pre = n1",
"dummy = ListNode(0)\ndummy.next = head\npre = dummy\nwhile pre.next and pre.next.next:\n first... | <|body_start_0|>
dummy = ListNode(0)
dummy.next = head
pre = dummy
while pre.next and pre.next.next:
n1 = pre.next
n2 = n1.next
tmp = n2.next
pre.next = n2
n2.next = n1
n1.next = tmp
pre = n1
<|end_body_0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairs_2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dummy = ListNode(0)
dummy.next ... | stack_v2_sparse_classes_75kplus_train_002903 | 1,460 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs",
"signature": "def swapPairs(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs_2",
"signature": "def swapPairs_2(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009822 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def swapPairs_2(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def swapPairs_2(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def swapP... | a42098599bac4188eccb447de146434bc236a70a | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairs_2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
dummy = ListNode(0)
dummy.next = head
pre = dummy
while pre.next and pre.next.next:
n1 = pre.next
n2 = n1.next
tmp = n2.next
pre.next = n2
... | the_stack_v2_python_sparse | 力扣/z_03_两两交换链表中的节点.py | Pysuper/LetCODE | train | 1 | |
028a20ae7c5ff3524ccfc04dd2bfeb1d0493e36f | [
"super().__init__(pred_name, target_name, filter_func, **kwargs)\nself._class_names = class_names\nself._operation_point = operation_point\nself._metrics = metrics\nself._sum_weights = sum_weights",
"if isinstance(self._operation_point, Callable):\n class_thresholds = self._operation_point(self.epoch_preds, se... | <|body_start_0|>
super().__init__(pred_name, target_name, filter_func, **kwargs)
self._class_names = class_names
self._operation_point = operation_point
self._metrics = metrics
self._sum_weights = sum_weights
<|end_body_0|>
<|body_start_1|>
if isinstance(self._operation_... | Multi class version for confusion metrics including: sensitivity, specificity, recall., precision, f1. | FuseMetricConfusion | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FuseMetricConfusion:
"""Multi class version for confusion metrics including: sensitivity, specificity, recall., precision, f1."""
def __init__(self, pred_name: str, target_name: str, filter_func: Optional[Callable]=None, class_names: List=None, operation_point: Optional[Union[float, List[Tup... | stack_v2_sparse_classes_75kplus_train_002904 | 5,198 | permissive | [
{
"docstring": ":param pred_name: batch_dict key for predicted output (e.g., class probabilities after softmax) :param target_name: batch_dict key for target (e.g., ground truth label) :param filter_func: function that filters batch_dict/ The function gets ans input batch_dict and returns filtered batch_dict :p... | 2 | stack_v2_sparse_classes_30k_train_006953 | Implement the Python class `FuseMetricConfusion` described below.
Class description:
Multi class version for confusion metrics including: sensitivity, specificity, recall., precision, f1.
Method signatures and docstrings:
- def __init__(self, pred_name: str, target_name: str, filter_func: Optional[Callable]=None, cla... | Implement the Python class `FuseMetricConfusion` described below.
Class description:
Multi class version for confusion metrics including: sensitivity, specificity, recall., precision, f1.
Method signatures and docstrings:
- def __init__(self, pred_name: str, target_name: str, filter_func: Optional[Callable]=None, cla... | acbfd4975f18cd4361d31697faf2f82036399865 | <|skeleton|>
class FuseMetricConfusion:
"""Multi class version for confusion metrics including: sensitivity, specificity, recall., precision, f1."""
def __init__(self, pred_name: str, target_name: str, filter_func: Optional[Callable]=None, class_names: List=None, operation_point: Optional[Union[float, List[Tup... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FuseMetricConfusion:
"""Multi class version for confusion metrics including: sensitivity, specificity, recall., precision, f1."""
def __init__(self, pred_name: str, target_name: str, filter_func: Optional[Callable]=None, class_names: List=None, operation_point: Optional[Union[float, List[Tuple], Callable... | the_stack_v2_python_sparse | fuse/metrics/classification/metric_confusion.py | rosenzvi/fuse-med-ml | train | 0 |
f7b3b5fd1cb3cb88317dfb63c8f0a9f856ae127b | [
"start, goal = (0, 4)\narcs = [(0, 1), (0, 2), (0, 3), (3, 4)]\ng = Graph(goal + 1)\nfor arc in arcs:\n g.add_edge(arc[0], arc[1])\nself.assertEqual(g.find_love(start, goal), (2, ['3', '4']))\nstart, goal = (0, 9)\narcs = [(0, 1), (0, 2), (0, 3), (1, 5), (2, 4), (3, 7), (4, 9), (5, 6), (7, 8), (6, 9), (8, 9)]\ng... | <|body_start_0|>
start, goal = (0, 4)
arcs = [(0, 1), (0, 2), (0, 3), (3, 4)]
g = Graph(goal + 1)
for arc in arcs:
g.add_edge(arc[0], arc[1])
self.assertEqual(g.find_love(start, goal), (2, ['3', '4']))
start, goal = (0, 9)
arcs = [(0, 1), (0, 2), (0, 3... | TestStringMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStringMethods:
def test_find_love(self):
"""Función encargada de probar la función find love. :return:"""
<|body_0|>
def test_priority_queue(self):
"""Función encargada de probar la cola de prioridad :return:"""
<|body_1|>
def test_related_regions(se... | stack_v2_sparse_classes_75kplus_train_002905 | 3,855 | no_license | [
{
"docstring": "Función encargada de probar la función find love. :return:",
"name": "test_find_love",
"signature": "def test_find_love(self)"
},
{
"docstring": "Función encargada de probar la cola de prioridad :return:",
"name": "test_priority_queue",
"signature": "def test_priority_que... | 4 | null | Implement the Python class `TestStringMethods` described below.
Class description:
Implement the TestStringMethods class.
Method signatures and docstrings:
- def test_find_love(self): Función encargada de probar la función find love. :return:
- def test_priority_queue(self): Función encargada de probar la cola de pri... | Implement the Python class `TestStringMethods` described below.
Class description:
Implement the TestStringMethods class.
Method signatures and docstrings:
- def test_find_love(self): Función encargada de probar la función find love. :return:
- def test_priority_queue(self): Función encargada de probar la cola de pri... | a168ae5a28d00f39422ca501e1a3d997ce0a1833 | <|skeleton|>
class TestStringMethods:
def test_find_love(self):
"""Función encargada de probar la función find love. :return:"""
<|body_0|>
def test_priority_queue(self):
"""Función encargada de probar la cola de prioridad :return:"""
<|body_1|>
def test_related_regions(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestStringMethods:
def test_find_love(self):
"""Función encargada de probar la función find love. :return:"""
start, goal = (0, 4)
arcs = [(0, 1), (0, 2), (0, 3), (3, 4)]
g = Graph(goal + 1)
for arc in arcs:
g.add_edge(arc[0], arc[1])
self.assertEqua... | the_stack_v2_python_sparse | unit_tests.py | juancho20sp/final-ayed-backend | train | 5 | |
194b46c77762e4a55554c428d789a36a3cc3a5cc | [
"super(CustomSlider, self).__init__(*args, **kwargs)\nself.index = index\nself.value = value\nself.slider = QtWidgets.QSlider(QtCore.Qt.Vertical)\nself.slider.setSingleStep(1)\nself.label = QtWidgets.QLabel()\nself.slider.setValue(value)\nself.label.setText(str(self.slider.value()))\nself.vbox = QtWidgets.QVBoxLayo... | <|body_start_0|>
super(CustomSlider, self).__init__(*args, **kwargs)
self.index = index
self.value = value
self.slider = QtWidgets.QSlider(QtCore.Qt.Vertical)
self.slider.setSingleStep(1)
self.label = QtWidgets.QLabel()
self.slider.setValue(value)
self.lab... | CustomSlider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSlider:
def __init__(self, index, value, *args, **kwargs):
"""Args: index: value: *args: **kwargs:"""
<|body_0|>
def update_value(self, value):
"""Args: value: Returns:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(CustomSlider, self).... | stack_v2_sparse_classes_75kplus_train_002906 | 6,455 | no_license | [
{
"docstring": "Args: index: value: *args: **kwargs:",
"name": "__init__",
"signature": "def __init__(self, index, value, *args, **kwargs)"
},
{
"docstring": "Args: value: Returns:",
"name": "update_value",
"signature": "def update_value(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025176 | Implement the Python class `CustomSlider` described below.
Class description:
Implement the CustomSlider class.
Method signatures and docstrings:
- def __init__(self, index, value, *args, **kwargs): Args: index: value: *args: **kwargs:
- def update_value(self, value): Args: value: Returns: | Implement the Python class `CustomSlider` described below.
Class description:
Implement the CustomSlider class.
Method signatures and docstrings:
- def __init__(self, index, value, *args, **kwargs): Args: index: value: *args: **kwargs:
- def update_value(self, value): Args: value: Returns:
<|skeleton|>
class CustomS... | fe237b749c9393ca1acbb03b5fc593cebda8f71f | <|skeleton|>
class CustomSlider:
def __init__(self, index, value, *args, **kwargs):
"""Args: index: value: *args: **kwargs:"""
<|body_0|>
def update_value(self, value):
"""Args: value: Returns:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomSlider:
def __init__(self, index, value, *args, **kwargs):
"""Args: index: value: *args: **kwargs:"""
super(CustomSlider, self).__init__(*args, **kwargs)
self.index = index
self.value = value
self.slider = QtWidgets.QSlider(QtCore.Qt.Vertical)
self.slider.... | the_stack_v2_python_sparse | source/gui/new_configuration.py | kflana1/piscope | train | 0 | |
33f2887c4568e71985fe51770b0904c51f57e187 | [
"try:\n file_id = UUID(req_data['file_id']).hex\nexcept ValueError:\n return Response(status='400 Bad Request')\nstored_files = StoredFile.collection()\nto_delete = stored_files.first(id=file_id)\nlog_activity('%s deleted file %s' % (context.user.link, to_delete.filename))\nstored_files.delete(to_delete)\nget... | <|body_start_0|>
try:
file_id = UUID(req_data['file_id']).hex
except ValueError:
return Response(status='400 Bad Request')
stored_files = StoredFile.collection()
to_delete = stored_files.first(id=file_id)
log_activity('%s deleted file %s' % (context.user.l... | The file set controller. | FileSetController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileSetController:
"""The file set controller."""
def delete(self, *route, **req_data):
"""Handle a file delete."""
<|body_0|>
def upload(self, *route, **req_data):
"""Handle a file upload."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_75kplus_train_002907 | 8,541 | permissive | [
{
"docstring": "Handle a file delete.",
"name": "delete",
"signature": "def delete(self, *route, **req_data)"
},
{
"docstring": "Handle a file upload.",
"name": "upload",
"signature": "def upload(self, *route, **req_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012275 | Implement the Python class `FileSetController` described below.
Class description:
The file set controller.
Method signatures and docstrings:
- def delete(self, *route, **req_data): Handle a file delete.
- def upload(self, *route, **req_data): Handle a file upload. | Implement the Python class `FileSetController` described below.
Class description:
The file set controller.
Method signatures and docstrings:
- def delete(self, *route, **req_data): Handle a file delete.
- def upload(self, *route, **req_data): Handle a file upload.
<|skeleton|>
class FileSetController:
"""The fi... | b34cb4b2ee7cc40b2c99015f05bfcc12d4b49065 | <|skeleton|>
class FileSetController:
"""The file set controller."""
def delete(self, *route, **req_data):
"""Handle a file delete."""
<|body_0|>
def upload(self, *route, **req_data):
"""Handle a file upload."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileSetController:
"""The file set controller."""
def delete(self, *route, **req_data):
"""Handle a file delete."""
try:
file_id = UUID(req_data['file_id']).hex
except ValueError:
return Response(status='400 Bad Request')
stored_files = StoredFile.c... | the_stack_v2_python_sparse | zoom/_assets/standard_apps/content/files.py | dsilabs/zoom | train | 9 |
a9a0185ab6c07e59d5434aa273cbb2c48d948c50 | [
"import tables\nself.h5 = tables.open_file(filename)\nself.min_points = min_points\ntable_names = list(self.h5.root.events._v_children.keys())\nstart_times = [datetime(*getattr(self.h5.root.events, the_table).attrs['start_time']) for the_table in table_names]\nst, tn = zip(*sorted(zip(start_times, table_names)))\ns... | <|body_start_0|>
import tables
self.h5 = tables.open_file(filename)
self.min_points = min_points
table_names = list(self.h5.root.events._v_children.keys())
start_times = [datetime(*getattr(self.h5.root.events, the_table).attrs['start_time']) for the_table in table_names]
... | LMAh5File | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LMAh5File:
def __init__(self, filename, min_points=1):
"""Open an HDF5 LMA file so as to read LMA event/flash tables. The events and flashes groups may contain more than one table, and the list of self.table_names corresponds to self.start_times and are sorted in increasing time order. s... | stack_v2_sparse_classes_75kplus_train_002908 | 10,049 | permissive | [
{
"docstring": "Open an HDF5 LMA file so as to read LMA event/flash tables. The events and flashes groups may contain more than one table, and the list of self.table_names corresponds to self.start_times and are sorted in increasing time order. self.base_date provides the base_date against which time in seconds... | 3 | stack_v2_sparse_classes_30k_test_001945 | Implement the Python class `LMAh5File` described below.
Class description:
Implement the LMAh5File class.
Method signatures and docstrings:
- def __init__(self, filename, min_points=1): Open an HDF5 LMA file so as to read LMA event/flash tables. The events and flashes groups may contain more than one table, and the l... | Implement the Python class `LMAh5File` described below.
Class description:
Implement the LMAh5File class.
Method signatures and docstrings:
- def __init__(self, filename, min_points=1): Open an HDF5 LMA file so as to read LMA event/flash tables. The events and flashes groups may contain more than one table, and the l... | 392eff5f15735be7b7f5ccc20d2835a617000117 | <|skeleton|>
class LMAh5File:
def __init__(self, filename, min_points=1):
"""Open an HDF5 LMA file so as to read LMA event/flash tables. The events and flashes groups may contain more than one table, and the list of self.table_names corresponds to self.start_times and are sorted in increasing time order. s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LMAh5File:
def __init__(self, filename, min_points=1):
"""Open an HDF5 LMA file so as to read LMA event/flash tables. The events and flashes groups may contain more than one table, and the list of self.table_names corresponds to self.start_times and are sorted in increasing time order. self.base_date ... | the_stack_v2_python_sparse | lmatools/io/LMA_h5_file.py | deeplycloudy/lmatools | train | 16 | |
0dabe59778dfff899beb884fc08d75ae385e9eb5 | [
"def traverse(root, ret):\n if not root:\n return\n ret.append(root.val)\n traverse(root.left, ret)\n traverse(root.right, ret)\nret = []\ntraverse(root, ret)\nreturn self.DELIMITER.join(map(str, ret))",
"if not data:\n return\nlst = list(map(int, data.split(self.DELIMITER)))\nroot = TreeNod... | <|body_start_0|>
def traverse(root, ret):
if not root:
return
ret.append(root.val)
traverse(root.left, ret)
traverse(root.right, ret)
ret = []
traverse(root, ret)
return self.DELIMITER.join(map(str, ret))
<|end_body_0|>
<|b... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. Basic binary tree serialize (BFS), see Serialize and Deserialize Binary Tree The main difference is as compact as possible. No need "null", since insertion order is specfied. 3 (1) 2 (2) 5 (2) 6 (3) # bracket () is t... | stack_v2_sparse_classes_75kplus_train_002909 | 2,535 | permissive | [
{
"docstring": "Encodes a tree to a single string. Basic binary tree serialize (BFS), see Serialize and Deserialize Binary Tree The main difference is as compact as possible. No need \"null\", since insertion order is specfied. 3 (1) 2 (2) 5 (2) 6 (3) # bracket () is the insertion order pre-order traversal keep... | 2 | stack_v2_sparse_classes_30k_train_027356 | 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. Basic binary tree serialize (BFS), see Serialize and Deserialize Binary Tree The main difference is as compact as possible... | 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. Basic binary tree serialize (BFS), see Serialize and Deserialize Binary Tree The main difference is as compact as possible... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. Basic binary tree serialize (BFS), see Serialize and Deserialize Binary Tree The main difference is as compact as possible. No need "null", since insertion order is specfied. 3 (1) 2 (2) 5 (2) 6 (3) # bracket () is t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. Basic binary tree serialize (BFS), see Serialize and Deserialize Binary Tree The main difference is as compact as possible. No need "null", since insertion order is specfied. 3 (1) 2 (2) 5 (2) 6 (3) # bracket () is the insertion o... | the_stack_v2_python_sparse | 449 Serialize and Deserialize BST.py | Aminaba123/LeetCode | train | 1 | |
0abddf8a190c6edb6cc09e219700b4feae7742b4 | [
"if not helpers.ros_core_is_running():\n debug(1, \"Can't start ArdroneVideo, roscore not running\")\n return\nif not os.path.isdir(img_out_dir):\n debug(1, 'Invalid directory for output images from drone: ', img_out_dir, '. Using ./ instead')\n self.img_out_dir = './'\nelse:\n self.img_out_dir = img... | <|body_start_0|>
if not helpers.ros_core_is_running():
debug(1, "Can't start ArdroneVideo, roscore not running")
return
if not os.path.isdir(img_out_dir):
debug(1, 'Invalid directory for output images from drone: ', img_out_dir, '. Using ./ instead')
self.... | Captures images from the drone and stores it to img_out_dir | ArdroneVideo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArdroneVideo:
"""Captures images from the drone and stores it to img_out_dir"""
def __init__(self, img_out_dir, show_image=False, save_image=True):
""":param img_out_dir: directory to save image :param show_image: Display each captured image in a window. This might reduce the framera... | stack_v2_sparse_classes_75kplus_train_002910 | 5,510 | no_license | [
{
"docstring": ":param img_out_dir: directory to save image :param show_image: Display each captured image in a window. This might reduce the framerate :param save_image: Save images to img_out_dir :return:",
"name": "__init__",
"signature": "def __init__(self, img_out_dir, show_image=False, save_image=... | 6 | stack_v2_sparse_classes_30k_test_002911 | Implement the Python class `ArdroneVideo` described below.
Class description:
Captures images from the drone and stores it to img_out_dir
Method signatures and docstrings:
- def __init__(self, img_out_dir, show_image=False, save_image=True): :param img_out_dir: directory to save image :param show_image: Display each ... | Implement the Python class `ArdroneVideo` described below.
Class description:
Captures images from the drone and stores it to img_out_dir
Method signatures and docstrings:
- def __init__(self, img_out_dir, show_image=False, save_image=True): :param img_out_dir: directory to save image :param show_image: Display each ... | 35a3bc32e771cd4b13a7ad0c799474e7ba594703 | <|skeleton|>
class ArdroneVideo:
"""Captures images from the drone and stores it to img_out_dir"""
def __init__(self, img_out_dir, show_image=False, save_image=True):
""":param img_out_dir: directory to save image :param show_image: Display each captured image in a window. This might reduce the framera... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArdroneVideo:
"""Captures images from the drone and stores it to img_out_dir"""
def __init__(self, img_out_dir, show_image=False, save_image=True):
""":param img_out_dir: directory to save image :param show_image: Display each captured image in a window. This might reduce the framerate :param sav... | the_stack_v2_python_sparse | dronarch/drone/ArdroneVideo.py | DRONARCHers/DRONARCH | train | 1 |
ef89d1ecbeef51897ed5c1ad374848730ec3d2eb | [
"data_course = request.data\nauth_token = request.headers['Authorization'][6:]\nuser = YouYodaUser.objects.get(auth_token=auth_token)\ncourse = Courses.objects.get(id=data_course['course_id'])\ndata_course['participant_id'] = user.id\ndata_course['course_id'] = course.id\ncourse_add = CoursesSubscribers.objects.fil... | <|body_start_0|>
data_course = request.data
auth_token = request.headers['Authorization'][6:]
user = YouYodaUser.objects.get(auth_token=auth_token)
course = Courses.objects.get(id=data_course['course_id'])
data_course['participant_id'] = user.id
data_course['course_id'] =... | Takes data from CoursesSubscribersPostSerializator for add user to course | UserSubscribeToCourse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSubscribeToCourse:
"""Takes data from CoursesSubscribersPostSerializator for add user to course"""
def post(self, request):
"""Push user, course to db with CoursesSubscribersPostSerializator"""
<|body_0|>
def get(self, request):
"""Receives and transmits user... | stack_v2_sparse_classes_75kplus_train_002911 | 5,378 | no_license | [
{
"docstring": "Push user, course to db with CoursesSubscribersPostSerializator",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Receives and transmits user course data and schedule data about these courses",
"name": "get",
"signature": "def get(self, request)"... | 4 | stack_v2_sparse_classes_30k_train_007926 | Implement the Python class `UserSubscribeToCourse` described below.
Class description:
Takes data from CoursesSubscribersPostSerializator for add user to course
Method signatures and docstrings:
- def post(self, request): Push user, course to db with CoursesSubscribersPostSerializator
- def get(self, request): Receiv... | Implement the Python class `UserSubscribeToCourse` described below.
Class description:
Takes data from CoursesSubscribersPostSerializator for add user to course
Method signatures and docstrings:
- def post(self, request): Push user, course to db with CoursesSubscribersPostSerializator
- def get(self, request): Receiv... | 62b4f1cc79b4c71cc44bb741fb20af066c7023a5 | <|skeleton|>
class UserSubscribeToCourse:
"""Takes data from CoursesSubscribersPostSerializator for add user to course"""
def post(self, request):
"""Push user, course to db with CoursesSubscribersPostSerializator"""
<|body_0|>
def get(self, request):
"""Receives and transmits user... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserSubscribeToCourse:
"""Takes data from CoursesSubscribersPostSerializator for add user to course"""
def post(self, request):
"""Push user, course to db with CoursesSubscribersPostSerializator"""
data_course = request.data
auth_token = request.headers['Authorization'][6:]
... | the_stack_v2_python_sparse | backend/appsrc/views/user_subscribe_to_course.py | OleksandrHavrylchyk/YouYoda | train | 0 |
a5f7a0eab27292fa3d7b726318988c64c983615d | [
"if isinstance(other, Vector3):\n return self.cross(other)\nelse:\n return NotImplemented",
"if not isinstance(other, Vector3):\n raise TypeError('Attempt to cross Vector3 with invalid type')\nx = self.y * other.z - self.z * other.y\ny = self.z * other.x - self.x * other.z\nz = self.x * other.y - self.y ... | <|body_start_0|>
if isinstance(other, Vector3):
return self.cross(other)
else:
return NotImplemented
<|end_body_0|>
<|body_start_1|>
if not isinstance(other, Vector3):
raise TypeError('Attempt to cross Vector3 with invalid type')
x = self.y * other.z ... | Specialization of a Vector for 3 dimensions, adding support for cross-product of 3D vectors | Vector3 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector3:
"""Specialization of a Vector for 3 dimensions, adding support for cross-product of 3D vectors"""
def __matmul__(self, other):
"""Cross this 3D vector with another 3D vector :param other: Vector to cross this vector with :return: Cross product of two vectors"""
<|bod... | stack_v2_sparse_classes_75kplus_train_002912 | 21,973 | permissive | [
{
"docstring": "Cross this 3D vector with another 3D vector :param other: Vector to cross this vector with :return: Cross product of two vectors",
"name": "__matmul__",
"signature": "def __matmul__(self, other)"
},
{
"docstring": "Cross this 3D vector with another 3D vector :param other: Vector ... | 2 | stack_v2_sparse_classes_30k_train_032097 | Implement the Python class `Vector3` described below.
Class description:
Specialization of a Vector for 3 dimensions, adding support for cross-product of 3D vectors
Method signatures and docstrings:
- def __matmul__(self, other): Cross this 3D vector with another 3D vector :param other: Vector to cross this vector wi... | Implement the Python class `Vector3` described below.
Class description:
Specialization of a Vector for 3 dimensions, adding support for cross-product of 3D vectors
Method signatures and docstrings:
- def __matmul__(self, other): Cross this 3D vector with another 3D vector :param other: Vector to cross this vector wi... | 4bf155feec7cb983e8d283d93552902ec85178a2 | <|skeleton|>
class Vector3:
"""Specialization of a Vector for 3 dimensions, adding support for cross-product of 3D vectors"""
def __matmul__(self, other):
"""Cross this 3D vector with another 3D vector :param other: Vector to cross this vector with :return: Cross product of two vectors"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Vector3:
"""Specialization of a Vector for 3 dimensions, adding support for cross-product of 3D vectors"""
def __matmul__(self, other):
"""Cross this 3D vector with another 3D vector :param other: Vector to cross this vector with :return: Cross product of two vectors"""
if isinstance(othe... | the_stack_v2_python_sparse | spidertools/math/vector.py | CraftSpider/SpiderTools | train | 6 |
4bfd691c39d1b314fc79d231bb66bb5fc70b3b5c | [
"tkinter.Label.__init__(self, parent)\nself.display_seconds = seconds\nif self.display_seconds:\n self.time = time.strftime('%H:%M:%S')\nelse:\n self.time = time.strftime('%I:%M %p').lstrip('0')\nself.display_time = self.time\nself.configure(text=self.display_time)\nif colon:\n self.blink_colon()\nself.aft... | <|body_start_0|>
tkinter.Label.__init__(self, parent)
self.display_seconds = seconds
if self.display_seconds:
self.time = time.strftime('%H:%M:%S')
else:
self.time = time.strftime('%I:%M %p').lstrip('0')
self.display_time = self.time
self.configure... | Class that contains the clock widget and clock refresh | Clock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Clock:
"""Class that contains the clock widget and clock refresh"""
def __init__(self, parent=None, seconds=True, colon=False):
"""Create and place the clock widget into the parent element It's an ordinary Label element with two additional features."""
<|body_0|>
def tic... | stack_v2_sparse_classes_75kplus_train_002913 | 2,925 | no_license | [
{
"docstring": "Create and place the clock widget into the parent element It's an ordinary Label element with two additional features.",
"name": "__init__",
"signature": "def __init__(self, parent=None, seconds=True, colon=False)"
},
{
"docstring": "Updates the display clock every 200 millisecon... | 3 | null | Implement the Python class `Clock` described below.
Class description:
Class that contains the clock widget and clock refresh
Method signatures and docstrings:
- def __init__(self, parent=None, seconds=True, colon=False): Create and place the clock widget into the parent element It's an ordinary Label element with tw... | Implement the Python class `Clock` described below.
Class description:
Class that contains the clock widget and clock refresh
Method signatures and docstrings:
- def __init__(self, parent=None, seconds=True, colon=False): Create and place the clock widget into the parent element It's an ordinary Label element with tw... | c379fdcad1c48f0985222b1ee793cc2dfae718e4 | <|skeleton|>
class Clock:
"""Class that contains the clock widget and clock refresh"""
def __init__(self, parent=None, seconds=True, colon=False):
"""Create and place the clock widget into the parent element It's an ordinary Label element with two additional features."""
<|body_0|>
def tic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Clock:
"""Class that contains the clock widget and clock refresh"""
def __init__(self, parent=None, seconds=True, colon=False):
"""Create and place the clock widget into the parent element It's an ordinary Label element with two additional features."""
tkinter.Label.__init__(self, parent)... | the_stack_v2_python_sparse | sshp/utilities/Clock.py | EbinavSoftwares/RetailBillingSoftware_v2 | train | 0 |
f3dc754be3466b3e77961141e65282d2e06de147 | [
"curnum = 0\ncurarray = []\nk = 0\nstart = 0\ncurlength = 0\nans = 999999\nwhile start < len(nums):\n if curnum < s:\n curnum += nums[start]\n curarray.append(nums[start])\n start += 1\n curlength += 1\n else:\n while curnum >= s:\n ans = min(ans, curlength)\n ... | <|body_start_0|>
curnum = 0
curarray = []
k = 0
start = 0
curlength = 0
ans = 999999
while start < len(nums):
if curnum < s:
curnum += nums[start]
curarray.append(nums[start])
start += 1
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minSubArrayLen1(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_0|>
def minSubArrayLen2(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
curnu... | stack_v2_sparse_classes_75kplus_train_002914 | 1,465 | no_license | [
{
"docstring": ":type s: int :type nums: List[int] :rtype: int",
"name": "minSubArrayLen1",
"signature": "def minSubArrayLen1(self, s, nums)"
},
{
"docstring": ":type s: int :type nums: List[int] :rtype: int",
"name": "minSubArrayLen2",
"signature": "def minSubArrayLen2(self, s, nums)"
... | 2 | stack_v2_sparse_classes_30k_train_048168 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen1(self, s, nums): :type s: int :type nums: List[int] :rtype: int
- def minSubArrayLen2(self, s, nums): :type s: int :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen1(self, s, nums): :type s: int :type nums: List[int] :rtype: int
- def minSubArrayLen2(self, s, nums): :type s: int :type nums: List[int] :rtype: int
<|skeleto... | d741fe6138876587204ed395dddf58ade7ddb413 | <|skeleton|>
class Solution:
def minSubArrayLen1(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_0|>
def minSubArrayLen2(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minSubArrayLen1(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
curnum = 0
curarray = []
k = 0
start = 0
curlength = 0
ans = 999999
while start < len(nums):
if curnum < s:
curnum += n... | the_stack_v2_python_sparse | 209 长度最小的子数组.py | wyhhuster/leetcode | train | 0 | |
d1ab3f251ee407da224c994e728e5337ac0d61ed | [
"pos = {}\nfor i, num in enumerate(nums):\n if num in pos and i - pos[num] <= k:\n return True\n pos[num] = i\nreturn False",
"cnt = collections.Counter(nums[:k + 1])\nif any((True for x in cnt.keys() if cnt[x] > 1)):\n return True\nfor i, num in enumerate(nums[k + 1:], k + 1):\n cnt[nums[i - k... | <|body_start_0|>
pos = {}
for i, num in enumerate(nums):
if num in pos and i - pos[num] <= k:
return True
pos[num] = i
return False
<|end_body_0|>
<|body_start_1|>
cnt = collections.Counter(nums[:k + 1])
if any((True for x in cnt.keys() if... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
"""2022-10-21 Runtime: 760 ms, faster than 81.02% Memory Usage: 27.6 MB, less than 14.95% 1 <= nums.length <= 10^5 -10^9 <= nums[i] <= 10^9 0 <= k <= 10^5"""
<|body_0|>
def containsNearbyDuplicate2... | stack_v2_sparse_classes_75kplus_train_002915 | 1,696 | permissive | [
{
"docstring": "2022-10-21 Runtime: 760 ms, faster than 81.02% Memory Usage: 27.6 MB, less than 14.95% 1 <= nums.length <= 10^5 -10^9 <= nums[i] <= 10^9 0 <= k <= 10^5",
"name": "containsNearbyDuplicate",
"signature": "def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool"
},
{
"doc... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 2022-10-21 Runtime: 760 ms, faster than 81.02% Memory Usage: 27.6 MB, less than 14.95% 1 <= nums.length <= 10^... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 2022-10-21 Runtime: 760 ms, faster than 81.02% Memory Usage: 27.6 MB, less than 14.95% 1 <= nums.length <= 10^... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
"""2022-10-21 Runtime: 760 ms, faster than 81.02% Memory Usage: 27.6 MB, less than 14.95% 1 <= nums.length <= 10^5 -10^9 <= nums[i] <= 10^9 0 <= k <= 10^5"""
<|body_0|>
def containsNearbyDuplicate2... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
"""2022-10-21 Runtime: 760 ms, faster than 81.02% Memory Usage: 27.6 MB, less than 14.95% 1 <= nums.length <= 10^5 -10^9 <= nums[i] <= 10^9 0 <= k <= 10^5"""
pos = {}
for i, num in enumerate(nums):
... | the_stack_v2_python_sparse | src/219-ContainsDuplicateII.py | Jiezhi/myleetcode | train | 1 | |
43501b5ca26c2c99f92219b6b560d1a259d482be | [
"print('---test login---')\ndata = {'username': 'laiye', 'password': '123123', 'is_keep_login': True}\nres = auth_login(data)\ncon = res.content.decode()\ncon_data = json.loads(con)\nreturn con_data['data']['jwt_token']",
"print('---setup_class---')\nos.environ['token'] = self.auth_login(None)\ndata = {'agent_nam... | <|body_start_0|>
print('---test login---')
data = {'username': 'laiye', 'password': '123123', 'is_keep_login': True}
res = auth_login(data)
con = res.content.decode()
con_data = json.loads(con)
return con_data['data']['jwt_token']
<|end_body_0|>
<|body_start_1|>
... | TestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCase:
def auth_login(self):
"""登陆"""
<|body_0|>
def setup_class(self):
"""创建app ,创建意图"""
<|body_1|>
def teardown_class(self):
"""删除app"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
print('---test login---')
data = ... | stack_v2_sparse_classes_75kplus_train_002916 | 2,308 | no_license | [
{
"docstring": "登陆",
"name": "auth_login",
"signature": "def auth_login(self)"
},
{
"docstring": "创建app ,创建意图",
"name": "setup_class",
"signature": "def setup_class(self)"
},
{
"docstring": "删除app",
"name": "teardown_class",
"signature": "def teardown_class(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_006476 | Implement the Python class `TestCase` described below.
Class description:
Implement the TestCase class.
Method signatures and docstrings:
- def auth_login(self): 登陆
- def setup_class(self): 创建app ,创建意图
- def teardown_class(self): 删除app | Implement the Python class `TestCase` described below.
Class description:
Implement the TestCase class.
Method signatures and docstrings:
- def auth_login(self): 登陆
- def setup_class(self): 创建app ,创建意图
- def teardown_class(self): 删除app
<|skeleton|>
class TestCase:
def auth_login(self):
"""登陆"""
... | 6962db54256a5d0544ae021c06b82ef1d0dc29df | <|skeleton|>
class TestCase:
def auth_login(self):
"""登陆"""
<|body_0|>
def setup_class(self):
"""创建app ,创建意图"""
<|body_1|>
def teardown_class(self):
"""删除app"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCase:
def auth_login(self):
"""登陆"""
print('---test login---')
data = {'username': 'laiye', 'password': '123123', 'is_keep_login': True}
res = auth_login(data)
con = res.content.decode()
con_data = json.loads(con)
return con_data['data']['jwt_token']... | the_stack_v2_python_sparse | case/test_node/test_case_node.py | lg-cmd/MyCode | train | 0 | |
e8b12d44519e5dec08d1b11b0d3100cfca71fd4c | [
"super().__init__()\nself.hidden_layers = nn.ModuleList([nn.Linear(input_size, hidden_layers[0])])\nlayer_sizes = zip(hidden_layers[:-1], hidden_layers[1:])\nself.hidden_layers.extend([nn.Linear(h1, h2) for h1, h2 in layer_sizes])\nself.output = nn.Linear(hidden_layers[-1], output_size)\nself.dropout = nn.Dropout(p... | <|body_start_0|>
super().__init__()
self.hidden_layers = nn.ModuleList([nn.Linear(input_size, hidden_layers[0])])
layer_sizes = zip(hidden_layers[:-1], hidden_layers[1:])
self.hidden_layers.extend([nn.Linear(h1, h2) for h1, h2 in layer_sizes])
self.output = nn.Linear(hidden_layer... | Network | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Network:
def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5):
"""Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input output_size: integer, size of the output layer hidden_layers: list of integers, the si... | stack_v2_sparse_classes_75kplus_train_002917 | 4,436 | no_license | [
{
"docstring": "Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input output_size: integer, size of the output layer hidden_layers: list of integers, the sizes of the hidden layers drop_p: float between 0 and 1, dropout probability",
"name": "_... | 2 | stack_v2_sparse_classes_30k_train_008106 | Implement the Python class `Network` described below.
Class description:
Implement the Network class.
Method signatures and docstrings:
- def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5): Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of ... | Implement the Python class `Network` described below.
Class description:
Implement the Network class.
Method signatures and docstrings:
- def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5): Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of ... | 768edc4a5526c8972fec66c6a71a38c0b24a1451 | <|skeleton|>
class Network:
def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5):
"""Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input output_size: integer, size of the output layer hidden_layers: list of integers, the si... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Network:
def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5):
"""Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input output_size: integer, size of the output layer hidden_layers: list of integers, the sizes of the hid... | the_stack_v2_python_sparse | 人工智能/python人工智能课程/part_4_Neural_Networks/learning_with_PyTorch/p4_Inference and Validation.py | faker-hong/testOne | train | 1 | |
653f8a7c40eea359e9acf8dd6d9f805c328953e6 | [
"super().__init__()\nself._mab = MAB(embedding_dim=embedding_dim, num_heads=num_heads, multihead_init_type=multihead_init_type, use_layer_norm=use_layer_norm, elementwise_transform_type=elementwise_transform_type)\nself._seed_vectors = torch.nn.Parameter(torch.Tensor(1, num_seed_vectors, embedding_dim))\ntorch.nn.i... | <|body_start_0|>
super().__init__()
self._mab = MAB(embedding_dim=embedding_dim, num_heads=num_heads, multihead_init_type=multihead_init_type, use_layer_norm=use_layer_norm, elementwise_transform_type=elementwise_transform_type)
self._seed_vectors = torch.nn.Parameter(torch.Tensor(1, num_seed_ve... | Pooling by Multihead Attention block of the Set Transformer model. | PMA | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PMA:
"""Pooling by Multihead Attention block of the Set Transformer model."""
def __init__(self, embedding_dim: int, num_heads: int, num_seed_vectors: int, multihead_init_type: SetTransformer.MultiheadInitType, use_layer_norm: bool, elementwise_transform_type: SetTransformer.ElementwiseTrans... | stack_v2_sparse_classes_75kplus_train_002918 | 24,284 | permissive | [
{
"docstring": "Args: embedding_dim: Dimension of the input data. num_heads: Number of heads. num_seed_vectors: Number of seed vectors. multihead_init_type: How linear layers in torch.nn.MultiheadAttention are initialised. use_layer_norm: Whether layer normalisation should be used in MAB blocks. elementwise_tra... | 2 | null | Implement the Python class `PMA` described below.
Class description:
Pooling by Multihead Attention block of the Set Transformer model.
Method signatures and docstrings:
- def __init__(self, embedding_dim: int, num_heads: int, num_seed_vectors: int, multihead_init_type: SetTransformer.MultiheadInitType, use_layer_nor... | Implement the Python class `PMA` described below.
Class description:
Pooling by Multihead Attention block of the Set Transformer model.
Method signatures and docstrings:
- def __init__(self, embedding_dim: int, num_heads: int, num_seed_vectors: int, multihead_init_type: SetTransformer.MultiheadInitType, use_layer_nor... | de9c6191f716e5777f711bfec0eb6749c5062ec8 | <|skeleton|>
class PMA:
"""Pooling by Multihead Attention block of the Set Transformer model."""
def __init__(self, embedding_dim: int, num_heads: int, num_seed_vectors: int, multihead_init_type: SetTransformer.MultiheadInitType, use_layer_norm: bool, elementwise_transform_type: SetTransformer.ElementwiseTrans... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PMA:
"""Pooling by Multihead Attention block of the Set Transformer model."""
def __init__(self, embedding_dim: int, num_heads: int, num_seed_vectors: int, multihead_init_type: SetTransformer.MultiheadInitType, use_layer_norm: bool, elementwise_transform_type: SetTransformer.ElementwiseTransformType, use... | the_stack_v2_python_sparse | azua/models/transformer_set_encoder.py | Dragon-Dane/project-azua | train | 0 |
0504396c672adf8c76f0899828d9d03eab5c282d | [
"food_dict = {}\nfor food in orm.Food.objects.all():\n con = Consumption()\n con.in_event = Event(food.in_event.id)\n con.order = food.order\n con.quantity = food.quantity\n if food.name not in food_dict:\n en = Energy()\n en.name = food.name\n en.kcal = food.kcal\n en.kca... | <|body_start_0|>
food_dict = {}
for food in orm.Food.objects.all():
con = Consumption()
con.in_event = Event(food.in_event.id)
con.order = food.order
con.quantity = food.quantity
if food.name not in food_dict:
en = Energy()
... | Migration | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards migration here"""
<|body_0|>
def backwards(self, orm):
"""Write your backwards migration here"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
food_dict = {}
for food in orm.Food.obje... | stack_v2_sparse_classes_75kplus_train_002919 | 3,153 | permissive | [
{
"docstring": "Write your forwards migration here",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Write your backwards migration here",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008607 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards migration here
- def backwards(self, orm): Write your backwards migration here | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards migration here
- def backwards(self, orm): Write your backwards migration here
<|skeleton|>
class Migration:
def forwards(sel... | af535fda8e113e9dcdac31216852e35a01d3b950 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards migration here"""
<|body_0|>
def backwards(self, orm):
"""Write your backwards migration here"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Migration:
def forwards(self, orm):
"""Write your forwards migration here"""
food_dict = {}
for food in orm.Food.objects.all():
con = Consumption()
con.in_event = Event(food.in_event.id)
con.order = food.order
con.quantity = food.quantity... | the_stack_v2_python_sparse | kcal/migrations/0003_load_energy_model.py | ftrain/django-ftrain | train | 2 | |
8cf3a70ee87241c6df31c06ad7deaff45f313f02 | [
"t = [x.split(',') for x in transactions]\nt.sort(key=lambda x: (x[0], int(x[1])))\ni = 0\nret = set()\nwhile i < len(t):\n j = i + 1\n duplicate = False\n while j < len(t) and t[j][0] == t[i][0] and (int(t[j][1]) - int(t[i][1]) <= 60):\n if t[j][3] != t[i][3]:\n duplicate = True\n ... | <|body_start_0|>
t = [x.split(',') for x in transactions]
t.sort(key=lambda x: (x[0], int(x[1])))
i = 0
ret = set()
while i < len(t):
j = i + 1
duplicate = False
while j < len(t) and t[j][0] == t[i][0] and (int(t[j][1]) - int(t[i][1]) <= 60):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invalidTransactions(self, transactions):
""":type transactions: List[str] :rtype: List[str]"""
<|body_0|>
def invalidTransactions(self, transactions):
""":type transactions: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_002920 | 3,895 | no_license | [
{
"docstring": ":type transactions: List[str] :rtype: List[str]",
"name": "invalidTransactions",
"signature": "def invalidTransactions(self, transactions)"
},
{
"docstring": ":type transactions: List[str] :rtype: List[str]",
"name": "invalidTransactions",
"signature": "def invalidTransac... | 2 | stack_v2_sparse_classes_30k_train_033593 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invalidTransactions(self, transactions): :type transactions: List[str] :rtype: List[str]
- def invalidTransactions(self, transactions): :type transactions: List[str] :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invalidTransactions(self, transactions): :type transactions: List[str] :rtype: List[str]
- def invalidTransactions(self, transactions): :type transactions: List[str] :rtype: ... | 988b427b95181ca5a6da081b9ca790fbb4f8c252 | <|skeleton|>
class Solution:
def invalidTransactions(self, transactions):
""":type transactions: List[str] :rtype: List[str]"""
<|body_0|>
def invalidTransactions(self, transactions):
""":type transactions: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def invalidTransactions(self, transactions):
""":type transactions: List[str] :rtype: List[str]"""
t = [x.split(',') for x in transactions]
t.sort(key=lambda x: (x[0], int(x[1])))
i = 0
ret = set()
while i < len(t):
j = i + 1
du... | the_stack_v2_python_sparse | problem1169.py | meetgadoya/leetcode-sol | train | 1 | |
72d46a2ca7007048dd4f5f854854aa81c50b0d50 | [
"self.layer_creator = layer_creator\nself.num_layer = num_layer\nself.num_channel = num_channel\nself.num_filter = num_filter\nself.window_size = window_size\nself.stride_size = stride_size\nself.padding_type = padding_type\nself.activation = activation\nself.dropout = dropout\nself.layer_dropout = layer_dropout\ns... | <|body_start_0|>
self.layer_creator = layer_creator
self.num_layer = num_layer
self.num_channel = num_channel
self.num_filter = num_filter
self.window_size = window_size
self.stride_size = stride_size
self.padding_type = padding_type
self.activation = acti... | stacked multi-window convolution layer | StackedMultiConv | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StackedMultiConv:
"""stacked multi-window convolution layer"""
def __init__(self, layer_creator, num_layer, num_channel, num_filter, window_size, stride_size, padding_type, activation, dropout, layer_dropout=None, layer_norm=False, residual_connect=False, use_bias=True, num_gpus=1, default_g... | stack_v2_sparse_classes_75kplus_train_002921 | 24,662 | permissive | [
{
"docstring": "initialize stacked multi-window convolution layer",
"name": "__init__",
"signature": "def __init__(self, layer_creator, num_layer, num_channel, num_filter, window_size, stride_size, padding_type, activation, dropout, layer_dropout=None, layer_norm=False, residual_connect=False, use_bias=... | 2 | stack_v2_sparse_classes_30k_train_035589 | Implement the Python class `StackedMultiConv` described below.
Class description:
stacked multi-window convolution layer
Method signatures and docstrings:
- def __init__(self, layer_creator, num_layer, num_channel, num_filter, window_size, stride_size, padding_type, activation, dropout, layer_dropout=None, layer_norm... | Implement the Python class `StackedMultiConv` described below.
Class description:
stacked multi-window convolution layer
Method signatures and docstrings:
- def __init__(self, layer_creator, num_layer, num_channel, num_filter, window_size, stride_size, padding_type, activation, dropout, layer_dropout=None, layer_norm... | 05fcbec15e359e3db86af6c3798c13be8a6c58ee | <|skeleton|>
class StackedMultiConv:
"""stacked multi-window convolution layer"""
def __init__(self, layer_creator, num_layer, num_channel, num_filter, window_size, stride_size, padding_type, activation, dropout, layer_dropout=None, layer_norm=False, residual_connect=False, use_bias=True, num_gpus=1, default_g... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StackedMultiConv:
"""stacked multi-window convolution layer"""
def __init__(self, layer_creator, num_layer, num_channel, num_filter, window_size, stride_size, padding_type, activation, dropout, layer_dropout=None, layer_norm=False, residual_connect=False, use_bias=True, num_gpus=1, default_gpu_id=0, regu... | the_stack_v2_python_sparse | sequence_labeling/layer/convolution.py | stevezheng23/sequence_labeling_tf | train | 18 |
7de39e16669a62ff5d747c243d3a5c2a136bacd7 | [
"intlists = []\nif paramstr.strip():\n remainder = paramstr\n while remainder:\n liststr, sep, remainder = remainder.partition(';;')\n intlists.append(_str_to_intlist(liststr))\nreturn intlists",
"intliststrs = []\nfor ints in val:\n intliststrs.append(';'.join(['%d' % ii for ii in ints]))\... | <|body_start_0|>
intlists = []
if paramstr.strip():
remainder = paramstr
while remainder:
liststr, sep, remainder = remainder.partition(';;')
intlists.append(_str_to_intlist(liststr))
return intlists
<|end_body_0|>
<|body_start_1|>
... | A configuration type for a list of integer lists. | IntListList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntListList:
"""A configuration type for a list of integer lists."""
def _string_to_value(self, paramstr):
"""Parse 'paramstr' as a list of integer lists. The format must be <int>[;<int>...][;;<int>[;<int>...]...]."""
<|body_0|>
def _value_to_string(self, val):
"... | stack_v2_sparse_classes_75kplus_train_002922 | 11,479 | no_license | [
{
"docstring": "Parse 'paramstr' as a list of integer lists. The format must be <int>[;<int>...][;;<int>[;<int>...]...].",
"name": "_string_to_value",
"signature": "def _string_to_value(self, paramstr)"
},
{
"docstring": "Return a normalized version of the value.",
"name": "_value_to_string"... | 2 | null | Implement the Python class `IntListList` described below.
Class description:
A configuration type for a list of integer lists.
Method signatures and docstrings:
- def _string_to_value(self, paramstr): Parse 'paramstr' as a list of integer lists. The format must be <int>[;<int>...][;;<int>[;<int>...]...].
- def _value... | Implement the Python class `IntListList` described below.
Class description:
A configuration type for a list of integer lists.
Method signatures and docstrings:
- def _string_to_value(self, paramstr): Parse 'paramstr' as a list of integer lists. The format must be <int>[;<int>...][;;<int>[;<int>...]...].
- def _value... | c62683bc599f821fa3cc0528309e0a3bd8735baa | <|skeleton|>
class IntListList:
"""A configuration type for a list of integer lists."""
def _string_to_value(self, paramstr):
"""Parse 'paramstr' as a list of integer lists. The format must be <int>[;<int>...][;;<int>[;<int>...]...]."""
<|body_0|>
def _value_to_string(self, val):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IntListList:
"""A configuration type for a list of integer lists."""
def _string_to_value(self, paramstr):
"""Parse 'paramstr' as a list of integer lists. The format must be <int>[;<int>...][;;<int>[;<int>...]...]."""
intlists = []
if paramstr.strip():
remainder = para... | the_stack_v2_python_sparse | coast_guard/cleaners/config_types.py | danielreardon/MeerGuard | train | 2 |
89ca7bb8b95d73767adb01b27cb30f2df7d70b59 | [
"super().__init__()\nif hls_config is not None:\n self.hls_config = hls_config\nelse:\n self.hls_config = HLSConfig(True)\nself.hls_plugin_manager = HighLevelSynthesisPluginManager()\nself._coupling_map = coupling_map\nself._target = target\nself._use_qubit_indices = use_qubit_indices\nif target is not None:\... | <|body_start_0|>
super().__init__()
if hls_config is not None:
self.hls_config = hls_config
else:
self.hls_config = HLSConfig(True)
self.hls_plugin_manager = HighLevelSynthesisPluginManager()
self._coupling_map = coupling_map
self._target = target
... | Synthesize higher-level objects using synthesis plugins. Synthesis plugins apply synthesis methods specified in the high-level-synthesis config (refer to the documentation for :class:`~.HLSConfig`). As an example, let us assume that ``op_a`` and ``op_b`` are names of two higher-level objects, that ``op_a``-objects have... | HighLevelSynthesis | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HighLevelSynthesis:
"""Synthesize higher-level objects using synthesis plugins. Synthesis plugins apply synthesis methods specified in the high-level-synthesis config (refer to the documentation for :class:`~.HLSConfig`). As an example, let us assume that ``op_a`` and ``op_b`` are names of two hi... | stack_v2_sparse_classes_75kplus_train_002923 | 18,210 | permissive | [
{
"docstring": "HighLevelSynthesis initializer. Args: hls_config: Optional, the high-level-synthesis config that specifies synthesis methods and parameters for various high-level-objects in the circuit. If it is not specified, the default synthesis methods and parameters will be used. coupling_map: Optional, di... | 2 | stack_v2_sparse_classes_30k_train_046293 | Implement the Python class `HighLevelSynthesis` described below.
Class description:
Synthesize higher-level objects using synthesis plugins. Synthesis plugins apply synthesis methods specified in the high-level-synthesis config (refer to the documentation for :class:`~.HLSConfig`). As an example, let us assume that ``... | Implement the Python class `HighLevelSynthesis` described below.
Class description:
Synthesize higher-level objects using synthesis plugins. Synthesis plugins apply synthesis methods specified in the high-level-synthesis config (refer to the documentation for :class:`~.HLSConfig`). As an example, let us assume that ``... | 0b51250e219ca303654fc28a318c21366584ccd3 | <|skeleton|>
class HighLevelSynthesis:
"""Synthesize higher-level objects using synthesis plugins. Synthesis plugins apply synthesis methods specified in the high-level-synthesis config (refer to the documentation for :class:`~.HLSConfig`). As an example, let us assume that ``op_a`` and ``op_b`` are names of two hi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HighLevelSynthesis:
"""Synthesize higher-level objects using synthesis plugins. Synthesis plugins apply synthesis methods specified in the high-level-synthesis config (refer to the documentation for :class:`~.HLSConfig`). As an example, let us assume that ``op_a`` and ``op_b`` are names of two higher-level ob... | the_stack_v2_python_sparse | qiskit/transpiler/passes/synthesis/high_level_synthesis.py | 1ucian0/qiskit-terra | train | 6 |
aa6a8f1c6289666ed47724cb99dfeb397c81a9ab | [
"assert 'name' in kwargs, 'Key name must be provided in kwargs'\nself.command_function = command_function\nself.command_args = command_args or ()\nself.command_kwargs = command_kwargs or {}\nself.kwargs = kwargs\nself.stdout = stdout if stdout else sys.stdout\nself.stderr = stderr if stderr else sys.stderr",
"fro... | <|body_start_0|>
assert 'name' in kwargs, 'Key name must be provided in kwargs'
self.command_function = command_function
self.command_args = command_args or ()
self.command_kwargs = command_kwargs or {}
self.kwargs = kwargs
self.stdout = stdout if stdout else sys.stdout
... | A helper class that runs a django command and logs details about its run into DB. | CommandExecutor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandExecutor:
"""A helper class that runs a django command and logs details about its run into DB."""
def __init__(self, command_function, command_args=None, command_kwargs=None, stdout=None, stderr=None, **kwargs):
"""Initializes the command logger. Arguments: command_function: C... | stack_v2_sparse_classes_75kplus_train_002924 | 2,853 | permissive | [
{
"docstring": "Initializes the command logger. Arguments: command_function: Callable that implements the command. stdout: Custom stream where command's standard output will be written. stderr: Custom stream where command's error output will be written. **kwargs: Keyword arguments passed to CommandLog model.",
... | 2 | stack_v2_sparse_classes_30k_train_040855 | Implement the Python class `CommandExecutor` described below.
Class description:
A helper class that runs a django command and logs details about its run into DB.
Method signatures and docstrings:
- def __init__(self, command_function, command_args=None, command_kwargs=None, stdout=None, stderr=None, **kwargs): Initi... | Implement the Python class `CommandExecutor` described below.
Class description:
A helper class that runs a django command and logs details about its run into DB.
Method signatures and docstrings:
- def __init__(self, command_function, command_args=None, command_kwargs=None, stdout=None, stderr=None, **kwargs): Initi... | 630d4605a8f69cf89ebc83e8f889064247f8167e | <|skeleton|>
class CommandExecutor:
"""A helper class that runs a django command and logs details about its run into DB."""
def __init__(self, command_function, command_args=None, command_kwargs=None, stdout=None, stderr=None, **kwargs):
"""Initializes the command logger. Arguments: command_function: C... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommandExecutor:
"""A helper class that runs a django command and logs details about its run into DB."""
def __init__(self, command_function, command_args=None, command_kwargs=None, stdout=None, stderr=None, **kwargs):
"""Initializes the command logger. Arguments: command_function: Callable that ... | the_stack_v2_python_sparse | security/command.py | druids/django-security | train | 11 |
90f14d070d258975a54b4f771d28faaa58766233 | [
"if pPCSample is None:\n self.equalSamples_ = True\n self.pcSamples_ = PointCloud(pGrid.sortedPts_, pGrid.sortedBatchIds_, pGrid.batchSize_)\nelse:\n self.equalSamples_ = False\n self.pcSamples_ = pPCSample\nself.grid_ = pGrid\nself.radii_ = pRadii\nself.pMaxNeighbors_ = pMaxNeighbors\nself.samplesNeigh... | <|body_start_0|>
if pPCSample is None:
self.equalSamples_ = True
self.pcSamples_ = PointCloud(pGrid.sortedPts_, pGrid.sortedBatchIds_, pGrid.batchSize_)
else:
self.equalSamples_ = False
self.pcSamples_ = pPCSample
self.grid_ = pGrid
self.ra... | Class to represent a neighborhood of points. Attributes: pcSamples_ (PointCloud): Samples point cloud. grid_ (Grid): Regular grid data structure. radii_ (float tensor d): Radii used to select the neighbors. samplesNeighRanges_ (int tensor n): End of the ranges for each sample. neighbors_ (int tensor mx2): Indices of th... | Neighborhood | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Neighborhood:
"""Class to represent a neighborhood of points. Attributes: pcSamples_ (PointCloud): Samples point cloud. grid_ (Grid): Regular grid data structure. radii_ (float tensor d): Radii used to select the neighbors. samplesNeighRanges_ (int tensor n): End of the ranges for each sample. ne... | stack_v2_sparse_classes_75kplus_train_002925 | 3,651 | permissive | [
{
"docstring": "Constructor. Args: pGrid (Grid): Regular grid data structure. pRadii (float tensor d): Radii used to select the neighbors. pPCSample (PointCloud): Samples point cloud. If None, the sorted points from the grid will be used. pMaxNeighbors (int): Maximum number of neighbors per sample.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_008591 | Implement the Python class `Neighborhood` described below.
Class description:
Class to represent a neighborhood of points. Attributes: pcSamples_ (PointCloud): Samples point cloud. grid_ (Grid): Regular grid data structure. radii_ (float tensor d): Radii used to select the neighbors. samplesNeighRanges_ (int tensor n)... | Implement the Python class `Neighborhood` described below.
Class description:
Class to represent a neighborhood of points. Attributes: pcSamples_ (PointCloud): Samples point cloud. grid_ (Grid): Regular grid data structure. radii_ (float tensor d): Radii used to select the neighbors. samplesNeighRanges_ (int tensor n)... | 9c79ea000c20088fa48234f1868e42883a9b5a21 | <|skeleton|>
class Neighborhood:
"""Class to represent a neighborhood of points. Attributes: pcSamples_ (PointCloud): Samples point cloud. grid_ (Grid): Regular grid data structure. radii_ (float tensor d): Radii used to select the neighbors. samplesNeighRanges_ (int tensor n): End of the ranges for each sample. ne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Neighborhood:
"""Class to represent a neighborhood of points. Attributes: pcSamples_ (PointCloud): Samples point cloud. grid_ (Grid): Regular grid data structure. radii_ (float tensor d): Radii used to select the neighbors. samplesNeighRanges_ (int tensor n): End of the ranges for each sample. neighbors_ (int... | the_stack_v2_python_sparse | IEProtLib/pc/Neighborhood.py | sailfish009/IEConv_proteins | train | 0 |
3d02f5488f6dffaadffb0f97c6ebf8a446595497 | [
"self.snake = collections.deque([(0, 0)])\nself.dirs = {'U': (1, 0), 'D': (-1, 0), 'R': (0, 1), 'L': (0, -1)}\nself.width = width\nself.height = height\nself.food_p = 0\nself.snake_set = set([(0, 0)])\nself.food = food",
"new_row = self.snake[0][0] + self.dirs[direction][0]\nnew_col = self.snake[0][1] + self.dirs... | <|body_start_0|>
self.snake = collections.deque([(0, 0)])
self.dirs = {'U': (1, 0), 'D': (-1, 0), 'R': (0, 1), 'L': (0, -1)}
self.width = width
self.height = height
self.food_p = 0
self.snake_set = set([(0, 0)])
self.food = food
<|end_body_0|>
<|body_start_1|>
... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_75kplus_train_002926 | 2,003 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_026416 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | 14d973b09e6add87320900c34379667c93d9b538 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | 353.py | HONGWENHT/LeetCode | train | 0 | |
d04078859519e46724648f30515c693a7a9b8e0b | [
"for letter in letters:\n if letter > target:\n return letter\nreturn letters[0]",
"lo = 0\nhi = len(letters)\nwhile lo < hi:\n mid = lo + (hi - lo) / 2\n if letters[mid] <= target:\n lo = mid + 1\n else:\n hi = mid\nreturn letters[lo % len(letters)]"
] | <|body_start_0|>
for letter in letters:
if letter > target:
return letter
return letters[0]
<|end_body_0|>
<|body_start_1|>
lo = 0
hi = len(letters)
while lo < hi:
mid = lo + (hi - lo) / 2
if letters[mid] <= target:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreatestLetter(self, letters, target):
"""从头搜到尾 :type letters: List[str] :type target: str :rtype: str"""
<|body_0|>
def nextGreatestLetter(self, letters, target):
"""二分查找 :type letters: List[str] :type target: str :rtype: str"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_002927 | 1,942 | no_license | [
{
"docstring": "从头搜到尾 :type letters: List[str] :type target: str :rtype: str",
"name": "nextGreatestLetter",
"signature": "def nextGreatestLetter(self, letters, target)"
},
{
"docstring": "二分查找 :type letters: List[str] :type target: str :rtype: str",
"name": "nextGreatestLetter",
"signat... | 2 | stack_v2_sparse_classes_30k_train_007282 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreatestLetter(self, letters, target): 从头搜到尾 :type letters: List[str] :type target: str :rtype: str
- def nextGreatestLetter(self, letters, target): 二分查找 :type letters: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreatestLetter(self, letters, target): 从头搜到尾 :type letters: List[str] :type target: str :rtype: str
- def nextGreatestLetter(self, letters, target): 二分查找 :type letters: L... | 860590239da0618c52967a55eda8d6bbe00bfa96 | <|skeleton|>
class Solution:
def nextGreatestLetter(self, letters, target):
"""从头搜到尾 :type letters: List[str] :type target: str :rtype: str"""
<|body_0|>
def nextGreatestLetter(self, letters, target):
"""二分查找 :type letters: List[str] :type target: str :rtype: str"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def nextGreatestLetter(self, letters, target):
"""从头搜到尾 :type letters: List[str] :type target: str :rtype: str"""
for letter in letters:
if letter > target:
return letter
return letters[0]
def nextGreatestLetter(self, letters, target):
... | the_stack_v2_python_sparse | LeetCode/p0744/I/find-smallest-letter-greater-than-target.py | Ynjxsjmh/PracticeMakesPerfect | train | 0 | |
35bb14518b64c282b1745b4d35f8b2cd718ae89d | [
"self.session = session\nif api_version == AUTH_API_V2:\n from keystoneclient.v2_0 import client as keystone_client\nelif api_version == AUTH_API_V3:\n from keystoneclient.v3 import client as keystone_client\nelse:\n msg = 'The allowed values for api version are {} or {}'.format(AUTH_API_V2, AUTH_API_V3)\n... | <|body_start_0|>
self.session = session
if api_version == AUTH_API_V2:
from keystoneclient.v2_0 import client as keystone_client
elif api_version == AUTH_API_V3:
from keystoneclient.v3 import client as keystone_client
else:
msg = 'The allowed values fo... | This class provides methods to manage authorization. | AuthorizationManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthorizationManager:
"""This class provides methods to manage authorization."""
def __init__(self, identity_url, api_version):
"""Default contructor. :param identity_url: The url of the Keystone service. :param api_version: The version of the Kesytone API to be used. :return: None""... | stack_v2_sparse_classes_75kplus_train_002928 | 8,315 | permissive | [
{
"docstring": "Default contructor. :param identity_url: The url of the Keystone service. :param api_version: The version of the Kesytone API to be used. :return: None",
"name": "__init__",
"signature": "def __init__(self, identity_url, api_version)"
},
{
"docstring": "Init the variables related... | 5 | null | Implement the Python class `AuthorizationManager` described below.
Class description:
This class provides methods to manage authorization.
Method signatures and docstrings:
- def __init__(self, identity_url, api_version): Default contructor. :param identity_url: The url of the Keystone service. :param api_version: Th... | Implement the Python class `AuthorizationManager` described below.
Class description:
This class provides methods to manage authorization.
Method signatures and docstrings:
- def __init__(self, identity_url, api_version): Default contructor. :param identity_url: The url of the Keystone service. :param api_version: Th... | 5ad0c80e12b9384473f31bf336015c75cf02a2a2 | <|skeleton|>
class AuthorizationManager:
"""This class provides methods to manage authorization."""
def __init__(self, identity_url, api_version):
"""Default contructor. :param identity_url: The url of the Keystone service. :param api_version: The version of the Kesytone API to be used. :return: None""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthorizationManager:
"""This class provides methods to manage authorization."""
def __init__(self, identity_url, api_version):
"""Default contructor. :param identity_url: The url of the Keystone service. :param api_version: The version of the Kesytone API to be used. :return: None"""
sel... | the_stack_v2_python_sparse | fiwareglancesync/app/mod_auth/AuthorizationManager.py | telefonicaid/fiware-glancesync | train | 0 |
9f0f52ea2fe0bb44bc42bde40b86eb0864d74726 | [
"super(Include, self).pre_initialize()\nself.parent.insert_children(self, self.objects)\nfor obj in self.objects:\n obj.initialize()",
"if self.is_active:\n old = event.old\n new = event.new\n with new.children_event_context():\n with old.children_event_context():\n if new is None:\n... | <|body_start_0|>
super(Include, self).pre_initialize()
self.parent.insert_children(self, self.objects)
for obj in self.objects:
obj.initialize()
<|end_body_0|>
<|body_start_1|>
if self.is_active:
old = event.old
new = event.new
with new.ch... | An object which dynamically inserts children into its parent. The `Include` object is used to cleanly and easily insert objects into the children of its parent. `Object` instances assigned to the `objects` list of the `Include` will be parented with the parent of the `Include`. The parent of an `Include` should be an i... | Include | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Include:
"""An object which dynamically inserts children into its parent. The `Include` object is used to cleanly and easily insert objects into the children of its parent. `Object` instances assigned to the `objects` list of the `Include` will be parented with the parent of the `Include`. The pa... | stack_v2_sparse_classes_75kplus_train_002929 | 4,145 | permissive | [
{
"docstring": "A pre-initialization handler. This method will add the include objects to the parent of the include and ensure that they are initialized.",
"name": "pre_initialize",
"signature": "def pre_initialize(self)"
},
{
"docstring": "Handle a `ParentEvent` for the Include. If the object s... | 4 | stack_v2_sparse_classes_30k_train_015675 | Implement the Python class `Include` described below.
Class description:
An object which dynamically inserts children into its parent. The `Include` object is used to cleanly and easily insert objects into the children of its parent. `Object` instances assigned to the `objects` list of the `Include` will be parented w... | Implement the Python class `Include` described below.
Class description:
An object which dynamically inserts children into its parent. The `Include` object is used to cleanly and easily insert objects into the children of its parent. `Object` instances assigned to the `objects` list of the `Include` will be parented w... | 424bba29219de58fe9e47196de6763de8b2009f2 | <|skeleton|>
class Include:
"""An object which dynamically inserts children into its parent. The `Include` object is used to cleanly and easily insert objects into the children of its parent. `Object` instances assigned to the `objects` list of the `Include` will be parented with the parent of the `Include`. The pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Include:
"""An object which dynamically inserts children into its parent. The `Include` object is used to cleanly and easily insert objects into the children of its parent. `Object` instances assigned to the `objects` list of the `Include` will be parented with the parent of the `Include`. The parent of an `I... | the_stack_v2_python_sparse | enaml/core/include.py | enthought/enaml | train | 17 |
498d53a6768480a7186f5d0917fadda2b020d05d | [
"if as_datetime and 'detect_types' not in kwargs:\n kwargs['detect_types'] = sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES\nsuper(ConnectionsTable, self).__init__(database, **kwargs)\nself.execute(f'CREATE TABLE IF NOT EXISTS {self.NAME} (pid INTEGER PRIMARY KEY AUTOINCREMENT, datetime DATETIME NOT NULL, ip_a... | <|body_start_0|>
if as_datetime and 'detect_types' not in kwargs:
kwargs['detect_types'] = sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES
super(ConnectionsTable, self).__init__(database, **kwargs)
self.execute(f'CREATE TABLE IF NOT EXISTS {self.NAME} (pid INTEGER PRIMARY KEY AUTOIN... | ConnectionsTable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectionsTable:
def __init__(self, *, database=None, as_datetime=False, **kwargs):
"""The database table for devices that have connected to the Network :class:`~msl.network.manager.Manager`. Parameters ---------- database : :class:`str`, optional The path to the database file, or ``':m... | stack_v2_sparse_classes_75kplus_train_002930 | 20,753 | permissive | [
{
"docstring": "The database table for devices that have connected to the Network :class:`~msl.network.manager.Manager`. Parameters ---------- database : :class:`str`, optional The path to the database file, or ``':memory:'`` to open a connection to a database that resides in RAM instead of on disk. If :data:`N... | 3 | stack_v2_sparse_classes_30k_val_002313 | Implement the Python class `ConnectionsTable` described below.
Class description:
Implement the ConnectionsTable class.
Method signatures and docstrings:
- def __init__(self, *, database=None, as_datetime=False, **kwargs): The database table for devices that have connected to the Network :class:`~msl.network.manager.... | Implement the Python class `ConnectionsTable` described below.
Class description:
Implement the ConnectionsTable class.
Method signatures and docstrings:
- def __init__(self, *, database=None, as_datetime=False, **kwargs): The database table for devices that have connected to the Network :class:`~msl.network.manager.... | 700f003b2f27cada274ec8bfaccaf1bfa6acb0f0 | <|skeleton|>
class ConnectionsTable:
def __init__(self, *, database=None, as_datetime=False, **kwargs):
"""The database table for devices that have connected to the Network :class:`~msl.network.manager.Manager`. Parameters ---------- database : :class:`str`, optional The path to the database file, or ``':m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConnectionsTable:
def __init__(self, *, database=None, as_datetime=False, **kwargs):
"""The database table for devices that have connected to the Network :class:`~msl.network.manager.Manager`. Parameters ---------- database : :class:`str`, optional The path to the database file, or ``':memory:'`` to o... | the_stack_v2_python_sparse | msl/network/database.py | MSLNZ/msl-network | train | 0 | |
4b1ef9e795504d365ec3bc384fd2df38f55a0af8 | [
"self.verbose = verbose\nself.X_train, self.Y_train = (None, None)\nself.X_test, self.Y_test = (None, None)\nself.X_valid, self.Y_valid = (None, None)\nself.is_classification = None\nself.is_multilabel = None\nself.metric = None\nself.max_runtime = None\nself.categorical_features = None",
"print('Read:' + file_na... | <|body_start_0|>
self.verbose = verbose
self.X_train, self.Y_train = (None, None)
self.X_test, self.Y_test = (None, None)
self.X_valid, self.Y_valid = (None, None)
self.is_classification = None
self.is_multilabel = None
self.metric = None
self.max_runtime ... | Load data from multiple sources and formants | DataManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataManager:
"""Load data from multiple sources and formants"""
def __init__(self, verbose=0):
"""Construct the DataManager Keyword Arguments: verbose {bool} -- Whether to print stuff. (default: {0})"""
<|body_0|>
def read_data(self, file_name, test_split=0.0, is_classif... | stack_v2_sparse_classes_75kplus_train_002931 | 11,145 | permissive | [
{
"docstring": "Construct the DataManager Keyword Arguments: verbose {bool} -- Whether to print stuff. (default: {0})",
"name": "__init__",
"signature": "def __init__(self, verbose=0)"
},
{
"docstring": "Read the data. Arguments: file_name {str} -- The name of the file to load. Different Readers... | 6 | null | Implement the Python class `DataManager` described below.
Class description:
Load data from multiple sources and formants
Method signatures and docstrings:
- def __init__(self, verbose=0): Construct the DataManager Keyword Arguments: verbose {bool} -- Whether to print stuff. (default: {0})
- def read_data(self, file_... | Implement the Python class `DataManager` described below.
Class description:
Load data from multiple sources and formants
Method signatures and docstrings:
- def __init__(self, verbose=0): Construct the DataManager Keyword Arguments: verbose {bool} -- Whether to print stuff. (default: {0})
- def read_data(self, file_... | 6e72d5ba088981b89371f29773d243a211a4d068 | <|skeleton|>
class DataManager:
"""Load data from multiple sources and formants"""
def __init__(self, verbose=0):
"""Construct the DataManager Keyword Arguments: verbose {bool} -- Whether to print stuff. (default: {0})"""
<|body_0|>
def read_data(self, file_name, test_split=0.0, is_classif... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataManager:
"""Load data from multiple sources and formants"""
def __init__(self, verbose=0):
"""Construct the DataManager Keyword Arguments: verbose {bool} -- Whether to print stuff. (default: {0})"""
self.verbose = verbose
self.X_train, self.Y_train = (None, None)
self.... | the_stack_v2_python_sparse | autoPyTorch/data_management/data_manager.py | ArlindKadra/Auto-PyTorch | train | 1 |
d823d2b71050c5aedc7c0db9bb806fb53766f58b | [
"super().__init__()\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)\nself.F = tf.keras.layers.Dense(vocab)",
"attention = SelfAttention(s_prev.shape[1])\nctx, weights = attention(... | <|body_start_0|>
super().__init__()
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
self.F = tf.keras.layers.Dense(vocab)
<|end_body_0|>
<|body_start_1|>
... | RNN Decoder class | RNNDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""RNN Decoder class"""
def __init__(self, vocab, embedding, units, batch):
"""Constructor Args: W - a Dense layer with units units, to be applied to the previous decoder hidden state U - a Dense layer with units units, to be applied to the encoder hidden states V - a Den... | stack_v2_sparse_classes_75kplus_train_002932 | 2,009 | no_license | [
{
"docstring": "Constructor Args: W - a Dense layer with units units, to be applied to the previous decoder hidden state U - a Dense layer with units units, to be applied to the encoder hidden states V - a Dense layer with 1 units, to be applied to the tanh of the sum of the outputs of W and U",
"name": "__... | 2 | stack_v2_sparse_classes_30k_train_007893 | Implement the Python class `RNNDecoder` described below.
Class description:
RNN Decoder class
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Constructor Args: W - a Dense layer with units units, to be applied to the previous decoder hidden state U - a Dense layer with units un... | Implement the Python class `RNNDecoder` described below.
Class description:
RNN Decoder class
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Constructor Args: W - a Dense layer with units units, to be applied to the previous decoder hidden state U - a Dense layer with units un... | 2eb7965900fd018f4092d2fb1e2055d35ba4899e | <|skeleton|>
class RNNDecoder:
"""RNN Decoder class"""
def __init__(self, vocab, embedding, units, batch):
"""Constructor Args: W - a Dense layer with units units, to be applied to the previous decoder hidden state U - a Dense layer with units units, to be applied to the encoder hidden states V - a Den... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNDecoder:
"""RNN Decoder class"""
def __init__(self, vocab, embedding, units, batch):
"""Constructor Args: W - a Dense layer with units units, to be applied to the previous decoder hidden state U - a Dense layer with units units, to be applied to the encoder hidden states V - a Dense layer with... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | s0m35h1t/holbertonschool-machine_learning | train | 0 |
e8fd645788a7ad5242c7bbe4e36fd0abcfb71464 | [
"if arg == 'no_default':\n value = None\nelse:\n value = cls._get_from_registry(arg)\nreturn value",
"if value is None:\n value = cls._default_value\nif isinstance(value, str):\n if value == 'no_default':\n value = None\n else:\n value = cls._get_from_registry(value)\nelif not isinsta... | <|body_start_0|>
if arg == 'no_default':
value = None
else:
value = cls._get_from_registry(arg)
return value
<|end_body_0|>
<|body_start_1|>
if value is None:
value = cls._default_value
if isinstance(value, str):
if value == 'no_de... | The default cosmology to use. To change it:: >>> from astropy.cosmology import default_cosmology, WMAP7 >>> with default_cosmology.set(WMAP7): ... # WMAP7 cosmology in effect ... pass Or, you may use a string:: >>> with default_cosmology.set('WMAP7'): ... # WMAP7 cosmology in effect ... pass To get the default cosmolog... | default_cosmology | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class default_cosmology:
"""The default cosmology to use. To change it:: >>> from astropy.cosmology import default_cosmology, WMAP7 >>> with default_cosmology.set(WMAP7): ... # WMAP7 cosmology in effect ... pass Or, you may use a string:: >>> with default_cosmology.set('WMAP7'): ... # WMAP7 cosmology i... | stack_v2_sparse_classes_75kplus_train_002933 | 4,954 | permissive | [
{
"docstring": "Return a cosmology instance from a string.",
"name": "get_cosmology_from_string",
"signature": "def get_cosmology_from_string(cls, arg)"
},
{
"docstring": "Return a Cosmology given a value. Parameters ---------- value : None, str, or `~astropy.cosmology.Cosmology` Returns -------... | 3 | stack_v2_sparse_classes_30k_train_027985 | Implement the Python class `default_cosmology` described below.
Class description:
The default cosmology to use. To change it:: >>> from astropy.cosmology import default_cosmology, WMAP7 >>> with default_cosmology.set(WMAP7): ... # WMAP7 cosmology in effect ... pass Or, you may use a string:: >>> with default_cosmolog... | Implement the Python class `default_cosmology` described below.
Class description:
The default cosmology to use. To change it:: >>> from astropy.cosmology import default_cosmology, WMAP7 >>> with default_cosmology.set(WMAP7): ... # WMAP7 cosmology in effect ... pass Or, you may use a string:: >>> with default_cosmolog... | 53188c39a23c33b72df5850ec59e31886f84e29d | <|skeleton|>
class default_cosmology:
"""The default cosmology to use. To change it:: >>> from astropy.cosmology import default_cosmology, WMAP7 >>> with default_cosmology.set(WMAP7): ... # WMAP7 cosmology in effect ... pass Or, you may use a string:: >>> with default_cosmology.set('WMAP7'): ... # WMAP7 cosmology i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class default_cosmology:
"""The default cosmology to use. To change it:: >>> from astropy.cosmology import default_cosmology, WMAP7 >>> with default_cosmology.set(WMAP7): ... # WMAP7 cosmology in effect ... pass Or, you may use a string:: >>> with default_cosmology.set('WMAP7'): ... # WMAP7 cosmology in effect ... ... | the_stack_v2_python_sparse | astropy/cosmology/realizations.py | astropy/astropy | train | 3,922 |
8f45220716cfdf9575c2221252cdea69b86ef8c6 | [
"RAMSTKWorkView.__init__(self, controller, module='Function')\nself._lst_assess_labels[1].append(_(u'Total Mode Count:'))\nself._function_id = None\nself.txtModeCount = ramstk.RAMSTKEntry(width=125, editable=False, bold=True, tooltip=_(u'Displays the total number of failure modes associated with the selected Functi... | <|body_start_0|>
RAMSTKWorkView.__init__(self, controller, module='Function')
self._lst_assess_labels[1].append(_(u'Total Mode Count:'))
self._function_id = None
self.txtModeCount = ramstk.RAMSTKEntry(width=125, editable=False, bold=True, tooltip=_(u'Displays the total number of failure ... | Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_id: the ID of the Function currently being displayed. | AssessmentResults | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssessmentResults:
"""Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_id: the ID of the Function currently bei... | stack_v2_sparse_classes_75kplus_train_002934 | 16,082 | permissive | [
{
"docstring": "Initialize the Work View for the Function package. :param controller: the RAMSTK master data controller instance. :type controller: :class:`ramstk.RAMSTK.RAMSTK`",
"name": "__init__",
"signature": "def __init__(self, controller, **kwargs)"
},
{
"docstring": "Load the Function Ass... | 4 | stack_v2_sparse_classes_30k_train_016281 | Implement the Python class `AssessmentResults` described below.
Class description:
Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_i... | Implement the Python class `AssessmentResults` described below.
Class description:
Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_i... | 488ffed8b842399ddcae93007de6c6f1dda23d05 | <|skeleton|>
class AssessmentResults:
"""Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_id: the ID of the Function currently bei... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssessmentResults:
"""Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_id: the ID of the Function currently being displayed.... | the_stack_v2_python_sparse | src/ramstk/gui/gtk/workviews/Function.py | JmiXIII/ramstk | train | 0 |
2afd2f4bf803f1c7b94b4dfeaea99c6b90f336a1 | [
"p = super().Params()\np.Define('input_dims', 0, 'Depth of the input to the network.')\np.Define('epsilon', 1e-06, 'Tiny value to guard rsqrt.')\np.Define('direct_scale', True, 'Whether to apply scale directly without a +1.0. Var is initialized to 1.0 instead when true. This makes the weight compatible with the imp... | <|body_start_0|>
p = super().Params()
p.Define('input_dims', 0, 'Depth of the input to the network.')
p.Define('epsilon', 1e-06, 'Tiny value to guard rsqrt.')
p.Define('direct_scale', True, 'Whether to apply scale directly without a +1.0. Var is initialized to 1.0 instead when true. This... | RMS normalization: https://arxiv.org/abs/1910.07467. | RmsNorm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RmsNorm:
"""RMS normalization: https://arxiv.org/abs/1910.07467."""
def Params(cls) -> InstantiableParams:
"""Returns the layer params with RMS Norm specific params."""
<|body_0|>
def create_layer_variables(self) -> None:
"""Creates RMS normalization variables.""... | stack_v2_sparse_classes_75kplus_train_002935 | 17,959 | permissive | [
{
"docstring": "Returns the layer params with RMS Norm specific params.",
"name": "Params",
"signature": "def Params(cls) -> InstantiableParams"
},
{
"docstring": "Creates RMS normalization variables.",
"name": "create_layer_variables",
"signature": "def create_layer_variables(self) -> N... | 3 | stack_v2_sparse_classes_30k_test_000797 | Implement the Python class `RmsNorm` described below.
Class description:
RMS normalization: https://arxiv.org/abs/1910.07467.
Method signatures and docstrings:
- def Params(cls) -> InstantiableParams: Returns the layer params with RMS Norm specific params.
- def create_layer_variables(self) -> None: Creates RMS norma... | Implement the Python class `RmsNorm` described below.
Class description:
RMS normalization: https://arxiv.org/abs/1910.07467.
Method signatures and docstrings:
- def Params(cls) -> InstantiableParams: Returns the layer params with RMS Norm specific params.
- def create_layer_variables(self) -> None: Creates RMS norma... | c00a74b260fcf6ba11199cc4a340c127d6616479 | <|skeleton|>
class RmsNorm:
"""RMS normalization: https://arxiv.org/abs/1910.07467."""
def Params(cls) -> InstantiableParams:
"""Returns the layer params with RMS Norm specific params."""
<|body_0|>
def create_layer_variables(self) -> None:
"""Creates RMS normalization variables.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RmsNorm:
"""RMS normalization: https://arxiv.org/abs/1910.07467."""
def Params(cls) -> InstantiableParams:
"""Returns the layer params with RMS Norm specific params."""
p = super().Params()
p.Define('input_dims', 0, 'Depth of the input to the network.')
p.Define('epsilon',... | the_stack_v2_python_sparse | lingvo/jax/layers/normalizations.py | tensorflow/lingvo | train | 2,963 |
eb90e6cd01b97c3c8dc0d6d859b269d6be558285 | [
"super(FilteredLeaveOneGroupOut, self).__init__()\nself.keep = keep\nself.example_ids = example_ids\nself._warned = False\nself.logger = logger if logger else logging.getLogger(__name__)",
"for train_index, test_index in super(FilteredLeaveOneGroupOut, self).split(X, y, groups):\n train_len = len(train_index)\... | <|body_start_0|>
super(FilteredLeaveOneGroupOut, self).__init__()
self.keep = keep
self.example_ids = example_ids
self._warned = False
self.logger = logger if logger else logging.getLogger(__name__)
<|end_body_0|>
<|body_start_1|>
for train_index, test_index in super(Fil... | Custom version ``LeaveOneGroupOut`` cross-validation iterator. This version only outputs indices of instances with IDs in a prespecified set. Parameters ---------- keep : Iterable[IdType] A set of IDs to keep. example_ids : numpy.ndarray, of length n_samples A list of example IDs. logger : Optional[logging.Logger], def... | FilteredLeaveOneGroupOut | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilteredLeaveOneGroupOut:
"""Custom version ``LeaveOneGroupOut`` cross-validation iterator. This version only outputs indices of instances with IDs in a prespecified set. Parameters ---------- keep : Iterable[IdType] A set of IDs to keep. example_ids : numpy.ndarray, of length n_samples A list of... | stack_v2_sparse_classes_75kplus_train_002936 | 47,118 | permissive | [
{
"docstring": "Initialize the model.",
"name": "__init__",
"signature": "def __init__(self, keep: Iterable[IdType], example_ids: np.ndarray, logger: Optional[logging.Logger]=None)"
},
{
"docstring": "Generate indices to split data into training and test set. Parameters ---------- X : numpy.ndar... | 2 | stack_v2_sparse_classes_30k_train_025648 | Implement the Python class `FilteredLeaveOneGroupOut` described below.
Class description:
Custom version ``LeaveOneGroupOut`` cross-validation iterator. This version only outputs indices of instances with IDs in a prespecified set. Parameters ---------- keep : Iterable[IdType] A set of IDs to keep. example_ids : numpy... | Implement the Python class `FilteredLeaveOneGroupOut` described below.
Class description:
Custom version ``LeaveOneGroupOut`` cross-validation iterator. This version only outputs indices of instances with IDs in a prespecified set. Parameters ---------- keep : Iterable[IdType] A set of IDs to keep. example_ids : numpy... | b10ce3963620d8679a1ce82ccb2268f7ea5fb9c9 | <|skeleton|>
class FilteredLeaveOneGroupOut:
"""Custom version ``LeaveOneGroupOut`` cross-validation iterator. This version only outputs indices of instances with IDs in a prespecified set. Parameters ---------- keep : Iterable[IdType] A set of IDs to keep. example_ids : numpy.ndarray, of length n_samples A list of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FilteredLeaveOneGroupOut:
"""Custom version ``LeaveOneGroupOut`` cross-validation iterator. This version only outputs indices of instances with IDs in a prespecified set. Parameters ---------- keep : Iterable[IdType] A set of IDs to keep. example_ids : numpy.ndarray, of length n_samples A list of example IDs.... | the_stack_v2_python_sparse | skll/learner/utils.py | EducationalTestingService/skll | train | 320 |
42cd832772cd2640bd60da85999dc6c83a2696ef | [
"super().__init__(self.SCHEMA_NAME)\nself.redfish['@odata.type'] = self.get_odata_type()\nself.redfish['Name'] = 'Resource Zone Collection'\nself.redfish['Members@odata.count'] = len(zone_ids)\nself.redfish['Members'] = list()\nself._fill_redfish_members(zone_ids)\nself.redfish['@odata.context'] = '/redfish/v1/$met... | <|body_start_0|>
super().__init__(self.SCHEMA_NAME)
self.redfish['@odata.type'] = self.get_odata_type()
self.redfish['Name'] = 'Resource Zone Collection'
self.redfish['Members@odata.count'] = len(zone_ids)
self.redfish['Members'] = list()
self._fill_redfish_members(zone_i... | Creates a Zone Collection Redfish dict Populates self.redfish with some hardcoded ZoneCollection values and with the response of OneView. | ZoneCollection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZoneCollection:
"""Creates a Zone Collection Redfish dict Populates self.redfish with some hardcoded ZoneCollection values and with the response of OneView."""
def __init__(self, zone_ids):
"""ZoneCollection constructor Populates self.redfish with some hardcoded ZoneCollection values... | stack_v2_sparse_classes_75kplus_train_002937 | 2,261 | permissive | [
{
"docstring": "ZoneCollection constructor Populates self.redfish with some hardcoded ZoneCollection values and with the response of OneView. Args: zone_ids: Zone ids based on Oneview data",
"name": "__init__",
"signature": "def __init__(self, zone_ids)"
},
{
"docstring": "Mounts the list of Red... | 2 | null | Implement the Python class `ZoneCollection` described below.
Class description:
Creates a Zone Collection Redfish dict Populates self.redfish with some hardcoded ZoneCollection values and with the response of OneView.
Method signatures and docstrings:
- def __init__(self, zone_ids): ZoneCollection constructor Populat... | Implement the Python class `ZoneCollection` described below.
Class description:
Creates a Zone Collection Redfish dict Populates self.redfish with some hardcoded ZoneCollection values and with the response of OneView.
Method signatures and docstrings:
- def __init__(self, zone_ids): ZoneCollection constructor Populat... | ffc86ea0a9e5d192ab6a2fe21c1717957b55d1da | <|skeleton|>
class ZoneCollection:
"""Creates a Zone Collection Redfish dict Populates self.redfish with some hardcoded ZoneCollection values and with the response of OneView."""
def __init__(self, zone_ids):
"""ZoneCollection constructor Populates self.redfish with some hardcoded ZoneCollection values... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZoneCollection:
"""Creates a Zone Collection Redfish dict Populates self.redfish with some hardcoded ZoneCollection values and with the response of OneView."""
def __init__(self, zone_ids):
"""ZoneCollection constructor Populates self.redfish with some hardcoded ZoneCollection values and with the... | the_stack_v2_python_sparse | oneview_redfish_toolkit/api/zone_collection.py | shobhit-sinha/oneview-redfish-toolkit | train | 2 |
f7f0f40e4c7e3be96d5a121901d49344f01edff7 | [
"cleaned_data = self.cleaned_data\ntry:\n precio_costo = int(cleaned_data.get('precio_costo'))\n precio_venta = int(cleaned_data.get('precio_venta'))\nexcept (TypeError, ValueError):\n return cleaned_data\nif precio_costo >= precio_venta:\n msg = u'El Precio de costo debe ser menor que el precio de vent... | <|body_start_0|>
cleaned_data = self.cleaned_data
try:
precio_costo = int(cleaned_data.get('precio_costo'))
precio_venta = int(cleaned_data.get('precio_venta'))
except (TypeError, ValueError):
return cleaned_data
if precio_costo >= precio_venta:
... | PromocionForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PromocionForm:
def clean(self):
"""Método de validación personalizado que válida si el precio de costo no sea mayor que el precio de venta"""
<|body_0|>
def clean_codigo(self):
"""Verifica que campo único, quitando espacio en blanco"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_002938 | 14,795 | permissive | [
{
"docstring": "Método de validación personalizado que válida si el precio de costo no sea mayor que el precio de venta",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Verifica que campo único, quitando espacio en blanco",
"name": "clean_codigo",
"signature": "def cl... | 2 | stack_v2_sparse_classes_30k_train_016411 | Implement the Python class `PromocionForm` described below.
Class description:
Implement the PromocionForm class.
Method signatures and docstrings:
- def clean(self): Método de validación personalizado que válida si el precio de costo no sea mayor que el precio de venta
- def clean_codigo(self): Verifica que campo ún... | Implement the Python class `PromocionForm` described below.
Class description:
Implement the PromocionForm class.
Method signatures and docstrings:
- def clean(self): Método de validación personalizado que válida si el precio de costo no sea mayor que el precio de venta
- def clean_codigo(self): Verifica que campo ún... | 1420e305f41301b8548dfbbabfc64330b74403be | <|skeleton|>
class PromocionForm:
def clean(self):
"""Método de validación personalizado que válida si el precio de costo no sea mayor que el precio de venta"""
<|body_0|>
def clean_codigo(self):
"""Verifica que campo único, quitando espacio en blanco"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PromocionForm:
def clean(self):
"""Método de validación personalizado que válida si el precio de costo no sea mayor que el precio de venta"""
cleaned_data = self.cleaned_data
try:
precio_costo = int(cleaned_data.get('precio_costo'))
precio_venta = int(cleaned_da... | the_stack_v2_python_sparse | AlyMoly/mantenedor/forms.py | CreceLibre/alymoly | train | 0 | |
df1ad5bf0fbe3d0af12d91c8032c7acb994b3d5f | [
"score = Score.objects.filter(user_id=user_id, quiz_id=quiz_id)\nif score:\n return float(score[0].score)\nreturn -1",
"score = Score.objects.filter(quiz_id=quiz_id)\nif score:\n return round(score.aggregate(Avg('score'))['score__avg'], 2)\nreturn 0"
] | <|body_start_0|>
score = Score.objects.filter(user_id=user_id, quiz_id=quiz_id)
if score:
return float(score[0].score)
return -1
<|end_body_0|>
<|body_start_1|>
score = Score.objects.filter(quiz_id=quiz_id)
if score:
return round(score.aggregate(Avg('scor... | Score class, extends base Django model | Score | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Score:
"""Score class, extends base Django model"""
def get_score(quiz_id, user_id):
"""gets score value from database. Returns: score value if found, -1 otherwise."""
<|body_0|>
def get_avg_score(quiz_id):
"""calculates average score from database. Returns: aver... | stack_v2_sparse_classes_75kplus_train_002939 | 1,236 | no_license | [
{
"docstring": "gets score value from database. Returns: score value if found, -1 otherwise.",
"name": "get_score",
"signature": "def get_score(quiz_id, user_id)"
},
{
"docstring": "calculates average score from database. Returns: average score if there any scores for this quiz, 0 otherwise.",
... | 2 | stack_v2_sparse_classes_30k_train_039455 | Implement the Python class `Score` described below.
Class description:
Score class, extends base Django model
Method signatures and docstrings:
- def get_score(quiz_id, user_id): gets score value from database. Returns: score value if found, -1 otherwise.
- def get_avg_score(quiz_id): calculates average score from da... | Implement the Python class `Score` described below.
Class description:
Score class, extends base Django model
Method signatures and docstrings:
- def get_score(quiz_id, user_id): gets score value from database. Returns: score value if found, -1 otherwise.
- def get_avg_score(quiz_id): calculates average score from da... | c6895efcefe74b87fbcba6f501bb63a33c09072a | <|skeleton|>
class Score:
"""Score class, extends base Django model"""
def get_score(quiz_id, user_id):
"""gets score value from database. Returns: score value if found, -1 otherwise."""
<|body_0|>
def get_avg_score(quiz_id):
"""calculates average score from database. Returns: aver... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Score:
"""Score class, extends base Django model"""
def get_score(quiz_id, user_id):
"""gets score value from database. Returns: score value if found, -1 otherwise."""
score = Score.objects.filter(user_id=user_id, quiz_id=quiz_id)
if score:
return float(score[0].score)... | the_stack_v2_python_sparse | quiz_project/scores/models.py | Lv-474-Python/FirstAppTeemmer | train | 0 |
a59e727f26cd386bf30431e770a81364affa8fc9 | [
"for field, result in zip(self.fields, self.jac_results):\n py_result = lie.jac(field, self.x)\n self.assertEqual(result, py_result)",
"for field, result1, result2 in self.deriv_results:\n py_result1 = lie.lie_deriv(self.h, field, self.x)\n self.assertEqual(result1, py_result1)\n py_result2 = lie.l... | <|body_start_0|>
for field, result in zip(self.fields, self.jac_results):
py_result = lie.jac(field, self.x)
self.assertEqual(result, py_result)
<|end_body_0|>
<|body_start_1|>
for field, result1, result2 in self.deriv_results:
py_result1 = lie.lie_deriv(self.h, fiel... | KnownValues | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnownValues:
def testKnownValuesJac(self):
"""jac should give known result with known input"""
<|body_0|>
def testKnownValuesLie_Deriv(self):
"""lie_deriv should give known result with known input (also for higher order derivatives)"""
<|body_1|>
def tes... | stack_v2_sparse_classes_75kplus_train_002940 | 10,319 | no_license | [
{
"docstring": "jac should give known result with known input",
"name": "testKnownValuesJac",
"signature": "def testKnownValuesJac(self)"
},
{
"docstring": "lie_deriv should give known result with known input (also for higher order derivatives)",
"name": "testKnownValuesLie_Deriv",
"sign... | 4 | stack_v2_sparse_classes_30k_train_001798 | Implement the Python class `KnownValues` described below.
Class description:
Implement the KnownValues class.
Method signatures and docstrings:
- def testKnownValuesJac(self): jac should give known result with known input
- def testKnownValuesLie_Deriv(self): lie_deriv should give known result with known input (also ... | Implement the Python class `KnownValues` described below.
Class description:
Implement the KnownValues class.
Method signatures and docstrings:
- def testKnownValuesJac(self): jac should give known result with known input
- def testKnownValuesLie_Deriv(self): lie_deriv should give known result with known input (also ... | fd77bf2280ac12708fe9528f83dd82ea4b3b9c65 | <|skeleton|>
class KnownValues:
def testKnownValuesJac(self):
"""jac should give known result with known input"""
<|body_0|>
def testKnownValuesLie_Deriv(self):
"""lie_deriv should give known result with known input (also for higher order derivatives)"""
<|body_1|>
def tes... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KnownValues:
def testKnownValuesJac(self):
"""jac should give known result with known input"""
for field, result in zip(self.fields, self.jac_results):
py_result = lie.jac(field, self.x)
self.assertEqual(result, py_result)
def testKnownValuesLie_Deriv(self):
... | the_stack_v2_python_sparse | 20141114/pycontroltools/lietools/test_lietools.py | umfundii/OS_RT | train | 0 | |
270b8264182459660f446b1a3d744e9caca0a2aa | [
"if self.type != rest_methods.GET:\n raise NotImplementedError(\"Can't execute a service method that is not a GET\")\nmethod_url = url_override if url_override else self.resource.absolute_url()\nneeded_parameters = dict([(p.parameter, rest_method_parameters.reverse[p.parameter]) for p in self.parameters])\nparam... | <|body_start_0|>
if self.type != rest_methods.GET:
raise NotImplementedError("Can't execute a service method that is not a GET")
method_url = url_override if url_override else self.resource.absolute_url()
needed_parameters = dict([(p.parameter, rest_method_parameters.reverse[p.parame... | ResourceMethod | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceMethod:
def execute(self, received_parameters, url_override='', locale=None):
"""takes a dictionary of method parameters, executes the method and returns response"""
<|body_0|>
def execute_several(method_parameters_pairs, thread_number=8, locale=None):
"""See... | stack_v2_sparse_classes_75kplus_train_002941 | 8,747 | no_license | [
{
"docstring": "takes a dictionary of method parameters, executes the method and returns response",
"name": "execute",
"signature": "def execute(self, received_parameters, url_override='', locale=None)"
},
{
"docstring": "See execute(). given a list of tuples in the form (method, parameters), ex... | 2 | stack_v2_sparse_classes_30k_train_035453 | Implement the Python class `ResourceMethod` described below.
Class description:
Implement the ResourceMethod class.
Method signatures and docstrings:
- def execute(self, received_parameters, url_override='', locale=None): takes a dictionary of method parameters, executes the method and returns response
- def execute_... | Implement the Python class `ResourceMethod` described below.
Class description:
Implement the ResourceMethod class.
Method signatures and docstrings:
- def execute(self, received_parameters, url_override='', locale=None): takes a dictionary of method parameters, executes the method and returns response
- def execute_... | 891a8b38d72083d52d60995e06ad9e8d091e234b | <|skeleton|>
class ResourceMethod:
def execute(self, received_parameters, url_override='', locale=None):
"""takes a dictionary of method parameters, executes the method and returns response"""
<|body_0|>
def execute_several(method_parameters_pairs, thread_number=8, locale=None):
"""See... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourceMethod:
def execute(self, received_parameters, url_override='', locale=None):
"""takes a dictionary of method parameters, executes the method and returns response"""
if self.type != rest_methods.GET:
raise NotImplementedError("Can't execute a service method that is not a GE... | the_stack_v2_python_sparse | concierge/concierge/services_models.py | miguelvps/pi | train | 0 | |
8e52e48fc9e5bd4deb0a2a7f33481e16a68ef013 | [
"super().__init__()\nself.player = player\nself.spawnTime = 0\nself.disappear = False\npygame.sprite.Sprite.__init__(self)\nsprite_sheet = SpriteSheet('Golem.png')\nimage = sprite_sheet.get_image(29, 11, 101, 319)\nself.image = image\nself.rect = self.image.get_rect()\nself.rect.x = player.rect.x\nself.rect.y = -31... | <|body_start_0|>
super().__init__()
self.player = player
self.spawnTime = 0
self.disappear = False
pygame.sprite.Sprite.__init__(self)
sprite_sheet = SpriteSheet('Golem.png')
image = sprite_sheet.get_image(29, 11, 101, 319)
self.image = image
self.... | Punch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Punch:
def __init__(self, player):
""":param player: The player object This initializes the punch Variables: self.player: The player object self.spawnTime: The amout of time the punch will stay on screen self.disappear: True to allow the punch to disappear sprite_sheet: The spritesheet t... | stack_v2_sparse_classes_75kplus_train_002942 | 2,449 | no_license | [
{
"docstring": ":param player: The player object This initializes the punch Variables: self.player: The player object self.spawnTime: The amout of time the punch will stay on screen self.disappear: True to allow the punch to disappear sprite_sheet: The spritesheet to where the custom spries came from image: Hol... | 2 | stack_v2_sparse_classes_30k_train_024518 | Implement the Python class `Punch` described below.
Class description:
Implement the Punch class.
Method signatures and docstrings:
- def __init__(self, player): :param player: The player object This initializes the punch Variables: self.player: The player object self.spawnTime: The amout of time the punch will stay ... | Implement the Python class `Punch` described below.
Class description:
Implement the Punch class.
Method signatures and docstrings:
- def __init__(self, player): :param player: The player object This initializes the punch Variables: self.player: The player object self.spawnTime: The amout of time the punch will stay ... | 56fbcfc786dfc373f477270468f06e31b6271749 | <|skeleton|>
class Punch:
def __init__(self, player):
""":param player: The player object This initializes the punch Variables: self.player: The player object self.spawnTime: The amout of time the punch will stay on screen self.disappear: True to allow the punch to disappear sprite_sheet: The spritesheet t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Punch:
def __init__(self, player):
""":param player: The player object This initializes the punch Variables: self.player: The player object self.spawnTime: The amout of time the punch will stay on screen self.disappear: True to allow the punch to disappear sprite_sheet: The spritesheet to where the cu... | the_stack_v2_python_sparse | Doki Doki Island/bossAttacks/golem/golAttack3.py | cashpop5000/DokiProject | train | 0 | |
03d427f92bf9b5b55d19e59fd55729241db995a1 | [
"excluded_ports = set(['TruePort', 'FalsePort', 'TrueOutputPorts', 'FalseOutputPorts'])\nfor port_name, connector_list in self.inputPorts.iteritems():\n if port_name not in excluded_ports:\n for connector in connector_list:\n connector.obj.update()\nfor port_name, connectorList in copy.copy(sel... | <|body_start_0|>
excluded_ports = set(['TruePort', 'FalsePort', 'TrueOutputPorts', 'FalseOutputPorts'])
for port_name, connector_list in self.inputPorts.iteritems():
if port_name not in excluded_ports:
for connector in connector_list:
connector.obj.update(... | The If Module alows the user to choose the part of the workflow to be executed through the use of a condition. | If | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class If:
"""The If Module alows the user to choose the part of the workflow to be executed through the use of a condition."""
def update_upstream(self):
"""A modified version of the update_upstream method."""
<|body_0|>
def compute(self):
"""The compute method for the... | stack_v2_sparse_classes_75kplus_train_002943 | 7,772 | permissive | [
{
"docstring": "A modified version of the update_upstream method.",
"name": "update_upstream",
"signature": "def update_upstream(self)"
},
{
"docstring": "The compute method for the If module.",
"name": "compute",
"signature": "def compute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038344 | Implement the Python class `If` described below.
Class description:
The If Module alows the user to choose the part of the workflow to be executed through the use of a condition.
Method signatures and docstrings:
- def update_upstream(self): A modified version of the update_upstream method.
- def compute(self): The c... | Implement the Python class `If` described below.
Class description:
The If Module alows the user to choose the part of the workflow to be executed through the use of a condition.
Method signatures and docstrings:
- def update_upstream(self): A modified version of the update_upstream method.
- def compute(self): The c... | 93f1e5d375ee1e870f9bad699a22c9aafb954090 | <|skeleton|>
class If:
"""The If Module alows the user to choose the part of the workflow to be executed through the use of a condition."""
def update_upstream(self):
"""A modified version of the update_upstream method."""
<|body_0|>
def compute(self):
"""The compute method for the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class If:
"""The If Module alows the user to choose the part of the workflow to be executed through the use of a condition."""
def update_upstream(self):
"""A modified version of the update_upstream method."""
excluded_ports = set(['TruePort', 'FalsePort', 'TrueOutputPorts', 'FalseOutputPorts']... | the_stack_v2_python_sparse | vistrails/packages/controlflow/conditional.py | alexmavr/VisTrails | train | 1 |
3aba6aa9e4795f157e89b4b3bf5f188091d6b390 | [
"super().__init__(data, *args, **kwargs)\nif user is None:\n raise TypeError(\"'user' argument must not be None\")\nself.user = user",
"if not self.user.check_password(self.cleaned_data['password']):\n raise forms.ValidationError(_('Please enter the correct password!'))\nreturn self.cleaned_data['password']... | <|body_start_0|>
super().__init__(data, *args, **kwargs)
if user is None:
raise TypeError("'user' argument must not be None")
self.user = user
<|end_body_0|>
<|body_start_1|>
if not self.user.check_password(self.cleaned_data['password']):
raise forms.ValidationEr... | Simple form with one password field for confirmation when deleting a Team. | DeleteForm | [
"MIT",
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteForm:
"""Simple form with one password field for confirmation when deleting a Team."""
def __init__(self, data=None, *args, user=None, **kwargs):
"""Custom initializer which takes the user account to be deleted as an additional argument."""
<|body_0|>
def clean_pas... | stack_v2_sparse_classes_75kplus_train_002944 | 8,844 | permissive | [
{
"docstring": "Custom initializer which takes the user account to be deleted as an additional argument.",
"name": "__init__",
"signature": "def __init__(self, data=None, *args, user=None, **kwargs)"
},
{
"docstring": "Ensures that the entered password is valid for the specified user account.",
... | 2 | stack_v2_sparse_classes_30k_train_046667 | Implement the Python class `DeleteForm` described below.
Class description:
Simple form with one password field for confirmation when deleting a Team.
Method signatures and docstrings:
- def __init__(self, data=None, *args, user=None, **kwargs): Custom initializer which takes the user account to be deleted as an addi... | Implement the Python class `DeleteForm` described below.
Class description:
Simple form with one password field for confirmation when deleting a Team.
Method signatures and docstrings:
- def __init__(self, data=None, *args, user=None, **kwargs): Custom initializer which takes the user account to be deleted as an addi... | 03e0d0377e9687c60dd0454c1c1dc0efb5151bff | <|skeleton|>
class DeleteForm:
"""Simple form with one password field for confirmation when deleting a Team."""
def __init__(self, data=None, *args, user=None, **kwargs):
"""Custom initializer which takes the user account to be deleted as an additional argument."""
<|body_0|>
def clean_pas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeleteForm:
"""Simple form with one password field for confirmation when deleting a Team."""
def __init__(self, data=None, *args, user=None, **kwargs):
"""Custom initializer which takes the user account to be deleted as an additional argument."""
super().__init__(data, *args, **kwargs)
... | the_stack_v2_python_sparse | src/ctf_gameserver/web/registration/forms.py | fausecteam/ctf-gameserver | train | 43 |
ae1705e3167c07dc55778e586b7615303f8a204c | [
"global user_selection\nuser_selection = input(f'\\n\\nWelcome to an informational directory about a book.\\n Here are your options: \\n Type 1 to find out about the cover\\n Type 2 to uncover the title \\n Type 3 to view the author\\n Type 4 to find out how many pages their are\\... | <|body_start_0|>
global user_selection
user_selection = input(f'\n\nWelcome to an informational directory about a book.\n Here are your options: \n Type 1 to find out about the cover\n Type 2 to uncover the title \n Type 3 to view the author\n Type 4 to find out how ma... | Has two menus, directory and exit menu. | Menu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menu:
"""Has two menus, directory and exit menu."""
def directory(self):
"""Main directory for the program, this function also checks for valid input"""
<|body_0|>
def exit_menu(self):
"""Exit menu to check if the user wants to leave"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_002945 | 2,240 | no_license | [
{
"docstring": "Main directory for the program, this function also checks for valid input",
"name": "directory",
"signature": "def directory(self)"
},
{
"docstring": "Exit menu to check if the user wants to leave",
"name": "exit_menu",
"signature": "def exit_menu(self)"
}
] | 2 | null | Implement the Python class `Menu` described below.
Class description:
Has two menus, directory and exit menu.
Method signatures and docstrings:
- def directory(self): Main directory for the program, this function also checks for valid input
- def exit_menu(self): Exit menu to check if the user wants to leave | Implement the Python class `Menu` described below.
Class description:
Has two menus, directory and exit menu.
Method signatures and docstrings:
- def directory(self): Main directory for the program, this function also checks for valid input
- def exit_menu(self): Exit menu to check if the user wants to leave
<|skele... | 00aa54b2c0cc6d5a773e0bb8d084c71b5ddcf275 | <|skeleton|>
class Menu:
"""Has two menus, directory and exit menu."""
def directory(self):
"""Main directory for the program, this function also checks for valid input"""
<|body_0|>
def exit_menu(self):
"""Exit menu to check if the user wants to leave"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Menu:
"""Has two menus, directory and exit menu."""
def directory(self):
"""Main directory for the program, this function also checks for valid input"""
global user_selection
user_selection = input(f'\n\nWelcome to an informational directory about a book.\n Here are your op... | the_stack_v2_python_sparse | Python_2/assignment_1/book.py | Trent-Farley/All-Code | train | 1 |
55411e7880092d9bf3cd6fabee5fcf03da3530a7 | [
"self._args = args\nself._kwargs = kwargs\nself._template = template\nif not self._template:\n self._template = '{asctime} {message}'",
"self._kwargs['message'] = record.message\nif '{asctime}' in self._template:\n lt = time.localtime(record.index)\n self._kwargs['asctime'] = time.strftime(self._datefmt,... | <|body_start_0|>
self._args = args
self._kwargs = kwargs
self._template = template
if not self._template:
self._template = '{asctime} {message}'
<|end_body_0|>
<|body_start_1|>
self._kwargs['message'] = record.message
if '{asctime}' in self._template:
... | Class specifying how to format a Record. | Formatter | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Formatter:
"""Class specifying how to format a Record."""
def __init__(self, template=None, *args, **kwargs):
"""Initializes formatter. Args: template: String template which can contain placeholders for arguments in args, kwargs or supported attributes. *args: Replacement field for p... | stack_v2_sparse_classes_75kplus_train_002946 | 7,866 | permissive | [
{
"docstring": "Initializes formatter. Args: template: String template which can contain placeholders for arguments in args, kwargs or supported attributes. *args: Replacement field for positional argument. **kwargs: Replacement field for keyword argument.",
"name": "__init__",
"signature": "def __init_... | 2 | stack_v2_sparse_classes_30k_train_011269 | Implement the Python class `Formatter` described below.
Class description:
Class specifying how to format a Record.
Method signatures and docstrings:
- def __init__(self, template=None, *args, **kwargs): Initializes formatter. Args: template: String template which can contain placeholders for arguments in args, kwarg... | Implement the Python class `Formatter` described below.
Class description:
Class specifying how to format a Record.
Method signatures and docstrings:
- def __init__(self, template=None, *args, **kwargs): Initializes formatter. Args: template: String template which can contain placeholders for arguments in args, kwarg... | e71f21b9b4b9b839f5093301974a45545dad2691 | <|skeleton|>
class Formatter:
"""Class specifying how to format a Record."""
def __init__(self, template=None, *args, **kwargs):
"""Initializes formatter. Args: template: String template which can contain placeholders for arguments in args, kwargs or supported attributes. *args: Replacement field for p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Formatter:
"""Class specifying how to format a Record."""
def __init__(self, template=None, *args, **kwargs):
"""Initializes formatter. Args: template: String template which can contain placeholders for arguments in args, kwargs or supported attributes. *args: Replacement field for positional arg... | the_stack_v2_python_sparse | third_party/catapult/dashboard/dashboard/quick_logger.py | zenoalbisser/chromium | train | 0 |
7bd72cf3778d6311e0102715cdddfbd6c8bd130f | [
"self._flag_n = False\nself.__cached__.clear()\nBUFID = info.bufid\nFO = info.fo\nIHL = info.ihl\nMF = info.mf\nTL = info.tl\nif not FO and (not MF):\n if BUFID in self._buffer:\n self._dtgram.extend(self.submit(self._buffer.pop(BUFID), bufid=BUFID))\n return\nif BUFID not in self._buffer:\n sel... | <|body_start_0|>
self._flag_n = False
self.__cached__.clear()
BUFID = info.bufid
FO = info.fo
IHL = info.ihl
MF = info.mf
TL = info.tl
if not FO and (not MF):
if BUFID in self._buffer:
self._dtgram.extend(self.submit(self._buffe... | Reassembly for IP payload. Args: strict: if return all datagrams (including those not implemented) when submit *args: Arbitrary positional arguments. **kwargs: Arbitrary keyword arguments. Important: This class is not intended to be instantiated directly, but rather used as a base class for the protocol-aware reassembl... | IP | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IP:
"""Reassembly for IP payload. Args: strict: if return all datagrams (including those not implemented) when submit *args: Arbitrary positional arguments. **kwargs: Arbitrary keyword arguments. Important: This class is not intended to be instantiated directly, but rather used as a base class fo... | stack_v2_sparse_classes_75kplus_train_002947 | 6,372 | permissive | [
{
"docstring": "Reassembly procedure. Arguments: info: info dict of packets to be reassembled",
"name": "reassembly",
"signature": "def reassembly(self, info: 'Packet[AT]') -> 'None'"
},
{
"docstring": "Submit reassembled payload. Arguments: buf: buffer dict of reassembled packets bufid: buffer ... | 2 | stack_v2_sparse_classes_30k_test_001118 | Implement the Python class `IP` described below.
Class description:
Reassembly for IP payload. Args: strict: if return all datagrams (including those not implemented) when submit *args: Arbitrary positional arguments. **kwargs: Arbitrary keyword arguments. Important: This class is not intended to be instantiated direc... | Implement the Python class `IP` described below.
Class description:
Reassembly for IP payload. Args: strict: if return all datagrams (including those not implemented) when submit *args: Arbitrary positional arguments. **kwargs: Arbitrary keyword arguments. Important: This class is not intended to be instantiated direc... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class IP:
"""Reassembly for IP payload. Args: strict: if return all datagrams (including those not implemented) when submit *args: Arbitrary positional arguments. **kwargs: Arbitrary keyword arguments. Important: This class is not intended to be instantiated directly, but rather used as a base class fo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IP:
"""Reassembly for IP payload. Args: strict: if return all datagrams (including those not implemented) when submit *args: Arbitrary positional arguments. **kwargs: Arbitrary keyword arguments. Important: This class is not intended to be instantiated directly, but rather used as a base class for the protoco... | the_stack_v2_python_sparse | pcapkit/foundation/reassembly/ip.py | JarryShaw/PyPCAPKit | train | 204 |
81b8e26b34bb9608030d522a626fc988576dee4b | [
"hook_name, key = value.split('::')\nwarnings.warn(cls.DEPRECATION_MSG, DeprecationWarning)\nLOGGER.warning(cls.DEPRECATION_MSG)\nreturn ('{}.{}'.format(hook_name, key), {})",
"try:\n query, args = cls.parse(value)\nexcept ValueError:\n query, args = cls.legacy_parse(value)\nresult = context.hook_data.find(... | <|body_start_0|>
hook_name, key = value.split('::')
warnings.warn(cls.DEPRECATION_MSG, DeprecationWarning)
LOGGER.warning(cls.DEPRECATION_MSG)
return ('{}.{}'.format(hook_name, key), {})
<|end_body_0|>
<|body_start_1|>
try:
query, args = cls.parse(value)
exce... | Hook data lookup. | HookDataLookup | [
"BSD-2-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HookDataLookup:
"""Hook data lookup."""
def legacy_parse(cls, value):
"""Retain support for legacy lookup syntax. Args: value (str): Parameter(s) given to this lookup. Format of value: <hook_name>::<key>"""
<|body_0|>
def handle(cls, value, context=None, provider=None, *... | stack_v2_sparse_classes_75kplus_train_002948 | 2,074 | permissive | [
{
"docstring": "Retain support for legacy lookup syntax. Args: value (str): Parameter(s) given to this lookup. Format of value: <hook_name>::<key>",
"name": "legacy_parse",
"signature": "def legacy_parse(cls, value)"
},
{
"docstring": "Return the data from ``hook_data``. Args: value (str): Param... | 2 | stack_v2_sparse_classes_30k_train_003606 | Implement the Python class `HookDataLookup` described below.
Class description:
Hook data lookup.
Method signatures and docstrings:
- def legacy_parse(cls, value): Retain support for legacy lookup syntax. Args: value (str): Parameter(s) given to this lookup. Format of value: <hook_name>::<key>
- def handle(cls, value... | Implement the Python class `HookDataLookup` described below.
Class description:
Hook data lookup.
Method signatures and docstrings:
- def legacy_parse(cls, value): Retain support for legacy lookup syntax. Args: value (str): Parameter(s) given to this lookup. Format of value: <hook_name>::<key>
- def handle(cls, value... | 94aebff4f83b294653192a1b74111f6a9f114de2 | <|skeleton|>
class HookDataLookup:
"""Hook data lookup."""
def legacy_parse(cls, value):
"""Retain support for legacy lookup syntax. Args: value (str): Parameter(s) given to this lookup. Format of value: <hook_name>::<key>"""
<|body_0|>
def handle(cls, value, context=None, provider=None, *... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HookDataLookup:
"""Hook data lookup."""
def legacy_parse(cls, value):
"""Retain support for legacy lookup syntax. Args: value (str): Parameter(s) given to this lookup. Format of value: <hook_name>::<key>"""
hook_name, key = value.split('::')
warnings.warn(cls.DEPRECATION_MSG, Depr... | the_stack_v2_python_sparse | runway/cfngin/lookups/handlers/hook_data.py | edgarpoce/runway | train | 1 |
9eea9815dce16707bdd5af12cb194067fb0260ee | [
"user = UserDB.objects(user_id=id)\nif not user:\n return json.dumps({'Answer': 'There is not an user with the user_id: ' + id})\nelse:\n a = []\n for u in user:\n user_id = u['id']\n name = u['name'].replace('\\\\', '')\n email = u['email'].replace('\\\\', '')\n roles = u['role... | <|body_start_0|>
user = UserDB.objects(user_id=id)
if not user:
return json.dumps({'Answer': 'There is not an user with the user_id: ' + id})
else:
a = []
for u in user:
user_id = u['id']
name = u['name'].replace('\\', '')
... | Method for user with an especific user_id | UserServiceID | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserServiceID:
"""Method for user with an especific user_id"""
def get(self, id):
"""get the user with <user_id>"""
<|body_0|>
def put(self, id):
"""the user with <user_id> is going to be update"""
<|body_1|>
def delete(self, id):
"""the user... | stack_v2_sparse_classes_75kplus_train_002949 | 5,491 | no_license | [
{
"docstring": "get the user with <user_id>",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "the user with <user_id> is going to be update",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "the user with <user_id> is going to be deleted",
... | 3 | stack_v2_sparse_classes_30k_train_040586 | Implement the Python class `UserServiceID` described below.
Class description:
Method for user with an especific user_id
Method signatures and docstrings:
- def get(self, id): get the user with <user_id>
- def put(self, id): the user with <user_id> is going to be update
- def delete(self, id): the user with <user_id>... | Implement the Python class `UserServiceID` described below.
Class description:
Method for user with an especific user_id
Method signatures and docstrings:
- def get(self, id): get the user with <user_id>
- def put(self, id): the user with <user_id> is going to be update
- def delete(self, id): the user with <user_id>... | 9543352519e09bc96182730c2b4f950d3725ab1e | <|skeleton|>
class UserServiceID:
"""Method for user with an especific user_id"""
def get(self, id):
"""get the user with <user_id>"""
<|body_0|>
def put(self, id):
"""the user with <user_id> is going to be update"""
<|body_1|>
def delete(self, id):
"""the user... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserServiceID:
"""Method for user with an especific user_id"""
def get(self, id):
"""get the user with <user_id>"""
user = UserDB.objects(user_id=id)
if not user:
return json.dumps({'Answer': 'There is not an user with the user_id: ' + id})
else:
a ... | the_stack_v2_python_sparse | Users/Services/UserServices.py | dfriveros11/Arquisoft | train | 0 |
76c1fc1abe352e504572fab4f499a8e9bcb1144d | [
"self.create_and_verify_stack('single/basic_api')\nfirst_dep_ids = self.get_stack_deployment_ids()\nself.assertEqual(len(first_dep_ids), 1)\nself.set_template_resource_property('MyApi', 'DefinitionUri', self.get_s3_uri('swagger2.json'))\nself.transform_template()\nself.deploy_stack()\nsecond_dep_ids = self.get_stac... | <|body_start_0|>
self.create_and_verify_stack('single/basic_api')
first_dep_ids = self.get_stack_deployment_ids()
self.assertEqual(len(first_dep_ids), 1)
self.set_template_resource_property('MyApi', 'DefinitionUri', self.get_s3_uri('swagger2.json'))
self.transform_template()
... | Basic AWS::Serverless::Api tests | TestBasicApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBasicApi:
"""Basic AWS::Serverless::Api tests"""
def test_basic_api(self):
"""Creates an API and updates its DefinitionUri"""
<|body_0|>
def test_basic_api_with_mode(self):
"""Creates an API and updates its DefinitionUri"""
<|body_1|>
def test_ba... | stack_v2_sparse_classes_75kplus_train_002950 | 3,551 | permissive | [
{
"docstring": "Creates an API and updates its DefinitionUri",
"name": "test_basic_api",
"signature": "def test_basic_api(self)"
},
{
"docstring": "Creates an API and updates its DefinitionUri",
"name": "test_basic_api_with_mode",
"signature": "def test_basic_api_with_mode(self)"
},
... | 5 | null | Implement the Python class `TestBasicApi` described below.
Class description:
Basic AWS::Serverless::Api tests
Method signatures and docstrings:
- def test_basic_api(self): Creates an API and updates its DefinitionUri
- def test_basic_api_with_mode(self): Creates an API and updates its DefinitionUri
- def test_basic_... | Implement the Python class `TestBasicApi` described below.
Class description:
Basic AWS::Serverless::Api tests
Method signatures and docstrings:
- def test_basic_api(self): Creates an API and updates its DefinitionUri
- def test_basic_api_with_mode(self): Creates an API and updates its DefinitionUri
- def test_basic_... | 1af3e97b2043369087729cc3849934f8cf838b7e | <|skeleton|>
class TestBasicApi:
"""Basic AWS::Serverless::Api tests"""
def test_basic_api(self):
"""Creates an API and updates its DefinitionUri"""
<|body_0|>
def test_basic_api_with_mode(self):
"""Creates an API and updates its DefinitionUri"""
<|body_1|>
def test_ba... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestBasicApi:
"""Basic AWS::Serverless::Api tests"""
def test_basic_api(self):
"""Creates an API and updates its DefinitionUri"""
self.create_and_verify_stack('single/basic_api')
first_dep_ids = self.get_stack_deployment_ids()
self.assertEqual(len(first_dep_ids), 1)
... | the_stack_v2_python_sparse | integration/single/test_basic_api.py | jfuss/serverless-application-model | train | 2 |
4eebcdbd096b1a340fe95da36da02a835cef770a | [
"stream_data = dict(get_data(stream))\nsheet = list(stream_data.keys())[0] if len(stream_data) == 1 else None\nif sheet is None or sheet != 'Data':\n raise ParseError('XLS parse error - spreadsheet should contain one sheet named `Data`')\nstream_data = stream_data[sheet]\nheaders = stream_data[0]\ndata = []\ntry... | <|body_start_0|>
stream_data = dict(get_data(stream))
sheet = list(stream_data.keys())[0] if len(stream_data) == 1 else None
if sheet is None or sheet != 'Data':
raise ParseError('XLS parse error - spreadsheet should contain one sheet named `Data`')
stream_data = stream_data[... | XLSParser | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XLSParser:
def parse(self, stream, media_type=None, parser_context=None):
"""Parses the incoming bytestream as XLS and return resulting data"""
<|body_0|>
def _json_loads(self, val):
"""Attempt to load the value as json"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_002951 | 3,110 | permissive | [
{
"docstring": "Parses the incoming bytestream as XLS and return resulting data",
"name": "parse",
"signature": "def parse(self, stream, media_type=None, parser_context=None)"
},
{
"docstring": "Attempt to load the value as json",
"name": "_json_loads",
"signature": "def _json_loads(self... | 2 | stack_v2_sparse_classes_30k_train_026785 | Implement the Python class `XLSParser` described below.
Class description:
Implement the XLSParser class.
Method signatures and docstrings:
- def parse(self, stream, media_type=None, parser_context=None): Parses the incoming bytestream as XLS and return resulting data
- def _json_loads(self, val): Attempt to load the... | Implement the Python class `XLSParser` described below.
Class description:
Implement the XLSParser class.
Method signatures and docstrings:
- def parse(self, stream, media_type=None, parser_context=None): Parses the incoming bytestream as XLS and return resulting data
- def _json_loads(self, val): Attempt to load the... | 85102bb41aa0d558a3fa088e4fd6f51613599ad0 | <|skeleton|>
class XLSParser:
def parse(self, stream, media_type=None, parser_context=None):
"""Parses the incoming bytestream as XLS and return resulting data"""
<|body_0|>
def _json_loads(self, val):
"""Attempt to load the value as json"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XLSParser:
def parse(self, stream, media_type=None, parser_context=None):
"""Parses the incoming bytestream as XLS and return resulting data"""
stream_data = dict(get_data(stream))
sheet = list(stream_data.keys())[0] if len(stream_data) == 1 else None
if sheet is None or sheet ... | the_stack_v2_python_sparse | orchestrator/core/orc_server/backup/utils/xls.py | g2-inc/openc2-oif-orchestrator | train | 1 | |
cf904c46815df5255f6b9d2e85d823d21775e182 | [
"current = Path(inspect.getabsfile(inspect.currentframe())).parent\nself.data_dir = current.joinpath('data')\nself.records_url = 'https://zenodo.org/api/records/6799475'",
"result = []\nfor item in Path.iterdir(self.data_dir):\n if item.is_file() and item.suffix not in '.py':\n result.append((item.name,... | <|body_start_0|>
current = Path(inspect.getabsfile(inspect.currentframe())).parent
self.data_dir = current.joinpath('data')
self.records_url = 'https://zenodo.org/api/records/6799475'
<|end_body_0|>
<|body_start_1|>
result = []
for item in Path.iterdir(self.data_dir):
... | A tool for locating, downloading and returning local file paths for Openseize's demo data. Data files are not included with the openseize software. Data that is needed to run the demos are stored at Zenodo. When a client request a path for a demo data file, this locator will first look on the clients local machine for ... | DataLocator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataLocator:
"""A tool for locating, downloading and returning local file paths for Openseize's demo data. Data files are not included with the openseize software. Data that is needed to run the demos are stored at Zenodo. When a client request a path for a demo data file, this locator will first... | stack_v2_sparse_classes_75kplus_train_002952 | 5,500 | permissive | [
{
"docstring": "Initialize an instance with the data_dir location & Zenodo url. It is important that the data dir always remain in the demo module of Openseize since we use a relative path to locate it here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns a dic... | 6 | stack_v2_sparse_classes_30k_train_003135 | Implement the Python class `DataLocator` described below.
Class description:
A tool for locating, downloading and returning local file paths for Openseize's demo data. Data files are not included with the openseize software. Data that is needed to run the demos are stored at Zenodo. When a client request a path for a ... | Implement the Python class `DataLocator` described below.
Class description:
A tool for locating, downloading and returning local file paths for Openseize's demo data. Data files are not included with the openseize software. Data that is needed to run the demos are stored at Zenodo. When a client request a path for a ... | 09ee87e044c7272754e33636dc2f14932145c903 | <|skeleton|>
class DataLocator:
"""A tool for locating, downloading and returning local file paths for Openseize's demo data. Data files are not included with the openseize software. Data that is needed to run the demos are stored at Zenodo. When a client request a path for a demo data file, this locator will first... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataLocator:
"""A tool for locating, downloading and returning local file paths for Openseize's demo data. Data files are not included with the openseize software. Data that is needed to run the demos are stored at Zenodo. When a client request a path for a demo data file, this locator will first look on the ... | the_stack_v2_python_sparse | src/openseize/demos/demopaths.py | mscaudill/openseize | train | 12 |
70b058eeb680f0eda919e38faee2a82b5faab6b4 | [
"import heapq as hq\ndiff = [(abs(a - x), a) for a in arr]\nhq.heapify(diff)\nresult = [hq.heappop(diff)[1] for _ in range(k)]\nreturn sorted(result)",
"left = 0\nright = len(arr) - k\nwhile left < right:\n mid = (left + right) // 2\n print('left: {} right: {} mid: {}'.format(left, right, mid))\n if abs(... | <|body_start_0|>
import heapq as hq
diff = [(abs(a - x), a) for a in arr]
hq.heapify(diff)
result = [hq.heappop(diff)[1] for _ in range(k)]
return sorted(result)
<|end_body_0|>
<|body_start_1|>
left = 0
right = len(arr) - k
while left < right:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findClosestElements(self, arr, k, x):
""":type arr: List[int] :type k: int :type x: int :rtype: List[int] input: SORTED array"""
<|body_0|>
def rewrite(self, arr, k, x):
""":type arr: List[int] :type k: int :type x: int :rtype: List[int] input: SORTED a... | stack_v2_sparse_classes_75kplus_train_002953 | 3,094 | no_license | [
{
"docstring": ":type arr: List[int] :type k: int :type x: int :rtype: List[int] input: SORTED array",
"name": "findClosestElements",
"signature": "def findClosestElements(self, arr, k, x)"
},
{
"docstring": ":type arr: List[int] :type k: int :type x: int :rtype: List[int] input: SORTED array Us... | 3 | stack_v2_sparse_classes_30k_train_008248 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findClosestElements(self, arr, k, x): :type arr: List[int] :type k: int :type x: int :rtype: List[int] input: SORTED array
- def rewrite(self, arr, k, x): :type arr: List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findClosestElements(self, arr, k, x): :type arr: List[int] :type k: int :type x: int :rtype: List[int] input: SORTED array
- def rewrite(self, arr, k, x): :type arr: List[int... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def findClosestElements(self, arr, k, x):
""":type arr: List[int] :type k: int :type x: int :rtype: List[int] input: SORTED array"""
<|body_0|>
def rewrite(self, arr, k, x):
""":type arr: List[int] :type k: int :type x: int :rtype: List[int] input: SORTED a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findClosestElements(self, arr, k, x):
""":type arr: List[int] :type k: int :type x: int :rtype: List[int] input: SORTED array"""
import heapq as hq
diff = [(abs(a - x), a) for a in arr]
hq.heapify(diff)
result = [hq.heappop(diff)[1] for _ in range(k)]
... | the_stack_v2_python_sparse | binary_search/658_Find_K_Closest_Elements.py | vsdrun/lc_public | train | 6 | |
4f30e95ada61ac9fdbed7e4c6b2ce3317060047c | [
"super().__init__()\nself.W = tf.keras.layers.Dense(units=units)\nself.U = tf.keras.layers.Dense(units=units)\nself.V = tf.keras.layers.Dense(units=1)",
"fixed_prev = tf.expand_dims(s_prev, axis=1)\nweights = self.V(tf.nn.tanh(self.W(fixed_prev) + self.U(hidden_states)))\nweights = tf.nn.softmax(weights)\ncontext... | <|body_start_0|>
super().__init__()
self.W = tf.keras.layers.Dense(units=units)
self.U = tf.keras.layers.Dense(units=units)
self.V = tf.keras.layers.Dense(units=1)
<|end_body_0|>
<|body_start_1|>
fixed_prev = tf.expand_dims(s_prev, axis=1)
weights = self.V(tf.nn.tanh(sel... | class SelfAttention | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""class SelfAttention"""
def __init__(self, units):
"""Initializer. Args: units: (int) representing the number of hidden units in the alignment model."""
<|body_0|>
def call(self, s_prev, hidden_states):
"""call method. Args: s_prev: (tf.Tensor) c... | stack_v2_sparse_classes_75kplus_train_002954 | 1,355 | no_license | [
{
"docstring": "Initializer. Args: units: (int) representing the number of hidden units in the alignment model.",
"name": "__init__",
"signature": "def __init__(self, units)"
},
{
"docstring": "call method. Args: s_prev: (tf.Tensor) containing the previous decoder hidden state. hidden_states: (t... | 2 | stack_v2_sparse_classes_30k_train_015329 | Implement the Python class `SelfAttention` described below.
Class description:
class SelfAttention
Method signatures and docstrings:
- def __init__(self, units): Initializer. Args: units: (int) representing the number of hidden units in the alignment model.
- def call(self, s_prev, hidden_states): call method. Args: ... | Implement the Python class `SelfAttention` described below.
Class description:
class SelfAttention
Method signatures and docstrings:
- def __init__(self, units): Initializer. Args: units: (int) representing the number of hidden units in the alignment model.
- def call(self, s_prev, hidden_states): call method. Args: ... | 75274394adb52d740f6cd4000cc00bbde44b9b72 | <|skeleton|>
class SelfAttention:
"""class SelfAttention"""
def __init__(self, units):
"""Initializer. Args: units: (int) representing the number of hidden units in the alignment model."""
<|body_0|>
def call(self, s_prev, hidden_states):
"""call method. Args: s_prev: (tf.Tensor) c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelfAttention:
"""class SelfAttention"""
def __init__(self, units):
"""Initializer. Args: units: (int) representing the number of hidden units in the alignment model."""
super().__init__()
self.W = tf.keras.layers.Dense(units=units)
self.U = tf.keras.layers.Dense(units=uni... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | jdarangop/holbertonschool-machine_learning | train | 2 |
cbed140c4cafb6636d33109c7fe2e76fa4895f2c | [
"if not meshRelax:\n return\nif not mc.objExists(meshRelax):\n raise UserInputError('IkaMeshRelax ' + meshRelax + ' does not exists! No influence data recorded!!')\nobjType = mc.objectType(meshRelax)\nif objType != 'ikaMeshRelax':\n raise UserInputError('Object ' + meshRelax + ' is not a vaild ikaMeshRelax... | <|body_start_0|>
if not meshRelax:
return
if not mc.objExists(meshRelax):
raise UserInputError('IkaMeshRelax ' + meshRelax + ' does not exists! No influence data recorded!!')
objType = mc.objectType(meshRelax)
if objType != 'ikaMeshRelax':
raise UserIn... | IkaMeshRelaxData class object. | IkaMeshRelaxData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IkaMeshRelaxData:
"""IkaMeshRelaxData class object."""
def __init__(self, meshRelax=''):
"""IkaMeshRelaxData class initilizer."""
<|body_0|>
def rebuild(self):
"""Rebuild surfaceSkin deformer from saved deformer data"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_75kplus_train_002955 | 1,916 | no_license | [
{
"docstring": "IkaMeshRelaxData class initilizer.",
"name": "__init__",
"signature": "def __init__(self, meshRelax='')"
},
{
"docstring": "Rebuild surfaceSkin deformer from saved deformer data",
"name": "rebuild",
"signature": "def rebuild(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011285 | Implement the Python class `IkaMeshRelaxData` described below.
Class description:
IkaMeshRelaxData class object.
Method signatures and docstrings:
- def __init__(self, meshRelax=''): IkaMeshRelaxData class initilizer.
- def rebuild(self): Rebuild surfaceSkin deformer from saved deformer data | Implement the Python class `IkaMeshRelaxData` described below.
Class description:
IkaMeshRelaxData class object.
Method signatures and docstrings:
- def __init__(self, meshRelax=''): IkaMeshRelaxData class initilizer.
- def rebuild(self): Rebuild surfaceSkin deformer from saved deformer data
<|skeleton|>
class IkaMe... | 16337badb6d1b4266f31008ceb17cfd70fec3623 | <|skeleton|>
class IkaMeshRelaxData:
"""IkaMeshRelaxData class object."""
def __init__(self, meshRelax=''):
"""IkaMeshRelaxData class initilizer."""
<|body_0|>
def rebuild(self):
"""Rebuild surfaceSkin deformer from saved deformer data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IkaMeshRelaxData:
"""IkaMeshRelaxData class object."""
def __init__(self, meshRelax=''):
"""IkaMeshRelaxData class initilizer."""
if not meshRelax:
return
if not mc.objExists(meshRelax):
raise UserInputError('IkaMeshRelax ' + meshRelax + ' does not exists! ... | the_stack_v2_python_sparse | glTools-master/data/ikaMeshRelaxData.py | moChen0607/pubTool | train | 0 |
23c5bd12875d9ac2ebcadcfa244d8a59e886092e | [
"dt = self.qd.get('downloadtype', '')\nif dt != None and dt != '':\n self.dtype = dt",
"lData = []\nsData = ''\noErr = ErrHandle()\ntry:\n if dtype == 'json':\n sData = self.obj.data\n elif dtype == 'hist-svg':\n pass\n elif dtype == 'hist-png':\n pass\n elif dtype == 'ps':\n ... | <|body_start_0|>
dt = self.qd.get('downloadtype', '')
if dt != None and dt != '':
self.dtype = dt
<|end_body_0|>
<|body_start_1|>
lData = []
sData = ''
oErr = ErrHandle()
try:
if dtype == 'json':
sData = self.obj.data
e... | Generic treatment of Visualization downloads for SSGs | StemmaDownload | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StemmaDownload:
"""Generic treatment of Visualization downloads for SSGs"""
def custom_init(self):
"""Calculate stuff"""
<|body_0|>
def get_data(self, prefix, dtype, response=None):
"""Gather the data as CSV, including a header line and comma-separated"""
... | stack_v2_sparse_classes_75kplus_train_002956 | 34,230 | permissive | [
{
"docstring": "Calculate stuff",
"name": "custom_init",
"signature": "def custom_init(self)"
},
{
"docstring": "Gather the data as CSV, including a header line and comma-separated",
"name": "get_data",
"signature": "def get_data(self, prefix, dtype, response=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020391 | Implement the Python class `StemmaDownload` described below.
Class description:
Generic treatment of Visualization downloads for SSGs
Method signatures and docstrings:
- def custom_init(self): Calculate stuff
- def get_data(self, prefix, dtype, response=None): Gather the data as CSV, including a header line and comma... | Implement the Python class `StemmaDownload` described below.
Class description:
Generic treatment of Visualization downloads for SSGs
Method signatures and docstrings:
- def custom_init(self): Calculate stuff
- def get_data(self, prefix, dtype, response=None): Gather the data as CSV, including a header line and comma... | 921fb5ec3f5b40b169bd3f65417580878365ccab | <|skeleton|>
class StemmaDownload:
"""Generic treatment of Visualization downloads for SSGs"""
def custom_init(self):
"""Calculate stuff"""
<|body_0|>
def get_data(self, prefix, dtype, response=None):
"""Gather the data as CSV, including a header line and comma-separated"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StemmaDownload:
"""Generic treatment of Visualization downloads for SSGs"""
def custom_init(self):
"""Calculate stuff"""
dt = self.qd.get('downloadtype', '')
if dt != None and dt != '':
self.dtype = dt
def get_data(self, prefix, dtype, response=None):
"""G... | the_stack_v2_python_sparse | passim/passim/stemma/views.py | ErwinKomen/RU-passim | train | 0 |
741c6773ee9da987a6884ccf683917d9f868c4c8 | [
"kwargs = super(NewbobAbs, cls).load_initial_kwargs_from_config(config)\nkwargs.update({'errorThreshold': config.float('newbob_error_threshold', -0.01), 'learningRateDecayFactor': config.float('newbob_learning_rate_decay', 0.5)})\nreturn kwargs",
"super(NewbobAbs, self).__init__(**kwargs)\nself.errorThreshold = e... | <|body_start_0|>
kwargs = super(NewbobAbs, cls).load_initial_kwargs_from_config(config)
kwargs.update({'errorThreshold': config.float('newbob_error_threshold', -0.01), 'learningRateDecayFactor': config.float('newbob_learning_rate_decay', 0.5)})
return kwargs
<|end_body_0|>
<|body_start_1|>
... | NewbobAbs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewbobAbs:
def load_initial_kwargs_from_config(cls, config):
""":type config: Config.Config :rtype: dict[str]"""
<|body_0|>
def __init__(self, errorThreshold, learningRateDecayFactor, **kwargs):
""":type errorThreshold: float :type learningRateDecayFactor: float"""
... | stack_v2_sparse_classes_75kplus_train_002957 | 19,323 | no_license | [
{
"docstring": ":type config: Config.Config :rtype: dict[str]",
"name": "load_initial_kwargs_from_config",
"signature": "def load_initial_kwargs_from_config(cls, config)"
},
{
"docstring": ":type errorThreshold: float :type learningRateDecayFactor: float",
"name": "__init__",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_010600 | Implement the Python class `NewbobAbs` described below.
Class description:
Implement the NewbobAbs class.
Method signatures and docstrings:
- def load_initial_kwargs_from_config(cls, config): :type config: Config.Config :rtype: dict[str]
- def __init__(self, errorThreshold, learningRateDecayFactor, **kwargs): :type e... | Implement the Python class `NewbobAbs` described below.
Class description:
Implement the NewbobAbs class.
Method signatures and docstrings:
- def load_initial_kwargs_from_config(cls, config): :type config: Config.Config :rtype: dict[str]
- def __init__(self, errorThreshold, learningRateDecayFactor, **kwargs): :type e... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class NewbobAbs:
def load_initial_kwargs_from_config(cls, config):
""":type config: Config.Config :rtype: dict[str]"""
<|body_0|>
def __init__(self, errorThreshold, learningRateDecayFactor, **kwargs):
""":type errorThreshold: float :type learningRateDecayFactor: float"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NewbobAbs:
def load_initial_kwargs_from_config(cls, config):
""":type config: Config.Config :rtype: dict[str]"""
kwargs = super(NewbobAbs, cls).load_initial_kwargs_from_config(config)
kwargs.update({'errorThreshold': config.float('newbob_error_threshold', -0.01), 'learningRateDecayFact... | the_stack_v2_python_sparse | python/rwth-i6_returnn/returnn-master/LearningRateControl.py | LiuFang816/SALSTM_py_data | train | 10 | |
c8139875b737aa6b776a36d2c056ddf6f4ea052a | [
"self.v1 = v1\nself.v2 = v2\nself.lenv1 = len(v1)\nself.lenv2 = len(v2)\nself.min2len = 2 * min(len(v1), len(v2))\nself.alllen = len(v1) + len(v2)\nself.cnt = 0\nself.pos = 0\nif len(v1) > len(v2):\n self.remainlist = v1[len(v2):len(v1)]\nelse:\n self.remainlist = v2[len(v1):len(v2)]\nself.remaincnt = 0",
"... | <|body_start_0|>
self.v1 = v1
self.v2 = v2
self.lenv1 = len(v1)
self.lenv2 = len(v2)
self.min2len = 2 * min(len(v1), len(v2))
self.alllen = len(v1) + len(v2)
self.cnt = 0
self.pos = 0
if len(v1) > len(v2):
self.remainlist = v1[len(v2):l... | ZigzagIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_75kplus_train_002958 | 1,340 | no_license | [
{
"docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]",
"name": "__init__",
"signature": "def __init__(self, v1, v2)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name"... | 3 | stack_v2_sparse_classes_30k_train_014229 | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | cd0341341a0216ac39850727804411e4cf5e4a67 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
self.v1 = v1
self.v2 = v2
self.lenv1 = len(v1)
self.lenv2 = len(v2)
self.min2len = 2 * min(len(v1), len(v2))
self.alllen = len(... | the_stack_v2_python_sparse | 281. Zigzag Iterator_google.py | cclain/LeetCode-Problem-Solution | train | 0 | |
a671e163df21aee3d74330660ba4caea68251629 | [
"enc1, enc2 = ([], [])\ncount1, count2 = (0, 0)\ndict1, dict2 = (dict(), dict())\nfor i in range(len(s1)):\n char1, char2 = (s1[i], s2[i])\n if char1 in dict1:\n enc1.append(dict1[char1])\n else:\n count1 += 1\n dict1[char1] = count1\n enc1.append(dict1[char1])\n if char2 in ... | <|body_start_0|>
enc1, enc2 = ([], [])
count1, count2 = (0, 0)
dict1, dict2 = (dict(), dict())
for i in range(len(s1)):
char1, char2 = (s1[i], s2[i])
if char1 in dict1:
enc1.append(dict1[char1])
else:
count1 += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def is_isomorphic(self, s1, s2):
"""Algorithm based on encoding two strings and comparing resulted encodings. Encoding is following: each new character receives a unique index, starting from 0. We keep track of already used characters. If we see the character again, we take ind... | stack_v2_sparse_classes_75kplus_train_002959 | 2,448 | no_license | [
{
"docstring": "Algorithm based on encoding two strings and comparing resulted encodings. Encoding is following: each new character receives a unique index, starting from 0. We keep track of already used characters. If we see the character again, we take index from a dictionary, otherwise we assign a new index.... | 2 | stack_v2_sparse_classes_30k_train_012774 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_isomorphic(self, s1, s2): Algorithm based on encoding two strings and comparing resulted encodings. Encoding is following: each new character receives a unique index, star... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_isomorphic(self, s1, s2): Algorithm based on encoding two strings and comparing resulted encodings. Encoding is following: each new character receives a unique index, star... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def is_isomorphic(self, s1, s2):
"""Algorithm based on encoding two strings and comparing resulted encodings. Encoding is following: each new character receives a unique index, starting from 0. We keep track of already used characters. If we see the character again, we take ind... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def is_isomorphic(self, s1, s2):
"""Algorithm based on encoding two strings and comparing resulted encodings. Encoding is following: each new character receives a unique index, starting from 0. We keep track of already used characters. If we see the character again, we take index from a dict... | the_stack_v2_python_sparse | Strings/isomorphic_strings.py | vladn90/Algorithms | train | 0 | |
e8808fed0f85eed450f5cb1055d9576e2a270b95 | [
"hdr_data = super(SpmAnalyzeHeader, klass).default_structarr(endianness)\nhdr_data['scl_slope'] = 1\nreturn hdr_data",
"slope = self._structarr['scl_slope']\nif np.isnan(slope) or slope in (0, -np.inf, np.inf):\n return (None, None)\nreturn (slope, None)",
"if slope is None:\n slope = np.nan\nif slope in ... | <|body_start_0|>
hdr_data = super(SpmAnalyzeHeader, klass).default_structarr(endianness)
hdr_data['scl_slope'] = 1
return hdr_data
<|end_body_0|>
<|body_start_1|>
slope = self._structarr['scl_slope']
if np.isnan(slope) or slope in (0, -np.inf, np.inf):
return (None, ... | Basic scaling Spm Analyze header | SpmAnalyzeHeader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpmAnalyzeHeader:
"""Basic scaling Spm Analyze header"""
def default_structarr(klass, endianness=None):
"""Create empty header binary block with given endianness"""
<|body_0|>
def get_slope_inter(self):
"""Get scalefactor and intercept If scalefactor is 0.0 retur... | stack_v2_sparse_classes_75kplus_train_002960 | 13,046 | permissive | [
{
"docstring": "Create empty header binary block with given endianness",
"name": "default_structarr",
"signature": "def default_structarr(klass, endianness=None)"
},
{
"docstring": "Get scalefactor and intercept If scalefactor is 0.0 return None to indicate no scalefactor. Intercept is always No... | 3 | stack_v2_sparse_classes_30k_train_013043 | Implement the Python class `SpmAnalyzeHeader` described below.
Class description:
Basic scaling Spm Analyze header
Method signatures and docstrings:
- def default_structarr(klass, endianness=None): Create empty header binary block with given endianness
- def get_slope_inter(self): Get scalefactor and intercept If sca... | Implement the Python class `SpmAnalyzeHeader` described below.
Class description:
Basic scaling Spm Analyze header
Method signatures and docstrings:
- def default_structarr(klass, endianness=None): Create empty header binary block with given endianness
- def get_slope_inter(self): Get scalefactor and intercept If sca... | 3c3acc55de8ba741e673063378e6cbaf10b64c7a | <|skeleton|>
class SpmAnalyzeHeader:
"""Basic scaling Spm Analyze header"""
def default_structarr(klass, endianness=None):
"""Create empty header binary block with given endianness"""
<|body_0|>
def get_slope_inter(self):
"""Get scalefactor and intercept If scalefactor is 0.0 retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpmAnalyzeHeader:
"""Basic scaling Spm Analyze header"""
def default_structarr(klass, endianness=None):
"""Create empty header binary block with given endianness"""
hdr_data = super(SpmAnalyzeHeader, klass).default_structarr(endianness)
hdr_data['scl_slope'] = 1
return hdr... | the_stack_v2_python_sparse | env/lib/python3.6/site-packages/nibabel/spm99analyze.py | Raniac/NEURO-LEARN | train | 9 |
9ec5418d2c4138a90ebd3f17077743d4aae3fd68 | [
"allowed_methods = [dec.factor_analysis.FactorAnalysis, dec.fastica_.FastICA, dec.incremental_pca.IncrementalPCA, dec.sparse_pca.MiniBatchSparsePCA, dec.nmf.NMF, dec.pca.PCA, dec.sparse_pca.SparsePCA, dec.truncated_svd.TruncatedSVD]\nself.estimator = estimator\nself.method_name = str(estimator)[:str(estimator).inde... | <|body_start_0|>
allowed_methods = [dec.factor_analysis.FactorAnalysis, dec.fastica_.FastICA, dec.incremental_pca.IncrementalPCA, dec.sparse_pca.MiniBatchSparsePCA, dec.nmf.NMF, dec.pca.PCA, dec.sparse_pca.SparsePCA, dec.truncated_svd.TruncatedSVD]
self.estimator = estimator
self.method_name = s... | Pycroscopy wrapper around the sklearn.decomposition classes | Decomposition | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decomposition:
"""Pycroscopy wrapper around the sklearn.decomposition classes"""
def __init__(self, h5_main, estimator):
"""Uses the provided (preconfigured) Decomposition object to decompose the provided dataset Parameters ------------ h5_main : HDF5 dataset object Main dataset with... | stack_v2_sparse_classes_75kplus_train_002961 | 7,337 | permissive | [
{
"docstring": "Uses the provided (preconfigured) Decomposition object to decompose the provided dataset Parameters ------------ h5_main : HDF5 dataset object Main dataset with ancillary spectroscopic, position indices and values datasets estimator : sklearn.cluster estimator object configured decomposition obj... | 5 | null | Implement the Python class `Decomposition` described below.
Class description:
Pycroscopy wrapper around the sklearn.decomposition classes
Method signatures and docstrings:
- def __init__(self, h5_main, estimator): Uses the provided (preconfigured) Decomposition object to decompose the provided dataset Parameters ---... | Implement the Python class `Decomposition` described below.
Class description:
Pycroscopy wrapper around the sklearn.decomposition classes
Method signatures and docstrings:
- def __init__(self, h5_main, estimator): Uses the provided (preconfigured) Decomposition object to decompose the provided dataset Parameters ---... | ae1e8b848f3c9e5f5a8dee82a17ceac2cf1ee0b9 | <|skeleton|>
class Decomposition:
"""Pycroscopy wrapper around the sklearn.decomposition classes"""
def __init__(self, h5_main, estimator):
"""Uses the provided (preconfigured) Decomposition object to decompose the provided dataset Parameters ------------ h5_main : HDF5 dataset object Main dataset with... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decomposition:
"""Pycroscopy wrapper around the sklearn.decomposition classes"""
def __init__(self, h5_main, estimator):
"""Uses the provided (preconfigured) Decomposition object to decompose the provided dataset Parameters ------------ h5_main : HDF5 dataset object Main dataset with ancillary sp... | the_stack_v2_python_sparse | pycroscopy/processing/decomposition.py | gangaiitk/pycroscopy | train | 0 |
cac5ee5f32cbc2d13565b13442e89b35731e03dc | [
"if not root:\n return []\nstack = [root]\ndata = [root.val]\nindex = 0\nwhile index < len(stack):\n node = stack[index]\n index += 1\n if node.left:\n stack.append(node.left)\n data.append(node.left.val)\n else:\n data.append(None)\n if node.right:\n stack.aappend(node... | <|body_start_0|>
if not root:
return []
stack = [root]
data = [root.val]
index = 0
while index < len(stack):
node = stack[index]
index += 1
if node.left:
stack.append(node.left)
data.append(node.left.... | 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_75kplus_train_002962 | 1,806 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_004504 | 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:... | 8da15dce9bff72fc8b8aa75cf60bfd58f6754935 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
stack = [root]
data = [root.val]
index = 0
while index < len(stack):
node = stack[index]
index ... | the_stack_v2_python_sparse | 0297/SerializeDeserializeBinaryTree.py | UchihaSean/LeetCode | train | 1 | |
4d312b627466621e5c71ccf2617988a108323fbb | [
"super(FinalizeSlicedDownloadTask, self).__init__()\nself._source_resource = source_resource\nself._destination_resource = destination_resource",
"tracker_file_util.delete_download_tracker_files(self._destination_resource.storage_url)\nwith files.BinaryFileReader(self._destination_resource.storage_url.object_name... | <|body_start_0|>
super(FinalizeSlicedDownloadTask, self).__init__()
self._source_resource = source_resource
self._destination_resource = destination_resource
<|end_body_0|>
<|body_start_1|>
tracker_file_util.delete_download_tracker_files(self._destination_resource.storage_url)
w... | Performs final steps of sliced download. | FinalizeSlicedDownloadTask | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FinalizeSlicedDownloadTask:
"""Performs final steps of sliced download."""
def __init__(self, source_resource, destination_resource):
"""Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contain object's metadata for checking content encoding. destin... | stack_v2_sparse_classes_75kplus_train_002963 | 3,847 | permissive | [
{
"docstring": "Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contain object's metadata for checking content encoding. destination_resource (resource_reference.FileObjectResource): Must contain local filesystem path to downloaded object.",
"name": "__init__",
"signa... | 2 | stack_v2_sparse_classes_30k_train_013163 | Implement the Python class `FinalizeSlicedDownloadTask` described below.
Class description:
Performs final steps of sliced download.
Method signatures and docstrings:
- def __init__(self, source_resource, destination_resource): Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contai... | Implement the Python class `FinalizeSlicedDownloadTask` described below.
Class description:
Performs final steps of sliced download.
Method signatures and docstrings:
- def __init__(self, source_resource, destination_resource): Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contai... | 849d09dd7863efecbdf4072a504e1554e119f6ae | <|skeleton|>
class FinalizeSlicedDownloadTask:
"""Performs final steps of sliced download."""
def __init__(self, source_resource, destination_resource):
"""Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contain object's metadata for checking content encoding. destin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FinalizeSlicedDownloadTask:
"""Performs final steps of sliced download."""
def __init__(self, source_resource, destination_resource):
"""Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contain object's metadata for checking content encoding. destination_resourc... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/storage/tasks/cp/finalize_sliced_download_task.py | PrateekKhatri/gcloud_cli | train | 0 |
304f8cdabf0c92ee8457d9baf12dadf167e6faf5 | [
"if not head or not head.next:\n return head\nfirst_node = head\nsecond_node = head.next\nfirst_node.next = self.swapPairs(second_node.next)\nsecond_node.next = first_node\nreturn second_node",
"dummy = ListNode(-1)\ndummy.next = head\nprev_node = dummy\nwhile head and head.next:\n first_node = head\n se... | <|body_start_0|>
if not head or not head.next:
return head
first_node = head
second_node = head.next
first_node.next = self.swapPairs(second_node.next)
second_node.next = first_node
return second_node
<|end_body_0|>
<|body_start_1|>
dummy = ListNode(-... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""使用链表的方式更新相关的数据 :type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairsMethod1(self, head: ListNode) -> ListNode:
"""这个是一个官方推荐的方法,确实代码非常简洁,比自己的方法写的太好了。 :type head: ListNode :rtype: ListNode"""
... | stack_v2_sparse_classes_75kplus_train_002964 | 3,143 | no_license | [
{
"docstring": "使用链表的方式更新相关的数据 :type head: ListNode :rtype: ListNode",
"name": "swapPairs",
"signature": "def swapPairs(self, head: ListNode) -> ListNode"
},
{
"docstring": "这个是一个官方推荐的方法,确实代码非常简洁,比自己的方法写的太好了。 :type head: ListNode :rtype: ListNode",
"name": "swapPairsMethod1",
"signature"... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head: ListNode) -> ListNode: 使用链表的方式更新相关的数据 :type head: ListNode :rtype: ListNode
- def swapPairsMethod1(self, head: ListNode) -> ListNode: 这个是一个官方推荐的方法,确实代码非... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head: ListNode) -> ListNode: 使用链表的方式更新相关的数据 :type head: ListNode :rtype: ListNode
- def swapPairsMethod1(self, head: ListNode) -> ListNode: 这个是一个官方推荐的方法,确实代码非... | af13162360a28a0bcd71918fd8bff77c41ddcc2a | <|skeleton|>
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""使用链表的方式更新相关的数据 :type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairsMethod1(self, head: ListNode) -> ListNode:
"""这个是一个官方推荐的方法,确实代码非常简洁,比自己的方法写的太好了。 :type head: ListNode :rtype: ListNode"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""使用链表的方式更新相关的数据 :type head: ListNode :rtype: ListNode"""
if not head or not head.next:
return head
first_node = head
second_node = head.next
first_node.next = self.swapPairs(second_node.next)
... | the_stack_v2_python_sparse | 算法分析和归类/链表/两两交换链表中的节点.py | Carmenliukang/leetcode | train | 4 | |
4bd9d898074699278af959ae18ad98f1e36aeef8 | [
"self.has_started = False\nself.momentum = None\nself.e1_targets = None\nself.e2_targets = None\nself.target_index = None\nself.last_target_index = None\nself.h_to_e1_max = None\nself.h_to_e2_max = None",
"self.has_started = autotrageur.has_started\nself.momentum = autotrageur.momentum\nself.e1_targets = autotrag... | <|body_start_0|>
self.has_started = False
self.momentum = None
self.e1_targets = None
self.e2_targets = None
self.target_index = None
self.last_target_index = None
self.h_to_e1_max = None
self.h_to_e2_max = None
<|end_body_0|>
<|body_start_1|>
sel... | Contains the current algorithm state. Encapsulates values pertaining to the algorithm. Useful for rollback situations. | FCFCheckpoint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FCFCheckpoint:
"""Contains the current algorithm state. Encapsulates values pertaining to the algorithm. Useful for rollback situations."""
def __init__(self):
"""Constructor."""
<|body_0|>
def save(self, autotrageur):
"""Saves the current autotrageur state befor... | stack_v2_sparse_classes_75kplus_train_002965 | 24,909 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Saves the current autotrageur state before another algorithm iteration. Args: autotrageur (FCFAutotrageur): The current FCFAutotrageur.",
"name": "save",
"signature": "def save(self, a... | 3 | stack_v2_sparse_classes_30k_train_002831 | Implement the Python class `FCFCheckpoint` described below.
Class description:
Contains the current algorithm state. Encapsulates values pertaining to the algorithm. Useful for rollback situations.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def save(self, autotrageur): Saves the current au... | Implement the Python class `FCFCheckpoint` described below.
Class description:
Contains the current algorithm state. Encapsulates values pertaining to the algorithm. Useful for rollback situations.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def save(self, autotrageur): Saves the current au... | 1c0d556d04c061c3a35802631ee471e6bf4641dd | <|skeleton|>
class FCFCheckpoint:
"""Contains the current algorithm state. Encapsulates values pertaining to the algorithm. Useful for rollback situations."""
def __init__(self):
"""Constructor."""
<|body_0|>
def save(self, autotrageur):
"""Saves the current autotrageur state befor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FCFCheckpoint:
"""Contains the current algorithm state. Encapsulates values pertaining to the algorithm. Useful for rollback situations."""
def __init__(self):
"""Constructor."""
self.has_started = False
self.momentum = None
self.e1_targets = None
self.e2_targets =... | the_stack_v2_python_sparse | bot/arbitrage/fcf_autotrageur.py | ronaldlam/Autotrageur | train | 0 |
97db9feb3ced8eef878fc21a1a09997603988f39 | [
"logfile = os.path.join(os.environ['TEST_DATA'], 'data', 'log2xml_test.log')\ntestfile = os.path.join(tempfile.gettempdir(), 'log2xml_test.xml')\nlog2xml.convert(logfile, testfile)\nminidom.parse(testfile)",
"logfile = os.path.join(os.environ['TEST_DATA'], 'data', 'log2xml_failure.log')\ntestfile = os.path.join(t... | <|body_start_0|>
logfile = os.path.join(os.environ['TEST_DATA'], 'data', 'log2xml_test.log')
testfile = os.path.join(tempfile.gettempdir(), 'log2xml_test.xml')
log2xml.convert(logfile, testfile)
minidom.parse(testfile)
<|end_body_0|>
<|body_start_1|>
logfile = os.path.join(os.en... | Acceptance tests for log2xml.py | Log2XMLTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Log2XMLTest:
"""Acceptance tests for log2xml.py"""
def test_log_conversion(self):
"""Convert a log into xml."""
<|body_0|>
def test_log_utf16_conversion(self):
"""Convert a log into xml."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
logfile = ... | stack_v2_sparse_classes_75kplus_train_002966 | 1,720 | no_license | [
{
"docstring": "Convert a log into xml.",
"name": "test_log_conversion",
"signature": "def test_log_conversion(self)"
},
{
"docstring": "Convert a log into xml.",
"name": "test_log_utf16_conversion",
"signature": "def test_log_utf16_conversion(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001416 | Implement the Python class `Log2XMLTest` described below.
Class description:
Acceptance tests for log2xml.py
Method signatures and docstrings:
- def test_log_conversion(self): Convert a log into xml.
- def test_log_utf16_conversion(self): Convert a log into xml. | Implement the Python class `Log2XMLTest` described below.
Class description:
Acceptance tests for log2xml.py
Method signatures and docstrings:
- def test_log_conversion(self): Convert a log into xml.
- def test_log_utf16_conversion(self): Convert a log into xml.
<|skeleton|>
class Log2XMLTest:
"""Acceptance test... | f458a4ce83f74d603362fe6b71eaa647ccc62fee | <|skeleton|>
class Log2XMLTest:
"""Acceptance tests for log2xml.py"""
def test_log_conversion(self):
"""Convert a log into xml."""
<|body_0|>
def test_log_utf16_conversion(self):
"""Convert a log into xml."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Log2XMLTest:
"""Acceptance tests for log2xml.py"""
def test_log_conversion(self):
"""Convert a log into xml."""
logfile = os.path.join(os.environ['TEST_DATA'], 'data', 'log2xml_test.log')
testfile = os.path.join(tempfile.gettempdir(), 'log2xml_test.xml')
log2xml.convert(lo... | the_stack_v2_python_sparse | buildframework/helium/sf/python/pythoncore/lib/pythoncoretests/test_log2xml.py | anagovitsyn/oss.FCL.sftools.dev.build | train | 0 |
8b1df7f45610beabb4ce1592ec51d60f3e9595f6 | [
"self.PntRefNum = None\nif FirstTraverse:\n self.CheckSurveyOrigin(LandXML_Obj)\n if self.PntRefNum is None:\n self.BdyConnectionStart(LandXML_Obj)",
"ConnectionChecker = BDY_Connections.CheckBdyConnection(self.PntRefNum, LandXML_Obj)\nfor point in LandXML_Obj.Coordinates.getchildren():\n if point... | <|body_start_0|>
self.PntRefNum = None
if FirstTraverse:
self.CheckSurveyOrigin(LandXML_Obj)
if self.PntRefNum is None:
self.BdyConnectionStart(LandXML_Obj)
<|end_body_0|>
<|body_start_1|>
ConnectionChecker = BDY_Connections.CheckBdyConnection(self.PntRef... | TraverseStart | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TraverseStart:
def __init__(self, LandXML_Obj, FirstTraverse):
"""Finds a suitable starting point for a traverse Adds PntRefNUm, Easting, Northing and code attributes if found :param LandXML_Obj:"""
<|body_0|>
def CheckSurveyOrigin(self, LandXML_Obj):
"""Checks surve... | stack_v2_sparse_classes_75kplus_train_002967 | 3,127 | no_license | [
{
"docstring": "Finds a suitable starting point for a traverse Adds PntRefNUm, Easting, Northing and code attributes if found :param LandXML_Obj:",
"name": "__init__",
"signature": "def __init__(self, LandXML_Obj, FirstTraverse)"
},
{
"docstring": "Checks survey origin if it is connected to a BD... | 3 | stack_v2_sparse_classes_30k_train_013661 | Implement the Python class `TraverseStart` described below.
Class description:
Implement the TraverseStart class.
Method signatures and docstrings:
- def __init__(self, LandXML_Obj, FirstTraverse): Finds a suitable starting point for a traverse Adds PntRefNUm, Easting, Northing and code attributes if found :param Lan... | Implement the Python class `TraverseStart` described below.
Class description:
Implement the TraverseStart class.
Method signatures and docstrings:
- def __init__(self, LandXML_Obj, FirstTraverse): Finds a suitable starting point for a traverse Adds PntRefNUm, Easting, Northing and code attributes if found :param Lan... | ccdc172ae5b5ef44de342d2d813b8ee21e9ba63e | <|skeleton|>
class TraverseStart:
def __init__(self, LandXML_Obj, FirstTraverse):
"""Finds a suitable starting point for a traverse Adds PntRefNUm, Easting, Northing and code attributes if found :param LandXML_Obj:"""
<|body_0|>
def CheckSurveyOrigin(self, LandXML_Obj):
"""Checks surve... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TraverseStart:
def __init__(self, LandXML_Obj, FirstTraverse):
"""Finds a suitable starting point for a traverse Adds PntRefNUm, Easting, Northing and code attributes if found :param LandXML_Obj:"""
self.PntRefNum = None
if FirstTraverse:
self.CheckSurveyOrigin(LandXML_Obj)... | the_stack_v2_python_sparse | src/LandXML/RefMarks/TraverseStart.py | sparkes-intrax/SurveyingCalcsUI | train | 0 | |
d90ae0e31dac304b1612d05a66502d153e4a33a3 | [
"favorite_journeys = FavoriteJourney.objects.filter(owner=self.request.user)\nserializer = FavoriteJourneySerializer(favorite_journeys, many=True)\nreturn Response(serializer.data)",
"try:\n return Stop.objects.get(pk=primary_key)\nexcept Stop.DoesNotExist as stop_not_exist:\n raise Http404(f'Cannot find St... | <|body_start_0|>
favorite_journeys = FavoriteJourney.objects.filter(owner=self.request.user)
serializer = FavoriteJourneySerializer(favorite_journeys, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
try:
return Stop.objects.get(pk=primary_key)
... | Get, Post or Delete a FavoriteJourney instance(s) for the currently authenticated user. | FavoriteJourneyView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FavoriteJourneyView:
"""Get, Post or Delete a FavoriteJourney instance(s) for the currently authenticated user."""
def get(self, request):
"""Return a list of all the FavoriteJourneys for the currently authenticated user."""
<|body_0|>
def get_stop_object(primary_key):
... | stack_v2_sparse_classes_75kplus_train_002968 | 31,821 | permissive | [
{
"docstring": "Return a list of all the FavoriteJourneys for the currently authenticated user.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Return the Stop object for the currently authenticated user.",
"name": "get_stop_object",
"signature": "def get_stop_o... | 5 | null | Implement the Python class `FavoriteJourneyView` described below.
Class description:
Get, Post or Delete a FavoriteJourney instance(s) for the currently authenticated user.
Method signatures and docstrings:
- def get(self, request): Return a list of all the FavoriteJourneys for the currently authenticated user.
- def... | Implement the Python class `FavoriteJourneyView` described below.
Class description:
Get, Post or Delete a FavoriteJourney instance(s) for the currently authenticated user.
Method signatures and docstrings:
- def get(self, request): Return a list of all the FavoriteJourneys for the currently authenticated user.
- def... | 35955cd9166b086f59157d23ed05a8ffcf82b617 | <|skeleton|>
class FavoriteJourneyView:
"""Get, Post or Delete a FavoriteJourney instance(s) for the currently authenticated user."""
def get(self, request):
"""Return a list of all the FavoriteJourneys for the currently authenticated user."""
<|body_0|>
def get_stop_object(primary_key):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FavoriteJourneyView:
"""Get, Post or Delete a FavoriteJourney instance(s) for the currently authenticated user."""
def get(self, request):
"""Return a list of all the FavoriteJourneys for the currently authenticated user."""
favorite_journeys = FavoriteJourney.objects.filter(owner=self.re... | the_stack_v2_python_sparse | backend/dublinbus/views.py | Botazio/UCD-DublinBus | train | 5 |
183a51ef6102dda5856fb3341d90030a8185bc54 | [
"end_date = start_date + relativedelta(months=duration)\nif timezone.now() <= end_date:\n return False\nreturn True",
"try:\n subscription_history = SubscriptionHistory.objects.get(user=user)\nexcept SubscriptionHistory.DoesNotExist as e:\n logger.exception(e)\n return False\nif not cls._is_subscripti... | <|body_start_0|>
end_date = start_date + relativedelta(months=duration)
if timezone.now() <= end_date:
return False
return True
<|end_body_0|>
<|body_start_1|>
try:
subscription_history = SubscriptionHistory.objects.get(user=user)
except SubscriptionHisto... | View for various checks of a user subscription | SubscriptionView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscriptionView:
"""View for various checks of a user subscription"""
def _is_subscription_expired(cls, start_date, duration):
"""Checks if a user subscription is expired or not. Args: start_date (datetime): Start date of subscription duration (int): Duration of subscription Returns... | stack_v2_sparse_classes_75kplus_train_002969 | 2,628 | no_license | [
{
"docstring": "Checks if a user subscription is expired or not. Args: start_date (datetime): Start date of subscription duration (int): Duration of subscription Returns: A bool value denoting if a user subscription is expired or not.",
"name": "_is_subscription_expired",
"signature": "def _is_subscript... | 3 | stack_v2_sparse_classes_30k_train_015847 | Implement the Python class `SubscriptionView` described below.
Class description:
View for various checks of a user subscription
Method signatures and docstrings:
- def _is_subscription_expired(cls, start_date, duration): Checks if a user subscription is expired or not. Args: start_date (datetime): Start date of subs... | Implement the Python class `SubscriptionView` described below.
Class description:
View for various checks of a user subscription
Method signatures and docstrings:
- def _is_subscription_expired(cls, start_date, duration): Checks if a user subscription is expired or not. Args: start_date (datetime): Start date of subs... | ab04535bc307167b2d79fa7e2b37e74e16f63963 | <|skeleton|>
class SubscriptionView:
"""View for various checks of a user subscription"""
def _is_subscription_expired(cls, start_date, duration):
"""Checks if a user subscription is expired or not. Args: start_date (datetime): Start date of subscription duration (int): Duration of subscription Returns... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubscriptionView:
"""View for various checks of a user subscription"""
def _is_subscription_expired(cls, start_date, duration):
"""Checks if a user subscription is expired or not. Args: start_date (datetime): Start date of subscription duration (int): Duration of subscription Returns: A bool valu... | the_stack_v2_python_sparse | utils/subscription.py | suraj-iitb/bodhitree | train | 1 |
b04fd945061f57090941fd0c5021759af2ae09ba | [
"if attrs is None:\n attrs = dict()\nself.value = value\nself.policy = policy\nself.continuation = continuation\nself.attrs = attrs",
"value = self.value.dataset\nother_value = other.value.dataset.interp_like(value)\nreturn np.max(np.abs(value - other_value).to_array())"
] | <|body_start_0|>
if attrs is None:
attrs = dict()
self.value = value
self.policy = policy
self.continuation = continuation
self.attrs = attrs
<|end_body_0|>
<|body_start_1|>
value = self.value.dataset
other_value = other.value.dataset.interp_like(valu... | Class to allow for solution interpolation using xarray. Represents a solution object for labeled models. | ConsumerSolutionLabeled | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsumerSolutionLabeled:
"""Class to allow for solution interpolation using xarray. Represents a solution object for labeled models."""
def __init__(self, value: ValueFuncCRRALabeled, policy: xr.Dataset, continuation: ValueFuncCRRALabeled, attrs=None):
"""Consumer Solution for labele... | stack_v2_sparse_classes_75kplus_train_002970 | 40,507 | permissive | [
{
"docstring": "Consumer Solution for labeled models. Parameters ---------- value : ValueFuncCRRALabeled Value function and marginal value function. policy : xr.Dataset Policy function. continuation : ValueFuncCRRALabeled Continuation value function and marginal value function. attrs : _type_, optional Attribut... | 2 | stack_v2_sparse_classes_30k_train_000660 | Implement the Python class `ConsumerSolutionLabeled` described below.
Class description:
Class to allow for solution interpolation using xarray. Represents a solution object for labeled models.
Method signatures and docstrings:
- def __init__(self, value: ValueFuncCRRALabeled, policy: xr.Dataset, continuation: ValueF... | Implement the Python class `ConsumerSolutionLabeled` described below.
Class description:
Class to allow for solution interpolation using xarray. Represents a solution object for labeled models.
Method signatures and docstrings:
- def __init__(self, value: ValueFuncCRRALabeled, policy: xr.Dataset, continuation: ValueF... | 7ce7138b6d9617a28fd4448936be3d61acad21d8 | <|skeleton|>
class ConsumerSolutionLabeled:
"""Class to allow for solution interpolation using xarray. Represents a solution object for labeled models."""
def __init__(self, value: ValueFuncCRRALabeled, policy: xr.Dataset, continuation: ValueFuncCRRALabeled, attrs=None):
"""Consumer Solution for labele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConsumerSolutionLabeled:
"""Class to allow for solution interpolation using xarray. Represents a solution object for labeled models."""
def __init__(self, value: ValueFuncCRRALabeled, policy: xr.Dataset, continuation: ValueFuncCRRALabeled, attrs=None):
"""Consumer Solution for labeled models. Par... | the_stack_v2_python_sparse | HARK/ConsumptionSaving/ConsLabeledModel.py | econ-ark/HARK | train | 315 |
fce59d35390e58115b540b80fb507735f53a267c | [
"valid, message = json_validate(nrange, {'type': 'object', 'properties': {'lower': {'$ref': '#/pScheduler/Numeric'}, 'upper': {'$ref': '#/pScheduler/Numeric'}}, 'additionalProperties': False, 'required': ['lower', 'upper']})\nif not valid:\n raise ValueError('Invalid numeric range: %s' % message)\nlower = nrange... | <|body_start_0|>
valid, message = json_validate(nrange, {'type': 'object', 'properties': {'lower': {'$ref': '#/pScheduler/Numeric'}, 'upper': {'$ref': '#/pScheduler/Numeric'}}, 'additionalProperties': False, 'required': ['lower', 'upper']})
if not valid:
raise ValueError('Invalid numeric ran... | Range of numbers | NumericRange | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumericRange:
"""Range of numbers"""
def __init__(self, nrange):
"""Construct a range from a JSON NumericRange."""
<|body_0|>
def __contains__(self, number):
"""See if the range contains the specified number, which can be any Numeric."""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus_train_002971 | 2,607 | permissive | [
{
"docstring": "Construct a range from a JSON NumericRange.",
"name": "__init__",
"signature": "def __init__(self, nrange)"
},
{
"docstring": "See if the range contains the specified number, which can be any Numeric.",
"name": "__contains__",
"signature": "def __contains__(self, number)"... | 3 | stack_v2_sparse_classes_30k_train_035090 | Implement the Python class `NumericRange` described below.
Class description:
Range of numbers
Method signatures and docstrings:
- def __init__(self, nrange): Construct a range from a JSON NumericRange.
- def __contains__(self, number): See if the range contains the specified number, which can be any Numeric.
- def c... | Implement the Python class `NumericRange` described below.
Class description:
Range of numbers
Method signatures and docstrings:
- def __init__(self, nrange): Construct a range from a JSON NumericRange.
- def __contains__(self, number): See if the range contains the specified number, which can be any Numeric.
- def c... | f6d04c0455e5be4d490df16ec1acb377f9025d9f | <|skeleton|>
class NumericRange:
"""Range of numbers"""
def __init__(self, nrange):
"""Construct a range from a JSON NumericRange."""
<|body_0|>
def __contains__(self, number):
"""See if the range contains the specified number, which can be any Numeric."""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumericRange:
"""Range of numbers"""
def __init__(self, nrange):
"""Construct a range from a JSON NumericRange."""
valid, message = json_validate(nrange, {'type': 'object', 'properties': {'lower': {'$ref': '#/pScheduler/Numeric'}, 'upper': {'$ref': '#/pScheduler/Numeric'}}, 'additionalPro... | the_stack_v2_python_sparse | python-pscheduler/pscheduler/pscheduler/numericrange.py | perfsonar/pscheduler | train | 53 |
e2e02221f82041ec26f92af88c2f8c61deb22fa2 | [
"old_namespaced_oligotype = NamespacedOligotypesModel.query.filter((NamespacedOligotypesModel.namespace == namespaced_oligotype.namespace) & (NamespacedOligotypesModel.oligotype == namespaced_oligotype.oligotype)).first()\nif old_namespaced_oligotype:\n return (False, from_dict(NamespacedOligotype, old_namespace... | <|body_start_0|>
old_namespaced_oligotype = NamespacedOligotypesModel.query.filter((NamespacedOligotypesModel.namespace == namespaced_oligotype.namespace) & (NamespacedOligotypesModel.oligotype == namespaced_oligotype.oligotype)).first()
if old_namespaced_oligotype:
return (False, from_dict(... | A manager of Namespaced Oligotypes model. | NamespacesdOligotypeRepositoryManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NamespacesdOligotypeRepositoryManager:
"""A manager of Namespaced Oligotypes model."""
def get_or_create(namespaced_oligotype: NamespacedOligotype) -> Tuple[bool, NamespacedOligotype]:
"""Insert a single record into database. Args: namespaced_oligotype (NamespacedOligotype): A single... | stack_v2_sparse_classes_75kplus_train_002972 | 3,211 | no_license | [
{
"docstring": "Insert a single record into database. Args: namespaced_oligotype (NamespacedOligotype): A single namespaced oligotype entity. Returns: Tuple[bool, NamespacesdOligotype]: A boolean indicating if the namespace was created (True) or recovered from database (False), and a instance of the created nam... | 2 | stack_v2_sparse_classes_30k_train_048975 | Implement the Python class `NamespacesdOligotypeRepositoryManager` described below.
Class description:
A manager of Namespaced Oligotypes model.
Method signatures and docstrings:
- def get_or_create(namespaced_oligotype: NamespacedOligotype) -> Tuple[bool, NamespacedOligotype]: Insert a single record into database. A... | Implement the Python class `NamespacesdOligotypeRepositoryManager` described below.
Class description:
A manager of Namespaced Oligotypes model.
Method signatures and docstrings:
- def get_or_create(namespaced_oligotype: NamespacedOligotype) -> Tuple[bool, NamespacedOligotype]: Insert a single record into database. A... | 5d240fea783a453137c9a3697b67dae67b08a73d | <|skeleton|>
class NamespacesdOligotypeRepositoryManager:
"""A manager of Namespaced Oligotypes model."""
def get_or_create(namespaced_oligotype: NamespacedOligotype) -> Tuple[bool, NamespacedOligotype]:
"""Insert a single record into database. Args: namespaced_oligotype (NamespacedOligotype): A single... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NamespacesdOligotypeRepositoryManager:
"""A manager of Namespaced Oligotypes model."""
def get_or_create(namespaced_oligotype: NamespacedOligotype) -> Tuple[bool, NamespacedOligotype]:
"""Insert a single record into database. Args: namespaced_oligotype (NamespacedOligotype): A single namespaced o... | the_stack_v2_python_sparse | src/adapters/repositories/oligotype_link.py | sgelias/blu | train | 0 |
62f2992408e88848645a4542def89fda4af6305f | [
"if isinstance(key, int):\n return HandoverInitiateFlag(key)\nreturn HandoverInitiateFlag[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nreturn cls(value)"
] | <|body_start_0|>
if isinstance(key, int):
return HandoverInitiateFlag(key)
return HandoverInitiateFlag[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
raise ValueError('%r is not a valid %s' % (value, cls.__name__))
ret... | [HandoverInitiateFlag] Handover Initiate Flags | HandoverInitiateFlag | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HandoverInitiateFlag:
"""[HandoverInitiateFlag] Handover Initiate Flags"""
def get(key: 'int | str', default: 'int'=-1) -> 'HandoverInitiateFlag':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<... | stack_v2_sparse_classes_75kplus_train_002973 | 1,561 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'HandoverInitiateFlag'"
},
{
"docstring": "Lookup function used when value is n... | 2 | stack_v2_sparse_classes_30k_train_041329 | Implement the Python class `HandoverInitiateFlag` described below.
Class description:
[HandoverInitiateFlag] Handover Initiate Flags
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'HandoverInitiateFlag': Backport support for original codes. Args: key: Key to get enum item. default... | Implement the Python class `HandoverInitiateFlag` described below.
Class description:
[HandoverInitiateFlag] Handover Initiate Flags
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'HandoverInitiateFlag': Backport support for original codes. Args: key: Key to get enum item. default... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class HandoverInitiateFlag:
"""[HandoverInitiateFlag] Handover Initiate Flags"""
def get(key: 'int | str', default: 'int'=-1) -> 'HandoverInitiateFlag':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HandoverInitiateFlag:
"""[HandoverInitiateFlag] Handover Initiate Flags"""
def get(key: 'int | str', default: 'int'=-1) -> 'HandoverInitiateFlag':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(... | the_stack_v2_python_sparse | pcapkit/const/mh/handover_initiate_flag.py | JarryShaw/PyPCAPKit | train | 204 |
35cff1223ef0a0c25984fa13e5418eb02e053a16 | [
"self.id = fragment.id\nself.name = fragment.name\nself.examine = fragment.examine\nself.icon = fragment.icon\nself.members = fragment.members\nself.value = fragment.value\nself.limit = fragment.limit\nself.lowalch = fragment.lowalch\nself.highalch = fragment.highalch",
"self.high = fragment.high\nself.highTime =... | <|body_start_0|>
self.id = fragment.id
self.name = fragment.name
self.examine = fragment.examine
self.icon = fragment.icon
self.members = fragment.members
self.value = fragment.value
self.limit = fragment.limit
self.lowalch = fragment.lowalch
self.... | A dataclass that represents the raw components of an Old School Runescape Item. Attributes: id (int): The item's internal id. name (str): The item's name. examine (str): The item's description. icon (str): The item's icon name on the Old School Wiki. members (bool): Whether the item is members-only. value (int): The it... | RunescapeItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunescapeItem:
"""A dataclass that represents the raw components of an Old School Runescape Item. Attributes: id (int): The item's internal id. name (str): The item's name. examine (str): The item's description. icon (str): The item's icon name on the Old School Wiki. members (bool): Whether the ... | stack_v2_sparse_classes_75kplus_train_002974 | 4,711 | permissive | [
{
"docstring": "A method that updates the item's internal data. Parameters: fragment (RunescapeItem): The RunescapeItem fragment to update the item with. Returns: None.",
"name": "update_with_mapping_fragment",
"signature": "def update_with_mapping_fragment(self, fragment: 'RunescapeItem') -> None"
},... | 2 | stack_v2_sparse_classes_30k_train_050887 | Implement the Python class `RunescapeItem` described below.
Class description:
A dataclass that represents the raw components of an Old School Runescape Item. Attributes: id (int): The item's internal id. name (str): The item's name. examine (str): The item's description. icon (str): The item's icon name on the Old Sc... | Implement the Python class `RunescapeItem` described below.
Class description:
A dataclass that represents the raw components of an Old School Runescape Item. Attributes: id (int): The item's internal id. name (str): The item's name. examine (str): The item's description. icon (str): The item's icon name on the Old Sc... | 16de7702fe5071aa731e863503ec28911eb64552 | <|skeleton|>
class RunescapeItem:
"""A dataclass that represents the raw components of an Old School Runescape Item. Attributes: id (int): The item's internal id. name (str): The item's name. examine (str): The item's description. icon (str): The item's icon name on the Old School Wiki. members (bool): Whether the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RunescapeItem:
"""A dataclass that represents the raw components of an Old School Runescape Item. Attributes: id (int): The item's internal id. name (str): The item's name. examine (str): The item's description. icon (str): The item's icon name on the Old School Wiki. members (bool): Whether the item is membe... | the_stack_v2_python_sparse | utils/runescape_data_classes.py | JakeSichley/Discord-Bot | train | 7 |
1f9f124b10872e561341b8548c1ddd4cd9dfc51e | [
"from distutils.sysconfig import get_python_lib\nlib_path = get_python_lib()\nproperty_file_path = os.path.join(lib_path, 'pyhanlp', 'static', 'hanlp.properties')\nhanlp_properties = Properties()\nhanlp_properties.load(open(property_file_path, encoding='utf-8'))\nroot_path = hanlp_properties['root']\ncustom_diction... | <|body_start_0|>
from distutils.sysconfig import get_python_lib
lib_path = get_python_lib()
property_file_path = os.path.join(lib_path, 'pyhanlp', 'static', 'hanlp.properties')
hanlp_properties = Properties()
hanlp_properties.load(open(property_file_path, encoding='utf-8'))
... | DictManagement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DictManagement:
def reload_dict(cls):
"""从数据库中获取词典更新到本地字库中 :return:"""
<|body_0|>
def upload_dict(cls, directory):
"""读取本地字典文件,上传到数据库中 注意:会清除数据库中已有的词典数据 (用于初始数据库) :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from distutils.sysconfig impo... | stack_v2_sparse_classes_75kplus_train_002975 | 3,274 | no_license | [
{
"docstring": "从数据库中获取词典更新到本地字库中 :return:",
"name": "reload_dict",
"signature": "def reload_dict(cls)"
},
{
"docstring": "读取本地字典文件,上传到数据库中 注意:会清除数据库中已有的词典数据 (用于初始数据库) :return:",
"name": "upload_dict",
"signature": "def upload_dict(cls, directory)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040786 | Implement the Python class `DictManagement` described below.
Class description:
Implement the DictManagement class.
Method signatures and docstrings:
- def reload_dict(cls): 从数据库中获取词典更新到本地字库中 :return:
- def upload_dict(cls, directory): 读取本地字典文件,上传到数据库中 注意:会清除数据库中已有的词典数据 (用于初始数据库) :return: | Implement the Python class `DictManagement` described below.
Class description:
Implement the DictManagement class.
Method signatures and docstrings:
- def reload_dict(cls): 从数据库中获取词典更新到本地字库中 :return:
- def upload_dict(cls, directory): 读取本地字典文件,上传到数据库中 注意:会清除数据库中已有的词典数据 (用于初始数据库) :return:
<|skeleton|>
class DictMana... | cacbcc9401f935e3fdf3c02d0f9fde47ba4df7d8 | <|skeleton|>
class DictManagement:
def reload_dict(cls):
"""从数据库中获取词典更新到本地字库中 :return:"""
<|body_0|>
def upload_dict(cls, directory):
"""读取本地字典文件,上传到数据库中 注意:会清除数据库中已有的词典数据 (用于初始数据库) :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DictManagement:
def reload_dict(cls):
"""从数据库中获取词典更新到本地字库中 :return:"""
from distutils.sysconfig import get_python_lib
lib_path = get_python_lib()
property_file_path = os.path.join(lib_path, 'pyhanlp', 'static', 'hanlp.properties')
hanlp_properties = Properties()
... | the_stack_v2_python_sparse | ns_ai_system/condition_identification/dict_management/dict_manage.py | fishersosoo/NS_policy_recommendation | train | 4 | |
cf2497b4dca4b16dcaae6aa90f864e6b5fb1bb27 | [
"test_result, results = result_info.build_test_result('fake_test_id', 123.4, test_harness='unit_tests', test_environment='unit_test_env')\nsystem_info = result_info.build_system_info(platform='aws', platform_type='p3.8xlarge')\ntest_info = result_info.build_test_info(batch_size=32, group_run_id='0000-uuid')\nmock_u... | <|body_start_0|>
test_result, results = result_info.build_test_result('fake_test_id', 123.4, test_harness='unit_tests', test_environment='unit_test_env')
system_info = result_info.build_system_info(platform='aws', platform_type='p3.8xlarge')
test_info = result_info.build_test_info(batch_size=32,... | TestResultUpload | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestResultUpload:
def test_build_row(self):
"""Tests creating row to be inserted. Test is too big but currently test aspects of `result_info` along with creating the final row with `result_upload`."""
<|body_0|>
def test_upload_stream(self, stream_upload, bigquery, google):
... | stack_v2_sparse_classes_75kplus_train_002976 | 4,915 | permissive | [
{
"docstring": "Tests creating row to be inserted. Test is too big but currently test aspects of `result_info` along with creating the final row with `result_upload`.",
"name": "test_build_row",
"signature": "def test_build_row(self)"
},
{
"docstring": "Tests calls to steam upload with mock inse... | 2 | null | Implement the Python class `TestResultUpload` described below.
Class description:
Implement the TestResultUpload class.
Method signatures and docstrings:
- def test_build_row(self): Tests creating row to be inserted. Test is too big but currently test aspects of `result_info` along with creating the final row with `r... | Implement the Python class `TestResultUpload` described below.
Class description:
Implement the TestResultUpload class.
Method signatures and docstrings:
- def test_build_row(self): Tests creating row to be inserted. Test is too big but currently test aspects of `result_info` along with creating the final row with `r... | b9f84203edad5e7e92161a9a634319db99631f3a | <|skeleton|>
class TestResultUpload:
def test_build_row(self):
"""Tests creating row to be inserted. Test is too big but currently test aspects of `result_info` along with creating the final row with `result_upload`."""
<|body_0|>
def test_upload_stream(self, stream_upload, bigquery, google):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestResultUpload:
def test_build_row(self):
"""Tests creating row to be inserted. Test is too big but currently test aspects of `result_info` along with creating the final row with `result_upload`."""
test_result, results = result_info.build_test_result('fake_test_id', 123.4, test_harness='uni... | the_stack_v2_python_sparse | oss_bench/upload/result_upload_test.py | tfboyd/benchmark_harness | train | 7 | |
d784e75e1332e735b4cfbf60db54088ca02a7d79 | [
"import sys\nprint(request, view, file=sys.stderr)\nreturn True",
"import sys\nprint(request, view, file=sys.stderr)\nreturn True"
] | <|body_start_0|>
import sys
print(request, view, file=sys.stderr)
return True
<|end_body_0|>
<|body_start_1|>
import sys
print(request, view, file=sys.stderr)
return True
<|end_body_1|>
| Grant permissions based on rules from ``django-rules`` library. | DjangoRulesPermission | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DjangoRulesPermission:
"""Grant permissions based on rules from ``django-rules`` library."""
def has_permission(self, request, view):
"""Return ``True`` if permission is granted, ``False`` otherwise."""
<|body_0|>
def has_object_permission(self, request, view, obj):
... | stack_v2_sparse_classes_75kplus_train_002977 | 3,599 | permissive | [
{
"docstring": "Return ``True`` if permission is granted, ``False`` otherwise.",
"name": "has_permission",
"signature": "def has_permission(self, request, view)"
},
{
"docstring": "Return ``True`` if permission is granted, ``False`` otherwise.",
"name": "has_object_permission",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_032279 | Implement the Python class `DjangoRulesPermission` described below.
Class description:
Grant permissions based on rules from ``django-rules`` library.
Method signatures and docstrings:
- def has_permission(self, request, view): Return ``True`` if permission is granted, ``False`` otherwise.
- def has_object_permission... | Implement the Python class `DjangoRulesPermission` described below.
Class description:
Grant permissions based on rules from ``django-rules`` library.
Method signatures and docstrings:
- def has_permission(self, request, view): Return ``True`` if permission is granted, ``False`` otherwise.
- def has_object_permission... | 6e16190fc34c54d834ecd23888a462f3af47611d | <|skeleton|>
class DjangoRulesPermission:
"""Grant permissions based on rules from ``django-rules`` library."""
def has_permission(self, request, view):
"""Return ``True`` if permission is granted, ``False`` otherwise."""
<|body_0|>
def has_object_permission(self, request, view, obj):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DjangoRulesPermission:
"""Grant permissions based on rules from ``django-rules`` library."""
def has_permission(self, request, view):
"""Return ``True`` if permission is granted, ``False`` otherwise."""
import sys
print(request, view, file=sys.stderr)
return True
def ... | the_stack_v2_python_sparse | flowcelltool/django_rules_rest_perms.py | bihealth/flowcelltool | train | 7 |
48915b02fde39b705ceae53fb5e7533d051eb798 | [
"nodeValuePairs = self.fetch('nodeValuePairs', None)\nfor nodeValuePair in nodeValuePairs:\n node = nodeValuePair[0]\n value = nodeValuePair[1]\n self.setNodeDatum(node, value)\nself.puts(success=True)\nreturn",
"if not cmds.attributeQuery('datum', node=node, exists=True):\n cmds.addAttr(node, longNam... | <|body_start_0|>
nodeValuePairs = self.fetch('nodeValuePairs', None)
for nodeValuePair in nodeValuePairs:
node = nodeValuePair[0]
value = nodeValuePair[1]
self.setNodeDatum(node, value)
self.puts(success=True)
return
<|end_body_0|>
<|body_start_1|>
... | A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed else False | SetNodeDatum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetNodeDatum:
"""A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed else False"""
def run(self, *args, **... | stack_v2_sparse_classes_75kplus_train_002978 | 1,869 | no_license | [
{
"docstring": "Sets the prev and next links for a list of node-value pairs that provide information about the prev and next to each specified node.",
"name": "run",
"signature": "def run(self, *args, **kwargs)"
},
{
"docstring": "Sets the node's datum value, creating the attribute if not alread... | 2 | stack_v2_sparse_classes_30k_train_049722 | Implement the Python class `SetNodeDatum` described below.
Class description:
A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed els... | Implement the Python class `SetNodeDatum` described below.
Class description:
A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed els... | c795ed7cfab512ad340ff88c8c0e67237ac2dfc5 | <|skeleton|>
class SetNodeDatum:
"""A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed else False"""
def run(self, *args, **... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SetNodeDatum:
"""A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed else False"""
def run(self, *args, **kwargs):
... | the_stack_v2_python_sparse | src/cadence/mayan/trackway/SetNodeDatum.py | satello/Cadence | train | 0 |
fab06a0ca675d768c4c1fa38948b3e3f7dad73d4 | [
"def dfs(i, j):\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n for dir in directions:\n row = i + dir[0]\n col = j + dir[1]\n if row >= 0 and row < m and (col >= 0) and (col < n) and (grid[row][col] == '1'):\n grid[row][col] = '0'\n dfs(row, col)\nres = 0\nm = l... | <|body_start_0|>
def dfs(i, j):
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dir in directions:
row = i + dir[0]
col = j + dir[1]
if row >= 0 and row < m and (col >= 0) and (col < n) and (grid[row][col] == '1'):
g... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numIslands_dfs(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def numIslands_bfs(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(i, j):
... | stack_v2_sparse_classes_75kplus_train_002979 | 2,252 | no_license | [
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands_dfs",
"signature": "def numIslands_dfs(self, grid)"
},
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands_bfs",
"signature": "def numIslands_bfs(self, grid)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands_dfs(self, grid): :type grid: List[List[str]] :rtype: int
- def numIslands_bfs(self, grid): :type grid: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands_dfs(self, grid): :type grid: List[List[str]] :rtype: int
- def numIslands_bfs(self, grid): :type grid: List[List[str]] :rtype: int
<|skeleton|>
class Solution:
... | 2e1751263f484709102f7f2caf18776a004c8230 | <|skeleton|>
class Solution:
def numIslands_dfs(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def numIslands_bfs(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numIslands_dfs(self, grid):
""":type grid: List[List[str]] :rtype: int"""
def dfs(i, j):
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dir in directions:
row = i + dir[0]
col = j + dir[1]
if row >= 0 an... | the_stack_v2_python_sparse | Python/Leetcode Daily Practice/DFS/200. Number of Islands.py | YaqianQi/Algorithm-and-Data-Structure | train | 1 | |
920f7b98e248f836c90086ca7e8d13fc00973ba6 | [
"try:\n org = Organization.objects.get(pk=organization_pk)\nexcept ObjectDoesNotExist:\n return JsonResponse({'status': 'error', 'message': 'Could not retrieve organization at organization_pk = ' + str(organization_pk)}, status=status.HTTP_404_NOT_FOUND)\nusers = []\nfor u in org.organizationuser_set.all():\n... | <|body_start_0|>
try:
org = Organization.objects.get(pk=organization_pk)
except ObjectDoesNotExist:
return JsonResponse({'status': 'error', 'message': 'Could not retrieve organization at organization_pk = ' + str(organization_pk)}, status=status.HTTP_404_NOT_FOUND)
users ... | OrganizationUserViewSet | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationUserViewSet:
def list(self, request, organization_pk):
"""Retrieve all users belonging to an org."""
<|body_0|>
def add(self, request, organization_pk, pk):
"""Adds an existing user to an organization as an owner."""
<|body_1|>
def remove(sel... | stack_v2_sparse_classes_75kplus_train_002980 | 5,593 | permissive | [
{
"docstring": "Retrieve all users belonging to an org.",
"name": "list",
"signature": "def list(self, request, organization_pk)"
},
{
"docstring": "Adds an existing user to an organization as an owner.",
"name": "add",
"signature": "def add(self, request, organization_pk, pk)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_049184 | Implement the Python class `OrganizationUserViewSet` described below.
Class description:
Implement the OrganizationUserViewSet class.
Method signatures and docstrings:
- def list(self, request, organization_pk): Retrieve all users belonging to an org.
- def add(self, request, organization_pk, pk): Adds an existing us... | Implement the Python class `OrganizationUserViewSet` described below.
Class description:
Implement the OrganizationUserViewSet class.
Method signatures and docstrings:
- def list(self, request, organization_pk): Retrieve all users belonging to an org.
- def add(self, request, organization_pk, pk): Adds an existing us... | 680b6a2b45f3c568d779d8ac86553a0b08c384c8 | <|skeleton|>
class OrganizationUserViewSet:
def list(self, request, organization_pk):
"""Retrieve all users belonging to an org."""
<|body_0|>
def add(self, request, organization_pk, pk):
"""Adds an existing user to an organization as an owner."""
<|body_1|>
def remove(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrganizationUserViewSet:
def list(self, request, organization_pk):
"""Retrieve all users belonging to an org."""
try:
org = Organization.objects.get(pk=organization_pk)
except ObjectDoesNotExist:
return JsonResponse({'status': 'error', 'message': 'Could not retr... | the_stack_v2_python_sparse | seed/views/v3/organization_users.py | SEED-platform/seed | train | 108 | |
f1e66f42e5ae4b77454c5db1a60b744941e1d083 | [
"self.mol = mol\nself.mints = mints\nself.V_nuc = mol.nuclear_repulsion_energy()\nself.T = np.matrix(mints.ao_kinetic())\nself.S = np.matrix(mints.ao_overlap())\nself.V = np.matrix(mints.ao_potential())\nself.g = np.array(mints.ao_eri()).swapaxes(1, 2)\nself.nelec = -mol.molecular_charge()\nfor A in range(mol.natom... | <|body_start_0|>
self.mol = mol
self.mints = mints
self.V_nuc = mol.nuclear_repulsion_energy()
self.T = np.matrix(mints.ao_kinetic())
self.S = np.matrix(mints.ao_overlap())
self.V = np.matrix(mints.ao_potential())
self.g = np.array(mints.ao_eri()).swapaxes(1, 2)
... | Restricted Hartree-Fock class for obtaining the restricted Hartree-Fock energy | RHF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RHF:
"""Restricted Hartree-Fock class for obtaining the restricted Hartree-Fock energy"""
def __init__(self, mol, mints):
"""Initialize the rhf :param mol: a Psi4 molecule object :param mints: a molecular integrals object (from MintsHelper)"""
<|body_0|>
def compute_ener... | stack_v2_sparse_classes_75kplus_train_002981 | 3,155 | no_license | [
{
"docstring": "Initialize the rhf :param mol: a Psi4 molecule object :param mints: a molecular integrals object (from MintsHelper)",
"name": "__init__",
"signature": "def __init__(self, mol, mints)"
},
{
"docstring": "Compute the rhf energy :return: energy",
"name": "compute_energy",
"s... | 2 | null | Implement the Python class `RHF` described below.
Class description:
Restricted Hartree-Fock class for obtaining the restricted Hartree-Fock energy
Method signatures and docstrings:
- def __init__(self, mol, mints): Initialize the rhf :param mol: a Psi4 molecule object :param mints: a molecular integrals object (from... | Implement the Python class `RHF` described below.
Class description:
Restricted Hartree-Fock class for obtaining the restricted Hartree-Fock energy
Method signatures and docstrings:
- def __init__(self, mol, mints): Initialize the rhf :param mol: a Psi4 molecule object :param mints: a molecular integrals object (from... | 2e8255ea548f13de6c492f649c4f2c4156f9995f | <|skeleton|>
class RHF:
"""Restricted Hartree-Fock class for obtaining the restricted Hartree-Fock energy"""
def __init__(self, mol, mints):
"""Initialize the rhf :param mol: a Psi4 molecule object :param mints: a molecular integrals object (from MintsHelper)"""
<|body_0|>
def compute_ener... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RHF:
"""Restricted Hartree-Fock class for obtaining the restricted Hartree-Fock energy"""
def __init__(self, mol, mints):
"""Initialize the rhf :param mol: a Psi4 molecule object :param mints: a molecular integrals object (from MintsHelper)"""
self.mol = mol
self.mints = mints
... | the_stack_v2_python_sparse | 4/aroeira/proj4.py | CCQC/summer-program | train | 35 |
eaefc59547875edc50de0780177ebe8d994e58e8 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | ACLServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ACLServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Read(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def Write(self, request, context):
"""Missing associated documentation c... | stack_v2_sparse_classes_75kplus_train_002982 | 11,076 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Read",
"signature": "def Read(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Write",
"signature": "def Write(self, request, context)"
},
... | 6 | stack_v2_sparse_classes_30k_val_002437 | Implement the Python class `ACLServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Read(self, request, context): Missing associated documentation comment in .proto file.
- def Write(self, request, context): Missing assoc... | Implement the Python class `ACLServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Read(self, request, context): Missing associated documentation comment in .proto file.
- def Write(self, request, context): Missing assoc... | b94598eca5db7dd1746cc6f49c5cd0c76961b9c2 | <|skeleton|>
class ACLServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Read(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def Write(self, request, context):
"""Missing associated documentation c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ACLServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Read(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | authzed/api/v0/acl_service_pb2_grpc.py | hercules261188/authzed-py | train | 0 |
3d069d8c71a3eb91ba21980466176d5bc4163b97 | [
"self.w = w\nself.lst = []\nself.seed = seed\npass",
"file_name = f'random_{self.w}.v'\nseed = self.seed\nw = self.w\nwith open(file_name, 'w') as fd:\n gv = verilog(fd)\n comment_list = []\n comment_list += [f'random size is 2**{self.w}']\n comment_list += [f'the seed is {self.seed}']\n comment_li... | <|body_start_0|>
self.w = w
self.lst = []
self.seed = seed
pass
<|end_body_0|>
<|body_start_1|>
file_name = f'random_{self.w}.v'
seed = self.seed
w = self.w
with open(file_name, 'w') as fd:
gv = verilog(fd)
comment_list = []
... | generate_random | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class generate_random:
def __init__(self, w=3, seed=0):
"""parameter @w : 2**w random or w_bit random parameeter @seed: init value"""
<|body_0|>
def generate_verilog(self):
"""generate random_{self.w}.v"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self... | stack_v2_sparse_classes_75kplus_train_002983 | 1,798 | no_license | [
{
"docstring": "parameter @w : 2**w random or w_bit random parameeter @seed: init value",
"name": "__init__",
"signature": "def __init__(self, w=3, seed=0)"
},
{
"docstring": "generate random_{self.w}.v",
"name": "generate_verilog",
"signature": "def generate_verilog(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025018 | Implement the Python class `generate_random` described below.
Class description:
Implement the generate_random class.
Method signatures and docstrings:
- def __init__(self, w=3, seed=0): parameter @w : 2**w random or w_bit random parameeter @seed: init value
- def generate_verilog(self): generate random_{self.w}.v | Implement the Python class `generate_random` described below.
Class description:
Implement the generate_random class.
Method signatures and docstrings:
- def __init__(self, w=3, seed=0): parameter @w : 2**w random or w_bit random parameeter @seed: init value
- def generate_verilog(self): generate random_{self.w}.v
<... | 590ded7dfdf18e516272f6c7189b06db3fda6168 | <|skeleton|>
class generate_random:
def __init__(self, w=3, seed=0):
"""parameter @w : 2**w random or w_bit random parameeter @seed: init value"""
<|body_0|>
def generate_verilog(self):
"""generate random_{self.w}.v"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class generate_random:
def __init__(self, w=3, seed=0):
"""parameter @w : 2**w random or w_bit random parameeter @seed: init value"""
self.w = w
self.lst = []
self.seed = seed
pass
def generate_verilog(self):
"""generate random_{self.w}.v"""
file_name = f... | the_stack_v2_python_sparse | qqyk_code/fpga_code/generate_random.py | qqyk3321/graduate | train | 0 | |
50f8d7442322b239010632cd6c34d6a7a11f4d31 | [
"mocker.patch.object(client, 'get_detections', return_value=detections)\ncmd_res = get_detections_cmd(client, first_timestamp='')\nif detections:\n assert len(cmd_res.outputs) == len(detections.get('results'))\nelse:\n assert 'No detections found' in cmd_res.readable_output",
"mocker.patch.object(client, 'g... | <|body_start_0|>
mocker.patch.object(client, 'get_detections', return_value=detections)
cmd_res = get_detections_cmd(client, first_timestamp='')
if detections:
assert len(cmd_res.outputs) == len(detections.get('results'))
else:
assert 'No detections found' in cmd_... | TestCommands | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCommands:
def test_get_detections_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audits: Dict[str, Any]):
"""Test `vectra-get-events` method detections part."""
<|body_0|>
def test_get_audits_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audi... | stack_v2_sparse_classes_75kplus_train_002984 | 12,115 | permissive | [
{
"docstring": "Test `vectra-get-events` method detections part.",
"name": "test_get_detections_cmd",
"signature": "def test_get_detections_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audits: Dict[str, Any])"
},
{
"docstring": "Test `vectra-get-events` method audits part.",
... | 5 | stack_v2_sparse_classes_30k_train_020794 | Implement the Python class `TestCommands` described below.
Class description:
Implement the TestCommands class.
Method signatures and docstrings:
- def test_get_detections_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audits: Dict[str, Any]): Test `vectra-get-events` method detections part.
- def test_... | Implement the Python class `TestCommands` described below.
Class description:
Implement the TestCommands class.
Method signatures and docstrings:
- def test_get_detections_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audits: Dict[str, Any]): Test `vectra-get-events` method detections part.
- def test_... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestCommands:
def test_get_detections_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audits: Dict[str, Any]):
"""Test `vectra-get-events` method detections part."""
<|body_0|>
def test_get_audits_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCommands:
def test_get_detections_cmd(self, mocker: MockerFixture, detections: Dict[str, Any], audits: Dict[str, Any]):
"""Test `vectra-get-events` method detections part."""
mocker.patch.object(client, 'get_detections', return_value=detections)
cmd_res = get_detections_cmd(client,... | the_stack_v2_python_sparse | Packs/Vectra_AI/Integrations/VectraAIEventCollector/VectraAIEventCollector_test.py | demisto/content | train | 1,023 | |
f7fc39d9e469074f8a8a4a59ff4c623956483f2a | [
"try:\n first_name, last_name = response['name'].split(' ', 1)\nexcept:\n first_name = response['name']\n last_name = ''\nreturn {'username': response['screen_name'], 'email': '', 'fullname': response['name'], 'first_name': first_name, 'last_name': last_name}",
"token = super(TwitterBackend, cls).tokens(... | <|body_start_0|>
try:
first_name, last_name = response['name'].split(' ', 1)
except:
first_name = response['name']
last_name = ''
return {'username': response['screen_name'], 'email': '', 'fullname': response['name'], 'first_name': first_name, 'last_name': las... | Twitter OAuth authentication backend | TwitterBackend | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwitterBackend:
"""Twitter OAuth authentication backend"""
def get_user_details(self, response):
"""Return user details from Twitter account"""
<|body_0|>
def tokens(cls, instance):
"""Return the tokens needed to authenticate the access to any API the service mig... | stack_v2_sparse_classes_75kplus_train_002985 | 3,324 | permissive | [
{
"docstring": "Return user details from Twitter account",
"name": "get_user_details",
"signature": "def get_user_details(self, response)"
},
{
"docstring": "Return the tokens needed to authenticate the access to any API the service might provide. Twitter uses a pair of OAuthToken consisting of ... | 2 | stack_v2_sparse_classes_30k_train_000936 | Implement the Python class `TwitterBackend` described below.
Class description:
Twitter OAuth authentication backend
Method signatures and docstrings:
- def get_user_details(self, response): Return user details from Twitter account
- def tokens(cls, instance): Return the tokens needed to authenticate the access to an... | Implement the Python class `TwitterBackend` described below.
Class description:
Twitter OAuth authentication backend
Method signatures and docstrings:
- def get_user_details(self, response): Return user details from Twitter account
- def tokens(cls, instance): Return the tokens needed to authenticate the access to an... | e47512f568b7dc7d247d0f667d8ef34972beb1d1 | <|skeleton|>
class TwitterBackend:
"""Twitter OAuth authentication backend"""
def get_user_details(self, response):
"""Return user details from Twitter account"""
<|body_0|>
def tokens(cls, instance):
"""Return the tokens needed to authenticate the access to any API the service mig... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwitterBackend:
"""Twitter OAuth authentication backend"""
def get_user_details(self, response):
"""Return user details from Twitter account"""
try:
first_name, last_name = response['name'].split(' ', 1)
except:
first_name = response['name']
las... | the_stack_v2_python_sparse | social_auth/backends/twitter.py | gugu/django-social-auth-1 | train | 3 |
fadde5d11e11e098fb24fcd2cd04abbd229e063f | [
"children = children or []\nsuper(AccordionWithThread, self).__init__(children=children, **kwargs)\nself._thread = None\nself._device_list = None",
"if hasattr(self, '_thread'):\n try:\n self._thread.do_run = False\n self._thread.join()\n except Exception:\n pass\nself.close()"
] | <|body_start_0|>
children = children or []
super(AccordionWithThread, self).__init__(children=children, **kwargs)
self._thread = None
self._device_list = None
<|end_body_0|>
<|body_start_1|>
if hasattr(self, '_thread'):
try:
self._thread.do_run = Fals... | An ``Accordion`` that will close an attached thread. | AccordionWithThread | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccordionWithThread:
"""An ``Accordion`` that will close an attached thread."""
def __init__(self, children: Optional[List]=None, **kwargs: Any):
"""AccordionWithThread constructor. Args: children: A list of widgets to be attached to the accordion. **kwargs: Additional keywords to be... | stack_v2_sparse_classes_75kplus_train_002986 | 13,104 | permissive | [
{
"docstring": "AccordionWithThread constructor. Args: children: A list of widgets to be attached to the accordion. **kwargs: Additional keywords to be passed to ``ipywidgets.Accordion``.",
"name": "__init__",
"signature": "def __init__(self, children: Optional[List]=None, **kwargs: Any)"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_050964 | Implement the Python class `AccordionWithThread` described below.
Class description:
An ``Accordion`` that will close an attached thread.
Method signatures and docstrings:
- def __init__(self, children: Optional[List]=None, **kwargs: Any): AccordionWithThread constructor. Args: children: A list of widgets to be attac... | Implement the Python class `AccordionWithThread` described below.
Class description:
An ``Accordion`` that will close an attached thread.
Method signatures and docstrings:
- def __init__(self, children: Optional[List]=None, **kwargs: Any): AccordionWithThread constructor. Args: children: A list of widgets to be attac... | 590f68d9ddb42a45c4ac8a8626ea60da85575b21 | <|skeleton|>
class AccordionWithThread:
"""An ``Accordion`` that will close an attached thread."""
def __init__(self, children: Optional[List]=None, **kwargs: Any):
"""AccordionWithThread constructor. Args: children: A list of widgets to be attached to the accordion. **kwargs: Additional keywords to be... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccordionWithThread:
"""An ``Accordion`` that will close an attached thread."""
def __init__(self, children: Optional[List]=None, **kwargs: Any):
"""AccordionWithThread constructor. Args: children: A list of widgets to be attached to the accordion. **kwargs: Additional keywords to be passed to ``... | the_stack_v2_python_sparse | qiskit/providers/ibmq/jupyter/dashboard/dashboard.py | Qiskit/qiskit-ibmq-provider | train | 240 |
5240813d24a07cfb3e96f511efc25f5d9e498a37 | [
"super().__init__()\nself.ignore = ignore\nif reduced:\n self.loss_fn = partial(reduced_focal_loss, gamma=gamma, threshold=threshold, reduction=reduction)\nelse:\n self.loss_fn = partial(sigmoid_focal_loss, gamma=gamma, alpha=alpha, reduction=reduction)",
"targets = targets.view(-1)\nlogits = logits.view(-1... | <|body_start_0|>
super().__init__()
self.ignore = ignore
if reduced:
self.loss_fn = partial(reduced_focal_loss, gamma=gamma, threshold=threshold, reduction=reduction)
else:
self.loss_fn = partial(sigmoid_focal_loss, gamma=gamma, alpha=alpha, reduction=reduction)
<... | FocalLossBinary | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FocalLossBinary:
def __init__(self, ignore: int=None, reduced: bool=False, gamma: float=2.0, alpha: float=0.25, threshold: float=0.5, reduction: str='mean'):
"""Compute focal loss for binary classification problem."""
<|body_0|>
def forward(self, logits, targets):
""... | stack_v2_sparse_classes_75kplus_train_002987 | 6,748 | permissive | [
{
"docstring": "Compute focal loss for binary classification problem.",
"name": "__init__",
"signature": "def __init__(self, ignore: int=None, reduced: bool=False, gamma: float=2.0, alpha: float=0.25, threshold: float=0.5, reduction: str='mean')"
},
{
"docstring": "Args: logits: [bs; ...] target... | 2 | null | Implement the Python class `FocalLossBinary` described below.
Class description:
Implement the FocalLossBinary class.
Method signatures and docstrings:
- def __init__(self, ignore: int=None, reduced: bool=False, gamma: float=2.0, alpha: float=0.25, threshold: float=0.5, reduction: str='mean'): Compute focal loss for ... | Implement the Python class `FocalLossBinary` described below.
Class description:
Implement the FocalLossBinary class.
Method signatures and docstrings:
- def __init__(self, ignore: int=None, reduced: bool=False, gamma: float=2.0, alpha: float=0.25, threshold: float=0.5, reduction: str='mean'): Compute focal loss for ... | 5341684211e6d91dab6ad76a7595a95addff23be | <|skeleton|>
class FocalLossBinary:
def __init__(self, ignore: int=None, reduced: bool=False, gamma: float=2.0, alpha: float=0.25, threshold: float=0.5, reduction: str='mean'):
"""Compute focal loss for binary classification problem."""
<|body_0|>
def forward(self, logits, targets):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FocalLossBinary:
def __init__(self, ignore: int=None, reduced: bool=False, gamma: float=2.0, alpha: float=0.25, threshold: float=0.5, reduction: str='mean'):
"""Compute focal loss for binary classification problem."""
super().__init__()
self.ignore = ignore
if reduced:
... | the_stack_v2_python_sparse | nnunet/training/network_training/nnUNet_variants/loss_function/nnUNetTrainerV2_focalLoss.py | Gitsamshi/nnUNet-1 | train | 0 | |
47e92e04ff212f3d67d41e838ff703440ce24fae | [
"form = super(CreateAlbum, self).get_form()\nform.fields['pictures'].queryset = self.request.user.photo_set.all()\nreturn form",
"self.object = form.save(commit=False)\nself.object.user_id = self.request.user.id\nself.object.save()\nreturn super(CreateAlbum, self).form_valid(form)"
] | <|body_start_0|>
form = super(CreateAlbum, self).get_form()
form.fields['pictures'].queryset = self.request.user.photo_set.all()
return form
<|end_body_0|>
<|body_start_1|>
self.object = form.save(commit=False)
self.object.user_id = self.request.user.id
self.object.save(... | CreateAlbum | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateAlbum:
def get_form(self, form_class=None):
"""Returns an instance of the form to be used in this view."""
<|body_0|>
def form_valid(self, form, *args, **kwargs):
"""If the form is valid, save the associated model."""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_75kplus_train_002988 | 7,282 | permissive | [
{
"docstring": "Returns an instance of the form to be used in this view.",
"name": "get_form",
"signature": "def get_form(self, form_class=None)"
},
{
"docstring": "If the form is valid, save the associated model.",
"name": "form_valid",
"signature": "def form_valid(self, form, *args, **... | 2 | stack_v2_sparse_classes_30k_train_041466 | Implement the Python class `CreateAlbum` described below.
Class description:
Implement the CreateAlbum class.
Method signatures and docstrings:
- def get_form(self, form_class=None): Returns an instance of the form to be used in this view.
- def form_valid(self, form, *args, **kwargs): If the form is valid, save the ... | Implement the Python class `CreateAlbum` described below.
Class description:
Implement the CreateAlbum class.
Method signatures and docstrings:
- def get_form(self, form_class=None): Returns an instance of the form to be used in this view.
- def form_valid(self, form, *args, **kwargs): If the form is valid, save the ... | 8dcad442e78c047a544369a699839c7e1ec459bd | <|skeleton|>
class CreateAlbum:
def get_form(self, form_class=None):
"""Returns an instance of the form to be used in this view."""
<|body_0|>
def form_valid(self, form, *args, **kwargs):
"""If the form is valid, save the associated model."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateAlbum:
def get_form(self, form_class=None):
"""Returns an instance of the form to be used in this view."""
form = super(CreateAlbum, self).get_form()
form.fields['pictures'].queryset = self.request.user.photo_set.all()
return form
def form_valid(self, form, *args, **... | the_stack_v2_python_sparse | imagersite/imagersite/views.py | icarrera/django-imager | train | 0 | |
c6683ac9c4d1cc344c1d55a3550438bef33092b1 | [
"super().__init__()\nself.data = data\nself.args = args\nself.batch_size = args.batch_size\nself.num_workers = args.num_workers",
"num_samples = self.data.shape[0]\nnum_train = round(num_samples * self.args.splits[0])\nnum_test = round(num_samples * self.args.splits[1])\nnum_val = num_samples - num_train - num_te... | <|body_start_0|>
super().__init__()
self.data = data
self.args = args
self.batch_size = args.batch_size
self.num_workers = args.num_workers
<|end_body_0|>
<|body_start_1|>
num_samples = self.data.shape[0]
num_train = round(num_samples * self.args.splits[0])
... | PyTorch Lightning data module class for time series data. | DataModule | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataModule:
"""PyTorch Lightning data module class for time series data."""
def __init__(self, data, args):
"""Instantiates the data module. Args: data: the numpy array of time series data, with the shape (seq_len x num_nodes x num_features). args: python argparse.ArgumentParser clas... | stack_v2_sparse_classes_75kplus_train_002989 | 6,627 | permissive | [
{
"docstring": "Instantiates the data module. Args: data: the numpy array of time series data, with the shape (seq_len x num_nodes x num_features). args: python argparse.ArgumentParser class.",
"name": "__init__",
"signature": "def __init__(self, data, args)"
},
{
"docstring": "Splits the data a... | 5 | stack_v2_sparse_classes_30k_train_032761 | Implement the Python class `DataModule` described below.
Class description:
PyTorch Lightning data module class for time series data.
Method signatures and docstrings:
- def __init__(self, data, args): Instantiates the data module. Args: data: the numpy array of time series data, with the shape (seq_len x num_nodes x... | Implement the Python class `DataModule` described below.
Class description:
PyTorch Lightning data module class for time series data.
Method signatures and docstrings:
- def __init__(self, data, args): Instantiates the data module. Args: data: the numpy array of time series data, with the shape (seq_len x num_nodes x... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class DataModule:
"""PyTorch Lightning data module class for time series data."""
def __init__(self, data, args):
"""Instantiates the data module. Args: data: the numpy array of time series data, with the shape (seq_len x num_nodes x num_features). args: python argparse.ArgumentParser clas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataModule:
"""PyTorch Lightning data module class for time series data."""
def __init__(self, data, args):
"""Instantiates the data module. Args: data: the numpy array of time series data, with the shape (seq_len x num_nodes x num_features). args: python argparse.ArgumentParser class."""
... | the_stack_v2_python_sparse | editable_graph_temporal/data.py | Jimmy-INL/google-research | train | 1 |
9b8f70ecb5efc70b9fbb550bf94a8d9c9ddcdb8b | [
"self.m = m\nself.group = group\nself.fullscreen = fullscreen\nbtn = MapBtn(content=icon_content, v_on='menu.on')\nslot = {'name': 'activator', 'variable': 'menu', 'children': btn}\nchildren = [card_content]\nif isinstance(card_content, sw.Tile):\n card_title = card_content.get_title()\n card_content.nest()\n... | <|body_start_0|>
self.m = m
self.group = group
self.fullscreen = fullscreen
btn = MapBtn(content=icon_content, v_on='menu.on')
slot = {'name': 'activator', 'variable': 'menu', 'children': btn}
children = [card_content]
if isinstance(card_content, sw.Tile):
... | MenuControl | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuControl:
def __init__(self, icon_content: str, card_content: Union[v.VuetifyWidget, str], card_title: str='', m: Optional[Map]=None, group: int=0, fullscreen: bool=False, **kwargs) -> None:
"""Widget control displaying a btn on the map. When clicked the menu expand to show the conten... | stack_v2_sparse_classes_75kplus_train_002990 | 6,732 | permissive | [
{
"docstring": "Widget control displaying a btn on the map. When clicked the menu expand to show the content set by the user and all the others are closed. It's used to display interactive tiles directly in the map. If the card_content is a Tile it will be automatically nested. Args: icon_content: the icon cont... | 5 | stack_v2_sparse_classes_30k_train_001803 | Implement the Python class `MenuControl` described below.
Class description:
Implement the MenuControl class.
Method signatures and docstrings:
- def __init__(self, icon_content: str, card_content: Union[v.VuetifyWidget, str], card_title: str='', m: Optional[Map]=None, group: int=0, fullscreen: bool=False, **kwargs) ... | Implement the Python class `MenuControl` described below.
Class description:
Implement the MenuControl class.
Method signatures and docstrings:
- def __init__(self, icon_content: str, card_content: Union[v.VuetifyWidget, str], card_title: str='', m: Optional[Map]=None, group: int=0, fullscreen: bool=False, **kwargs) ... | b26c7d698659d5c5a2029d02fc94dcd9daf0df98 | <|skeleton|>
class MenuControl:
def __init__(self, icon_content: str, card_content: Union[v.VuetifyWidget, str], card_title: str='', m: Optional[Map]=None, group: int=0, fullscreen: bool=False, **kwargs) -> None:
"""Widget control displaying a btn on the map. When clicked the menu expand to show the conten... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MenuControl:
def __init__(self, icon_content: str, card_content: Union[v.VuetifyWidget, str], card_title: str='', m: Optional[Map]=None, group: int=0, fullscreen: bool=False, **kwargs) -> None:
"""Widget control displaying a btn on the map. When clicked the menu expand to show the content set by the u... | the_stack_v2_python_sparse | sepal_ui/mapping/menu_control.py | 12rambau/sepal_ui | train | 17 | |
dd3c30de538f893a183f0f7e21257470fbcd7bc9 | [
"obj = super(Bartels, cls).__new__(cls)\nparse(local_fname=local_fname, data_map=obj)\nobj._interval_map = OrderedDict()\ntimes_1 = [x.dt for x in obj.values()[:-1]]\ntimes_2 = [x.dt for x in obj.values()[1:]]\nfor b_id, (t1, t2) in zip(obj, zip(times_1, times_2)):\n interval = P.closed_open(t1, t2)\n obj._in... | <|body_start_0|>
obj = super(Bartels, cls).__new__(cls)
parse(local_fname=local_fname, data_map=obj)
obj._interval_map = OrderedDict()
times_1 = [x.dt for x in obj.values()[:-1]]
times_2 = [x.dt for x in obj.values()[1:]]
for b_id, (t1, t2) in zip(obj, zip(times_1, times_... | Bartels | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bartels:
def __new__(cls, local_fname=BARTELS_FNAME):
"""Build a new Bartels rotation information object."""
<|body_0|>
def __call__(self, dt):
"""Return the Bartels rotation number corresponding to the date time *dt*."""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_002991 | 4,515 | permissive | [
{
"docstring": "Build a new Bartels rotation information object.",
"name": "__new__",
"signature": "def __new__(cls, local_fname=BARTELS_FNAME)"
},
{
"docstring": "Return the Bartels rotation number corresponding to the date time *dt*.",
"name": "__call__",
"signature": "def __call__(sel... | 2 | stack_v2_sparse_classes_30k_train_006238 | Implement the Python class `Bartels` described below.
Class description:
Implement the Bartels class.
Method signatures and docstrings:
- def __new__(cls, local_fname=BARTELS_FNAME): Build a new Bartels rotation information object.
- def __call__(self, dt): Return the Bartels rotation number corresponding to the date... | Implement the Python class `Bartels` described below.
Class description:
Implement the Bartels class.
Method signatures and docstrings:
- def __new__(cls, local_fname=BARTELS_FNAME): Build a new Bartels rotation information object.
- def __call__(self, dt): Return the Bartels rotation number corresponding to the date... | e364be68cb0cadbeea10ca569963b8f99aa7b05b | <|skeleton|>
class Bartels:
def __new__(cls, local_fname=BARTELS_FNAME):
"""Build a new Bartels rotation information object."""
<|body_0|>
def __call__(self, dt):
"""Return the Bartels rotation number corresponding to the date time *dt*."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bartels:
def __new__(cls, local_fname=BARTELS_FNAME):
"""Build a new Bartels rotation information object."""
obj = super(Bartels, cls).__new__(cls)
parse(local_fname=local_fname, data_map=obj)
obj._interval_map = OrderedDict()
times_1 = [x.dt for x in obj.values()[:-1]]... | the_stack_v2_python_sparse | pyrsss/l1/bartels.py | butala/pyrsss | train | 7 | |
e1d49ea64349dc6c627cfde00cdc92aa9e0194d0 | [
"rows = table.find_all('tr')[1:]\npolls = []\nfor row in rows:\n columns = [tag.text for tag in row.find_all('td')]\n poll, time_stamp, sample, biden, sanders, gabbard, spread = columns\n start, end = [d.split('/') for d in time_stamp.split('-')]\n start = date(year=YEAR, month=int(start[0]), day=int(st... | <|body_start_0|>
rows = table.find_all('tr')[1:]
polls = []
for row in rows:
columns = [tag.text for tag in row.find_all('td')]
poll, time_stamp, sample, biden, sanders, gabbard, spread = columns
start, end = [d.split('/') for d in time_stamp.split('-')]
... | RealClearPolitics object. RealClearPolitics is a custom class to parse a Web instance from the realclearpolitics website. Variables: web: Web -- The web object stores the information needed to process the data. Methods: find_table: -> str -- Parses the Web object for table elements and returns the first one that it fin... | RealClearPolitics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RealClearPolitics:
"""RealClearPolitics object. RealClearPolitics is a custom class to parse a Web instance from the realclearpolitics website. Variables: web: Web -- The web object stores the information needed to process the data. Methods: find_table: -> str -- Parses the Web object for table e... | stack_v2_sparse_classes_75kplus_train_002992 | 14,220 | no_license | [
{
"docstring": "Parses the row data from the html table. Arguments: table {Soup} -- Parses a BeautifulSoup table element and returns the text found in the td elements as Poll namedtuples. Returns: List[Poll] -- List of Poll namedtuples that were created from the table data.",
"name": "parse_rows",
"sign... | 3 | stack_v2_sparse_classes_30k_train_035962 | Implement the Python class `RealClearPolitics` described below.
Class description:
RealClearPolitics object. RealClearPolitics is a custom class to parse a Web instance from the realclearpolitics website. Variables: web: Web -- The web object stores the information needed to process the data. Methods: find_table: -> s... | Implement the Python class `RealClearPolitics` described below.
Class description:
RealClearPolitics object. RealClearPolitics is a custom class to parse a Web instance from the realclearpolitics website. Variables: web: Web -- The web object stores the information needed to process the data. Methods: find_table: -> s... | 9f839af4ef400786b7c28701c2241f310bb4422c | <|skeleton|>
class RealClearPolitics:
"""RealClearPolitics object. RealClearPolitics is a custom class to parse a Web instance from the realclearpolitics website. Variables: web: Web -- The web object stores the information needed to process the data. Methods: find_table: -> str -- Parses the Web object for table e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RealClearPolitics:
"""RealClearPolitics object. RealClearPolitics is a custom class to parse a Web instance from the realclearpolitics website. Variables: web: Web -- The web object stores the information needed to process the data. Methods: find_table: -> str -- Parses the Web object for table elements and r... | the_stack_v2_python_sparse | 266/composition.py | StefanKaeser/pybites | train | 0 |
dae181908512fc13eee33af5eabff612512d3258 | [
"self.bpq = bpq\nself.curkey = bpq._max\nself.curitem = iter(bpq._bucket[bpq._max])",
"while self.curkey > 0:\n try:\n res = next(self.curitem)\n return res\n except StopIteration:\n self.curkey -= 1\n self.curitem = iter(self.bpq._bucket[self.curkey])\nraise StopIteration"
] | <|body_start_0|>
self.bpq = bpq
self.curkey = bpq._max
self.curitem = iter(bpq._bucket[bpq._max])
<|end_body_0|>
<|body_start_1|>
while self.curkey > 0:
try:
res = next(self.curitem)
return res
except StopIteration:
... | The BPQueueIterator class is a bounded priority queue iterator that allows traversal of the queue in descending order. Bounded Priority Queue Iterator. Traverse the queue in descending order. Detaching queue items may invalidate the iterator because the iterator makes a copy of current key. | BPQueueIterator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BPQueueIterator:
"""The BPQueueIterator class is a bounded priority queue iterator that allows traversal of the queue in descending order. Bounded Priority Queue Iterator. Traverse the queue in descending order. Detaching queue items may invalidate the iterator because the iterator makes a copy o... | stack_v2_sparse_classes_75kplus_train_002993 | 13,441 | permissive | [
{
"docstring": "The function initializes an object with a given BPQueue and sets the current key and item. :param bpq: The `bpq` parameter is of type `BPQueue`. It is an object that represents a bounded priority queue :type bpq: BPQueue Examples: >>> bpq = BPQueue(-3, 3) >>> a = Dllink([0, 3]) >>> bpq.append(a,... | 2 | null | Implement the Python class `BPQueueIterator` described below.
Class description:
The BPQueueIterator class is a bounded priority queue iterator that allows traversal of the queue in descending order. Bounded Priority Queue Iterator. Traverse the queue in descending order. Detaching queue items may invalidate the itera... | Implement the Python class `BPQueueIterator` described below.
Class description:
The BPQueueIterator class is a bounded priority queue iterator that allows traversal of the queue in descending order. Bounded Priority Queue Iterator. Traverse the queue in descending order. Detaching queue items may invalidate the itera... | 531a0c6c15d6091bcc58958b99be5b6e10c6c906 | <|skeleton|>
class BPQueueIterator:
"""The BPQueueIterator class is a bounded priority queue iterator that allows traversal of the queue in descending order. Bounded Priority Queue Iterator. Traverse the queue in descending order. Detaching queue items may invalidate the iterator because the iterator makes a copy o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BPQueueIterator:
"""The BPQueueIterator class is a bounded priority queue iterator that allows traversal of the queue in descending order. Bounded Priority Queue Iterator. Traverse the queue in descending order. Detaching queue items may invalidate the iterator because the iterator makes a copy of current key... | the_stack_v2_python_sparse | src/ckpttnpy/bpqueue.py | luk036/ckpttnpy | train | 4 |
bfbff613c763035c3fc211ea7f147d9ab4babfc5 | [
"self.base_dir = base_dir\ndevice = torch.device('cuda:{}'.format(gpu_id) if torch.cuda.is_available() and gpu_id != -1 else 'cpu')\noptions_file = os.path.join(base_dir, './scripts/elmo_files/elmo_2x4096_512_2048cnn_2xhighway_options.json')\nweight_file = os.path.join(base_dir, './scripts/elmo_files/elmo_2x4096_51... | <|body_start_0|>
self.base_dir = base_dir
device = torch.device('cuda:{}'.format(gpu_id) if torch.cuda.is_available() and gpu_id != -1 else 'cpu')
options_file = os.path.join(base_dir, './scripts/elmo_files/elmo_2x4096_512_2048cnn_2xhighway_options.json')
weight_file = os.path.join(base_... | DurationAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DurationAPI:
def __init__(self, base_dir='.', gpu_id=-1):
""":param int gpu_id: cuda device id (optional); default - cpu"""
<|body_0|>
def pred(self, events):
"""Model inference for ELMo baseline, given Events JSON :param list[dict] events: list of sentences and extr... | stack_v2_sparse_classes_75kplus_train_002994 | 4,787 | no_license | [
{
"docstring": ":param int gpu_id: cuda device id (optional); default - cpu",
"name": "__init__",
"signature": "def __init__(self, base_dir='.', gpu_id=-1)"
},
{
"docstring": "Model inference for ELMo baseline, given Events JSON :param list[dict] events: list of sentences and extracted event-tri... | 2 | stack_v2_sparse_classes_30k_train_051225 | Implement the Python class `DurationAPI` described below.
Class description:
Implement the DurationAPI class.
Method signatures and docstrings:
- def __init__(self, base_dir='.', gpu_id=-1): :param int gpu_id: cuda device id (optional); default - cpu
- def pred(self, events): Model inference for ELMo baseline, given ... | Implement the Python class `DurationAPI` described below.
Class description:
Implement the DurationAPI class.
Method signatures and docstrings:
- def __init__(self, base_dir='.', gpu_id=-1): :param int gpu_id: cuda device id (optional); default - cpu
- def pred(self, events): Model inference for ELMo baseline, given ... | 460945baa4aa5a40354f9cd610d330cb73ca0625 | <|skeleton|>
class DurationAPI:
def __init__(self, base_dir='.', gpu_id=-1):
""":param int gpu_id: cuda device id (optional); default - cpu"""
<|body_0|>
def pred(self, events):
"""Model inference for ELMo baseline, given Events JSON :param list[dict] events: list of sentences and extr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DurationAPI:
def __init__(self, base_dir='.', gpu_id=-1):
""":param int gpu_id: cuda device id (optional); default - cpu"""
self.base_dir = base_dir
device = torch.device('cuda:{}'.format(gpu_id) if torch.cuda.is_available() and gpu_id != -1 else 'cpu')
options_file = os.path.j... | the_stack_v2_python_sparse | component/Duration/inference_api.py | VincentWei2021/EventPlus | train | 0 | |
3cab08f6023958fa3a378954e15960f7d923ef74 | [
"milestones = milestones_api.milestone_get(milestone_id)\nif milestones:\n return wmodels.Milestone.from_db_model(milestones)\nelse:\n raise exc.NotFound(_('Milestone %s not found') % milestone_id)",
"if limit is not None:\n limit = max(0, limit)\nmarker_milestone = milestones_api.milestone_get(marker)\n... | <|body_start_0|>
milestones = milestones_api.milestone_get(milestone_id)
if milestones:
return wmodels.Milestone.from_db_model(milestones)
else:
raise exc.NotFound(_('Milestone %s not found') % milestone_id)
<|end_body_0|>
<|body_start_1|>
if limit is not None:
... | REST controller for milestones. | MilestonesController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MilestonesController:
"""REST controller for milestones."""
def get_one(self, milestone_id):
"""Retrieve information about the given milestone. :param milestone_id: Milestone ID."""
<|body_0|>
def get_all(self, marker=None, limit=None, name=None, branch_id=None, sort_fie... | stack_v2_sparse_classes_75kplus_train_002995 | 5,814 | permissive | [
{
"docstring": "Retrieve information about the given milestone. :param milestone_id: Milestone ID.",
"name": "get_one",
"signature": "def get_one(self, milestone_id)"
},
{
"docstring": "Retrieve a list of milestones. :param marker: The resource id where the page should begin. :param limit: The n... | 4 | stack_v2_sparse_classes_30k_test_000946 | Implement the Python class `MilestonesController` described below.
Class description:
REST controller for milestones.
Method signatures and docstrings:
- def get_one(self, milestone_id): Retrieve information about the given milestone. :param milestone_id: Milestone ID.
- def get_all(self, marker=None, limit=None, nam... | Implement the Python class `MilestonesController` described below.
Class description:
REST controller for milestones.
Method signatures and docstrings:
- def get_one(self, milestone_id): Retrieve information about the given milestone. :param milestone_id: Milestone ID.
- def get_all(self, marker=None, limit=None, nam... | 5833f87e20722c524a1e4a0b8e1fb82206fb4e5c | <|skeleton|>
class MilestonesController:
"""REST controller for milestones."""
def get_one(self, milestone_id):
"""Retrieve information about the given milestone. :param milestone_id: Milestone ID."""
<|body_0|>
def get_all(self, marker=None, limit=None, name=None, branch_id=None, sort_fie... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MilestonesController:
"""REST controller for milestones."""
def get_one(self, milestone_id):
"""Retrieve information about the given milestone. :param milestone_id: Milestone ID."""
milestones = milestones_api.milestone_get(milestone_id)
if milestones:
return wmodels.M... | the_stack_v2_python_sparse | storyboard/api/v1/milestones.py | Sitcode-Zoograf/storyboard | train | 0 |
7f42faacea5c1d96d4cea8c16cd04c602056ceb5 | [
"super().__init__(len(atom_features), targets, sample_weights=sample_weights, batch_size=batch_size, is_shuffle=is_shuffle)\nself.atom_features = atom_features\nself.bond_features = bond_features\nself.state_features = state_features\nself.index1_list = index1_list\nself.index2_list = index2_list",
"feature_list_... | <|body_start_0|>
super().__init__(len(atom_features), targets, sample_weights=sample_weights, batch_size=batch_size, is_shuffle=is_shuffle)
self.atom_features = atom_features
self.bond_features = bond_features
self.state_features = state_features
self.index1_list = index1_list
... | A generator class that assembles several structures (indicated by batch_size) and form (x, y) pairs for model training. | GraphBatchGenerator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphBatchGenerator:
"""A generator class that assembles several structures (indicated by batch_size) and form (x, y) pairs for model training."""
def __init__(self, atom_features: list[np.ndarray], bond_features: list[np.ndarray], state_features: list[np.ndarray], index1_list: list[int], in... | stack_v2_sparse_classes_75kplus_train_002996 | 25,174 | permissive | [
{
"docstring": "Args: atom_features: (list of np.array) list of atom feature matrix, bond_features: (list of np.array) list of bond features matrix state_features: (list of np.array) list of [1, G] state features, where G is the global state feature dimension index1_list: (list of integer) list of (M, ) one sid... | 2 | null | Implement the Python class `GraphBatchGenerator` described below.
Class description:
A generator class that assembles several structures (indicated by batch_size) and form (x, y) pairs for model training.
Method signatures and docstrings:
- def __init__(self, atom_features: list[np.ndarray], bond_features: list[np.nd... | Implement the Python class `GraphBatchGenerator` described below.
Class description:
A generator class that assembles several structures (indicated by batch_size) and form (x, y) pairs for model training.
Method signatures and docstrings:
- def __init__(self, atom_features: list[np.ndarray], bond_features: list[np.nd... | f3705760266f24b62c4810dd4abacfc25f4f64ae | <|skeleton|>
class GraphBatchGenerator:
"""A generator class that assembles several structures (indicated by batch_size) and form (x, y) pairs for model training."""
def __init__(self, atom_features: list[np.ndarray], bond_features: list[np.ndarray], state_features: list[np.ndarray], index1_list: list[int], in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraphBatchGenerator:
"""A generator class that assembles several structures (indicated by batch_size) and form (x, y) pairs for model training."""
def __init__(self, atom_features: list[np.ndarray], bond_features: list[np.ndarray], state_features: list[np.ndarray], index1_list: list[int], index2_list: li... | the_stack_v2_python_sparse | megnet/data/graph.py | materialsvirtuallab/megnet | train | 471 |
5b1862b63f11509a4477aebdd71e2dcb83b4ea71 | [
"statement = '\\n SELECT ST_AsKml({0}) AS kml\\n FROM {1}\\n WHERE id={2};\\n '.format(self.geometryColumnName, self.tableName, self.id)\nresult = session.execute(statement)\nfor row in result:\n return row.kml",
"statement = '\\n ... | <|body_start_0|>
statement = '\n SELECT ST_AsKml({0}) AS kml\n FROM {1}\n WHERE id={2};\n '.format(self.geometryColumnName, self.tableName, self.id)
result = session.execute(statement)
for row in result:
retu... | Abstract base class for geometric objects. | GeometricObjectBase | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeometricObjectBase:
"""Abstract base class for geometric objects."""
def getAsKml(self, session):
"""Retrieve the geometry in KML format. This method is a veneer for an SQL query that calls the ``ST_AsKml()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.sessi... | stack_v2_sparse_classes_75kplus_train_002997 | 4,099 | permissive | [
{
"docstring": "Retrieve the geometry in KML format. This method is a veneer for an SQL query that calls the ``ST_AsKml()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database. Returns: str: KML string representation... | 4 | stack_v2_sparse_classes_30k_train_033071 | Implement the Python class `GeometricObjectBase` described below.
Class description:
Abstract base class for geometric objects.
Method signatures and docstrings:
- def getAsKml(self, session): Retrieve the geometry in KML format. This method is a veneer for an SQL query that calls the ``ST_AsKml()`` function on the g... | Implement the Python class `GeometricObjectBase` described below.
Class description:
Abstract base class for geometric objects.
Method signatures and docstrings:
- def getAsKml(self, session): Retrieve the geometry in KML format. This method is a veneer for an SQL query that calls the ``ST_AsKml()`` function on the g... | 73832e58b94d1182595bc7851148b626d5f76159 | <|skeleton|>
class GeometricObjectBase:
"""Abstract base class for geometric objects."""
def getAsKml(self, session):
"""Retrieve the geometry in KML format. This method is a veneer for an SQL query that calls the ``ST_AsKml()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.sessi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeometricObjectBase:
"""Abstract base class for geometric objects."""
def getAsKml(self, session):
"""Retrieve the geometry in KML format. This method is a veneer for an SQL query that calls the ``ST_AsKml()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.session.Session`):... | the_stack_v2_python_sparse | gsshapy/base/geom.py | CI-WATER/gsshapy | train | 9 |
0b45f614092ba5793cd4a2382c6ab6e5933bb74a | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | UserRpcServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRpcServiceServicer:
"""Missing associated documentation comment in .proto file."""
def registerUser(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def userLogin(self, request, context):
"""Missing associated... | stack_v2_sparse_classes_75kplus_train_002998 | 5,422 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "registerUser",
"signature": "def registerUser(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "userLogin",
"signature": "def userLogin(self, ... | 3 | stack_v2_sparse_classes_30k_train_042453 | Implement the Python class `UserRpcServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def registerUser(self, request, context): Missing associated documentation comment in .proto file.
- def userLogin(self, request, context... | Implement the Python class `UserRpcServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def registerUser(self, request, context): Missing associated documentation comment in .proto file.
- def userLogin(self, request, context... | b2319298944d0f29aa8d75ecd44526cc473b27ea | <|skeleton|>
class UserRpcServiceServicer:
"""Missing associated documentation comment in .proto file."""
def registerUser(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def userLogin(self, request, context):
"""Missing associated... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserRpcServiceServicer:
"""Missing associated documentation comment in .proto file."""
def registerUser(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implement... | the_stack_v2_python_sparse | rpc_packages/user_pb2_grpc.py | Silentharry94/python-grpc-demo | train | 0 |
4e04c0d4303024855ca3d8991ee648eb981ef413 | [
"self.BOX = box\nself.indexBOX = [box[ii] for ii in [0, 1, 2, 3]]\nif len(box) == 8:\n self.indexBOX = [box[ii] for ii in [0, 1, 2, 3, 6, 7]]\nself.fs_index = indexstore(self.cache, self.cachedir, os.path.sep.join([self.local_ftp, 'ar_index_global_prof.txt']))",
"if not hasattr(self, '_list_of_argo_files'):\n ... | <|body_start_0|>
self.BOX = box
self.indexBOX = [box[ii] for ii in [0, 1, 2, 3]]
if len(box) == 8:
self.indexBOX = [box[ii] for ii in [0, 1, 2, 3, 6, 7]]
self.fs_index = indexstore(self.cache, self.cachedir, os.path.sep.join([self.local_ftp, 'ar_index_global_prof.txt']))
<|en... | Manage access to local ftp Argo data for: a rectangular space/time domain | Fetch_box | [
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fetch_box:
"""Manage access to local ftp Argo data for: a rectangular space/time domain"""
def init(self, box: list):
"""Create Argo data loader Parameters ---------- box : list() The box domain to load all Argo data for, with one of the following convention: - box = [lon_min, lon_ma... | stack_v2_sparse_classes_75kplus_train_002999 | 21,335 | permissive | [
{
"docstring": "Create Argo data loader Parameters ---------- box : list() The box domain to load all Argo data for, with one of the following convention: - box = [lon_min, lon_max, lat_min, lat_max, pres_min, pres_max] - box = [lon_min, lon_max, lat_min, lat_max, pres_min, pres_max, datim_min, datim_max]",
... | 2 | stack_v2_sparse_classes_30k_train_039536 | Implement the Python class `Fetch_box` described below.
Class description:
Manage access to local ftp Argo data for: a rectangular space/time domain
Method signatures and docstrings:
- def init(self, box: list): Create Argo data loader Parameters ---------- box : list() The box domain to load all Argo data for, with ... | Implement the Python class `Fetch_box` described below.
Class description:
Manage access to local ftp Argo data for: a rectangular space/time domain
Method signatures and docstrings:
- def init(self, box: list): Create Argo data loader Parameters ---------- box : list() The box domain to load all Argo data for, with ... | a9e9375fde6d47506f65e8217d473ac03d4ab469 | <|skeleton|>
class Fetch_box:
"""Manage access to local ftp Argo data for: a rectangular space/time domain"""
def init(self, box: list):
"""Create Argo data loader Parameters ---------- box : list() The box domain to load all Argo data for, with one of the following convention: - box = [lon_min, lon_ma... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fetch_box:
"""Manage access to local ftp Argo data for: a rectangular space/time domain"""
def init(self, box: list):
"""Create Argo data loader Parameters ---------- box : list() The box domain to load all Argo data for, with one of the following convention: - box = [lon_min, lon_max, lat_min, l... | the_stack_v2_python_sparse | argopy/data_fetchers/localftp_data.py | xeulha/argopy | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.