blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f10f5fd0fc98fa56d1dd947c7f813ead03f9015b | [
"d = {}\nfor idx, val in enumerate(nums):\n if val in d and idx - d[val] <= k:\n return True\n d[val] = idx\nreturn False",
"d = {}\ndiv = t\nif t == 0:\n div = 1\nif t < 0:\n return False\nfor idx, val in enumerate(nums):\n key = val // div\n if key in d:\n return True\n if key... | <|body_start_0|>
d = {}
for idx, val in enumerate(nums):
if val in d and idx - d[val] <= k:
return True
d[val] = idx
return False
<|end_body_0|>
<|body_start_1|>
d = {}
div = t
if t == 0:
div = 1
if t < 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyAlmostDuplicate(self, nums, k, t):
""":type nums: List[int] :type k: int 距离 :type t: int 最大差值 :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_007100 | 1,313 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate",
"signature": "def containsNearbyDuplicate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int 距离 :type t: int 最大差值 :rtype: bool",
"name": "containsNearbyAlmostDuplicate",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyAlmostDuplicate(self, nums, k, t): :type nums: List[int] :type k: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyAlmostDuplicate(self, nums, k, t): :type nums: List[int] :type k: ... | 85128e7d26157b3c36eb43868269de42ea2fcb98 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyAlmostDuplicate(self, nums, k, t):
""":type nums: List[int] :type k: int 距离 :type t: int 最大差值 :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
d = {}
for idx, val in enumerate(nums):
if val in d and idx - d[val] <= k:
return True
d[val] = idx
return False
def contains... | the_stack_v2_python_sparse | src/containsNearbyAlmostDuplicate.py | jsdiuf/leetcode | train | 1 | |
af413f3a0412392ab5ce8d746a198b212b6aa779 | [
"self.records = collections.defaultdict(list)\nfor i, word in enumerate(words):\n self.records[word].append(i)",
"index_list1 = self.records[word1]\nindex_list2 = self.records[word2]\ni, j, min_distance = (0, 0, float('inf'))\nwhile i < len(index_list1) and j < len(index_list2):\n min_distance = min(min_dis... | <|body_start_0|>
self.records = collections.defaultdict(list)
for i, word in enumerate(words):
self.records[word].append(i)
<|end_body_0|>
<|body_start_1|>
index_list1 = self.records[word1]
index_list2 = self.records[word2]
i, j, min_distance = (0, 0, float('inf'))
... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.records = collections.defaultdic... | stack_v2_sparse_classes_36k_train_007101 | 3,746 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.records = collections.defaultdict(list)
for i, word in enumerate(words):
self.records[word].append(i)
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int""... | the_stack_v2_python_sparse | src/lt_244.py | oxhead/CodingYourWay | train | 0 | |
e039c33c9a179ba6d9b71f537a5b925995ef206a | [
"super(TabWidget, self).__init__(parent=parent)\nself._tab_buttons = []\nself.setStyleSheet(kuiUtils.get_style_sheet('stylesheet_tabWidget'))\nself.setLayout(qg.QVBoxLayout())\nself.layout().setContentsMargins(2, 2, 2, 2)\nself.layout().setSpacing(0)\nself.lay_tabs = qg.QHBoxLayout()\nself.lay_tabs.setAlignment(qc.... | <|body_start_0|>
super(TabWidget, self).__init__(parent=parent)
self._tab_buttons = []
self.setStyleSheet(kuiUtils.get_style_sheet('stylesheet_tabWidget'))
self.setLayout(qg.QVBoxLayout())
self.layout().setContentsMargins(2, 2, 2, 2)
self.layout().setSpacing(0)
se... | Widget for creating a tab menu that switches between different widgets | TabWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TabWidget:
"""Widget for creating a tab menu that switches between different widgets"""
def __init__(self, parent=None):
"""Sets main layout for widget and establishes"""
<|body_0|>
def add_tab(self, label, content_widget, selected=False):
"""Adds a new tab and a... | stack_v2_sparse_classes_36k_train_007102 | 3,926 | no_license | [
{
"docstring": "Sets main layout for widget and establishes",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Adds a new tab and associates it with the given content_widget :param label: String: Text to display on tab button :param content_widget: QWidget: W... | 3 | stack_v2_sparse_classes_30k_train_018181 | Implement the Python class `TabWidget` described below.
Class description:
Widget for creating a tab menu that switches between different widgets
Method signatures and docstrings:
- def __init__(self, parent=None): Sets main layout for widget and establishes
- def add_tab(self, label, content_widget, selected=False):... | Implement the Python class `TabWidget` described below.
Class description:
Widget for creating a tab menu that switches between different widgets
Method signatures and docstrings:
- def __init__(self, parent=None): Sets main layout for widget and establishes
- def add_tab(self, label, content_widget, selected=False):... | 67d7844f32921b44c9401ac4046a8387ea3cfa5c | <|skeleton|>
class TabWidget:
"""Widget for creating a tab menu that switches between different widgets"""
def __init__(self, parent=None):
"""Sets main layout for widget and establishes"""
<|body_0|>
def add_tab(self, label, content_widget, selected=False):
"""Adds a new tab and a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TabWidget:
"""Widget for creating a tab menu that switches between different widgets"""
def __init__(self, parent=None):
"""Sets main layout for widget and establishes"""
super(TabWidget, self).__init__(parent=parent)
self._tab_buttons = []
self.setStyleSheet(kuiUtils.get_... | the_stack_v2_python_sparse | kToolset/rigging/kar/ui/widgets/tabWidget.py | Kainev/kToolset | train | 0 |
551470ff6322f7f78a8271513236fca9aa7ef26f | [
"if not root:\n return ''\nqueue = [(1, root)]\nseq_val_tuples = []\nwhile queue:\n seq, node = queue.pop(0)\n seq_val_tuples.append(f'{seq}_{node.val}')\n if node.left:\n queue.append((seq * 2, node.left))\n if node.right:\n queue.append((seq * 2 + 1, node.right))\nreturn ','.join(seq_... | <|body_start_0|>
if not root:
return ''
queue = [(1, root)]
seq_val_tuples = []
while queue:
seq, node = queue.pop(0)
seq_val_tuples.append(f'{seq}_{node.val}')
if node.left:
queue.append((seq * 2, node.left))
if... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_007103 | 1,855 | 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_003923 | 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:... | 1a773bb02871d418def9629f608c68c4b0e8fe4e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
queue = [(1, root)]
seq_val_tuples = []
while queue:
seq, node = queue.pop(0)
seq_val_tuples.append(f'{... | the_stack_v2_python_sparse | archive-dhkim/leetcode/ch14_tree/prob47_serialize_and_deserialize_binary_tree.py | LenKIM/implements | train | 3 | |
11a72443dfdce4db6dd71ccd35e37422d9a7c62d | [
"if value is self.field.missing_value:\n return []\nterms = self.widget.update_terms()\ntry:\n return [terms.getTerm(value).token]\nexcept LookupError:\n return []",
"widget = self.widget\nif len(value) == 0 or value[0] == widget.no_value_token:\n return self.field.missing_value\nwidget.update_terms()... | <|body_start_0|>
if value is self.field.missing_value:
return []
terms = self.widget.update_terms()
try:
return [terms.getTerm(value).token]
except LookupError:
return []
<|end_body_0|>
<|body_start_1|>
widget = self.widget
if len(valu... | Basic data converter for ISequenceWidget. | SequenceDataConverter | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceDataConverter:
"""Basic data converter for ISequenceWidget."""
def to_widget_value(self, value):
"""Convert from Python bool to HTML representation."""
<|body_0|>
def to_field_value(self, value):
"""See interfaces.IDataConverter"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_007104 | 16,755 | permissive | [
{
"docstring": "Convert from Python bool to HTML representation.",
"name": "to_widget_value",
"signature": "def to_widget_value(self, value)"
},
{
"docstring": "See interfaces.IDataConverter",
"name": "to_field_value",
"signature": "def to_field_value(self, value)"
}
] | 2 | null | Implement the Python class `SequenceDataConverter` described below.
Class description:
Basic data converter for ISequenceWidget.
Method signatures and docstrings:
- def to_widget_value(self, value): Convert from Python bool to HTML representation.
- def to_field_value(self, value): See interfaces.IDataConverter | Implement the Python class `SequenceDataConverter` described below.
Class description:
Basic data converter for ISequenceWidget.
Method signatures and docstrings:
- def to_widget_value(self, value): Convert from Python bool to HTML representation.
- def to_field_value(self, value): See interfaces.IDataConverter
<|sk... | e83e2ce314355f98eaf66e90ad6feccbda7934f9 | <|skeleton|>
class SequenceDataConverter:
"""Basic data converter for ISequenceWidget."""
def to_widget_value(self, value):
"""Convert from Python bool to HTML representation."""
<|body_0|>
def to_field_value(self, value):
"""See interfaces.IDataConverter"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceDataConverter:
"""Basic data converter for ISequenceWidget."""
def to_widget_value(self, value):
"""Convert from Python bool to HTML representation."""
if value is self.field.missing_value:
return []
terms = self.widget.update_terms()
try:
r... | the_stack_v2_python_sparse | src/pyams_form/converter.py | Py-AMS/pyams-form | train | 0 |
f4524728369d3d1d59d0a2b147e2dfbee0dc6c28 | [
"self.data = data\nself.event = event\nself.event_id = generate_id()\nself.desc_map = {self.data: 'data', self.event: 'event', self.event_id: 'id'}",
"if not self.data:\n return ''\nlines = ['{}: {}'.format(name, key) for key, name in self.desc_map.items() if key]\nreturn '{}\\n\\n'.format('\\n'.join(lines))"
... | <|body_start_0|>
self.data = data
self.event = event
self.event_id = generate_id()
self.desc_map = {self.data: 'data', self.event: 'event', self.event_id: 'id'}
<|end_body_0|>
<|body_start_1|>
if not self.data:
return ''
lines = ['{}: {}'.format(name, key) fo... | Class to handle server-sent events. | ServerSentEvent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerSentEvent:
"""Class to handle server-sent events."""
def __init__(self, data, event):
"""Construct a Server Sent Event object."""
<|body_0|>
def encode(self):
"""Encode the event as a string."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_007105 | 3,925 | permissive | [
{
"docstring": "Construct a Server Sent Event object.",
"name": "__init__",
"signature": "def __init__(self, data, event)"
},
{
"docstring": "Encode the event as a string.",
"name": "encode",
"signature": "def encode(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010812 | Implement the Python class `ServerSentEvent` described below.
Class description:
Class to handle server-sent events.
Method signatures and docstrings:
- def __init__(self, data, event): Construct a Server Sent Event object.
- def encode(self): Encode the event as a string. | Implement the Python class `ServerSentEvent` described below.
Class description:
Class to handle server-sent events.
Method signatures and docstrings:
- def __init__(self, data, event): Construct a Server Sent Event object.
- def encode(self): Encode the event as a string.
<|skeleton|>
class ServerSentEvent:
"""... | b0fcbc6e569daef186a45fc0531de8a275d6382c | <|skeleton|>
class ServerSentEvent:
"""Class to handle server-sent events."""
def __init__(self, data, event):
"""Construct a Server Sent Event object."""
<|body_0|>
def encode(self):
"""Encode the event as a string."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServerSentEvent:
"""Class to handle server-sent events."""
def __init__(self, data, event):
"""Construct a Server Sent Event object."""
self.data = data
self.event = event
self.event_id = generate_id()
self.desc_map = {self.data: 'data', self.event: 'event', self.e... | the_stack_v2_python_sparse | src/gridrealm/server_events.py | fretboardfreak/gridrealm | train | 0 |
9a455f034e6782f596cd0ba088aa2aa7f448f04e | [
"sTitle = 'Failure Reason'\nif sMode == WuiFormContentBase.ksMode_Add:\n sTitle = 'Add' + sTitle\nelif sMode == WuiFormContentBase.ksMode_Edit:\n sTitle = 'Edit' + sTitle\nelse:\n assert sMode == WuiFormContentBase.ksMode_Show\nWuiFormContentBase.__init__(self, oFailureReasonData, sMode, 'FailureReason', o... | <|body_start_0|>
sTitle = 'Failure Reason'
if sMode == WuiFormContentBase.ksMode_Add:
sTitle = 'Add' + sTitle
elif sMode == WuiFormContentBase.ksMode_Edit:
sTitle = 'Edit' + sTitle
else:
assert sMode == WuiFormContentBase.ksMode_Show
WuiFormCon... | WUI Failure Reason HTML content generator. | WuiAdminFailureReason | [
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"CDDL-1.0",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"GPL-2.0-or-later",
"MPL-1.0",
"LicenseRef-scancode-generic-exception",
"Apache-2.0",
"OpenSSL",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WuiAdminFailureReason:
"""WUI Failure Reason HTML content generator."""
def __init__(self, oFailureReasonData, sMode, oDisp):
"""Prepare & initialize parent"""
<|body_0|>
def _populateForm(self, oForm, oData):
"""Construct an HTML form"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_007106 | 7,957 | permissive | [
{
"docstring": "Prepare & initialize parent",
"name": "__init__",
"signature": "def __init__(self, oFailureReasonData, sMode, oDisp)"
},
{
"docstring": "Construct an HTML form",
"name": "_populateForm",
"signature": "def _populateForm(self, oForm, oData)"
}
] | 2 | null | Implement the Python class `WuiAdminFailureReason` described below.
Class description:
WUI Failure Reason HTML content generator.
Method signatures and docstrings:
- def __init__(self, oFailureReasonData, sMode, oDisp): Prepare & initialize parent
- def _populateForm(self, oForm, oData): Construct an HTML form | Implement the Python class `WuiAdminFailureReason` described below.
Class description:
WUI Failure Reason HTML content generator.
Method signatures and docstrings:
- def __init__(self, oFailureReasonData, sMode, oDisp): Prepare & initialize parent
- def _populateForm(self, oForm, oData): Construct an HTML form
<|ske... | 6f78952d58da52ea4f0e55b2ab297f28e80c1160 | <|skeleton|>
class WuiAdminFailureReason:
"""WUI Failure Reason HTML content generator."""
def __init__(self, oFailureReasonData, sMode, oDisp):
"""Prepare & initialize parent"""
<|body_0|>
def _populateForm(self, oForm, oData):
"""Construct an HTML form"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WuiAdminFailureReason:
"""WUI Failure Reason HTML content generator."""
def __init__(self, oFailureReasonData, sMode, oDisp):
"""Prepare & initialize parent"""
sTitle = 'Failure Reason'
if sMode == WuiFormContentBase.ksMode_Add:
sTitle = 'Add' + sTitle
elif sMo... | the_stack_v2_python_sparse | third_party/virtualbox/src/VBox/ValidationKit/testmanager/webui/wuiadminfailurereason.py | thalium/icebox | train | 585 |
69ae0afb3c67976c340ecd7d0e41a88a10b81c2c | [
"client = Client()\npredictor_sdk = SDKConfig()\nclient_id = id(client)\npredictor_sdk.add_server_variant('default_tag_{}'.format(client_id), ['127.0.0.1:12003'], '100')\nassert predictor_sdk.tag_list == [f'default_tag_{client_id}']\nassert predictor_sdk.cluster_list == [['127.0.0.1:12003']]\nassert predictor_sdk.v... | <|body_start_0|>
client = Client()
predictor_sdk = SDKConfig()
client_id = id(client)
predictor_sdk.add_server_variant('default_tag_{}'.format(client_id), ['127.0.0.1:12003'], '100')
assert predictor_sdk.tag_list == [f'default_tag_{client_id}']
assert predictor_sdk.cluste... | test SDKConfig | TestSDKConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSDKConfig:
"""test SDKConfig"""
def test_add_server_variant(self):
"""test add server variant"""
<|body_0|>
def test_gen_desc(self):
"""test sdk desc"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
client = Client()
predictor_sdk = S... | stack_v2_sparse_classes_36k_train_007107 | 7,327 | no_license | [
{
"docstring": "test add server variant",
"name": "test_add_server_variant",
"signature": "def test_add_server_variant(self)"
},
{
"docstring": "test sdk desc",
"name": "test_gen_desc",
"signature": "def test_gen_desc(self)"
}
] | 2 | null | Implement the Python class `TestSDKConfig` described below.
Class description:
test SDKConfig
Method signatures and docstrings:
- def test_add_server_variant(self): test add server variant
- def test_gen_desc(self): test sdk desc | Implement the Python class `TestSDKConfig` described below.
Class description:
test SDKConfig
Method signatures and docstrings:
- def test_add_server_variant(self): test add server variant
- def test_gen_desc(self): test sdk desc
<|skeleton|>
class TestSDKConfig:
"""test SDKConfig"""
def test_add_server_var... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class TestSDKConfig:
"""test SDKConfig"""
def test_add_server_variant(self):
"""test add server variant"""
<|body_0|>
def test_gen_desc(self):
"""test sdk desc"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSDKConfig:
"""test SDKConfig"""
def test_add_server_variant(self):
"""test add server variant"""
client = Client()
predictor_sdk = SDKConfig()
client_id = id(client)
predictor_sdk.add_server_variant('default_tag_{}'.format(client_id), ['127.0.0.1:12003'], '100'... | the_stack_v2_python_sparse | inference/serving_api_test/paddle_serving_client/test_client.py | PaddlePaddle/PaddleTest | train | 42 |
260f9a96117b66eb93e91d32de4938de4cdfa909 | [
"if head == None:\n return head\nif head.next == None:\n return head\nrhead = ListNode(head.val)\nrhead.next = None\nwhile head.next != None:\n r2head = ListNode(head.next.val)\n r2head.next = rhead\n rhead = r2head\n head = head.next\nreturn rhead",
"rhead = Solution.reverseList(self, head)\nwh... | <|body_start_0|>
if head == None:
return head
if head.next == None:
return head
rhead = ListNode(head.val)
rhead.next = None
while head.next != None:
r2head = ListNode(head.next.val)
r2head.next = rhead
rhead = r2head
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if head == None:
return head... | stack_v2_sparse_classes_36k_train_007108 | 1,226 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019481 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def isPalindrome(self, head): :type head: ListNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
<|skeleton|>
class Solution:
def revers... | 14176f1752e2bb94dec51bd90dfd412896ed84de | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
if head == None:
return head
if head.next == None:
return head
rhead = ListNode(head.val)
rhead.next = None
while head.next != None:
r2head = L... | the_stack_v2_python_sparse | solutions/234-palindrome-linked-list/palindrome-linked-list.py | fagan2888/leetcode-6 | train | 0 | |
3d781147b6b6859dfc2d94f90633fb7bb8827ee0 | [
"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!')"
] | <|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... | Service to manage customer client links. | CustomerClientLinkServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerClientLinkServiceServicer:
"""Service to manage customer client links."""
def GetCustomerClientLink(self, request, context):
"""Returns the requested CustomerClientLink in full detail."""
<|body_0|>
def MutateCustomerClientLink(self, request, context):
""... | stack_v2_sparse_classes_36k_train_007109 | 5,740 | permissive | [
{
"docstring": "Returns the requested CustomerClientLink in full detail.",
"name": "GetCustomerClientLink",
"signature": "def GetCustomerClientLink(self, request, context)"
},
{
"docstring": "Creates or updates a customer client link. Operation statuses are returned.",
"name": "MutateCustome... | 2 | null | Implement the Python class `CustomerClientLinkServiceServicer` described below.
Class description:
Service to manage customer client links.
Method signatures and docstrings:
- def GetCustomerClientLink(self, request, context): Returns the requested CustomerClientLink in full detail.
- def MutateCustomerClientLink(sel... | Implement the Python class `CustomerClientLinkServiceServicer` described below.
Class description:
Service to manage customer client links.
Method signatures and docstrings:
- def GetCustomerClientLink(self, request, context): Returns the requested CustomerClientLink in full detail.
- def MutateCustomerClientLink(sel... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class CustomerClientLinkServiceServicer:
"""Service to manage customer client links."""
def GetCustomerClientLink(self, request, context):
"""Returns the requested CustomerClientLink in full detail."""
<|body_0|>
def MutateCustomerClientLink(self, request, context):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomerClientLinkServiceServicer:
"""Service to manage customer client links."""
def GetCustomerClientLink(self, request, context):
"""Returns the requested CustomerClientLink in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not imple... | the_stack_v2_python_sparse | google/ads/google_ads/v5/proto/services/customer_client_link_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
4547b82e8b54d1cfd5b58f4c091505c9a500ca65 | [
"self.mode = mode\nsuper().__init__(p.pro_max_speed, envirogrid, Antagonist.image, startcoord)\np.allObjects.add(self)\np.antagonist.add(self)\nOdorSource(__name__, GroupSingle(self), p.ant_odor_intensity, p.ant_colour)\nself.max_health = 100.0\nself.health = self.max_health\nenvirogrid.trackObj(self, self.coord)",... | <|body_start_0|>
self.mode = mode
super().__init__(p.pro_max_speed, envirogrid, Antagonist.image, startcoord)
p.allObjects.add(self)
p.antagonist.add(self)
OdorSource(__name__, GroupSingle(self), p.ant_odor_intensity, p.ant_colour)
self.max_health = 100.0
self.hea... | RAWRRR!!!! all i want to do is eat the protagonist!! i will chase it forever! | Antagonist | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Antagonist:
"""RAWRRR!!!! all i want to do is eat the protagonist!! i will chase it forever!"""
def __init__(self, envirogrid, startcoord, mode):
"""Constructor"""
<|body_0|>
def update(self, mouse, grid):
"""put AI stuff here"""
<|body_1|>
def affec... | stack_v2_sparse_classes_36k_train_007110 | 2,391 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, envirogrid, startcoord, mode)"
},
{
"docstring": "put AI stuff here",
"name": "update",
"signature": "def update(self, mouse, grid)"
},
{
"docstring": "overridden to not die but instead gain health... | 3 | stack_v2_sparse_classes_30k_train_018226 | Implement the Python class `Antagonist` described below.
Class description:
RAWRRR!!!! all i want to do is eat the protagonist!! i will chase it forever!
Method signatures and docstrings:
- def __init__(self, envirogrid, startcoord, mode): Constructor
- def update(self, mouse, grid): put AI stuff here
- def affectHea... | Implement the Python class `Antagonist` described below.
Class description:
RAWRRR!!!! all i want to do is eat the protagonist!! i will chase it forever!
Method signatures and docstrings:
- def __init__(self, envirogrid, startcoord, mode): Constructor
- def update(self, mouse, grid): put AI stuff here
- def affectHea... | b6db5ca1ae04035ebeb016dd0a5bc59bf6aaa24f | <|skeleton|>
class Antagonist:
"""RAWRRR!!!! all i want to do is eat the protagonist!! i will chase it forever!"""
def __init__(self, envirogrid, startcoord, mode):
"""Constructor"""
<|body_0|>
def update(self, mouse, grid):
"""put AI stuff here"""
<|body_1|>
def affec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Antagonist:
"""RAWRRR!!!! all i want to do is eat the protagonist!! i will chase it forever!"""
def __init__(self, envirogrid, startcoord, mode):
"""Constructor"""
self.mode = mode
super().__init__(p.pro_max_speed, envirogrid, Antagonist.image, startcoord)
p.allObjects.add... | the_stack_v2_python_sparse | p2_1184386/antagonist.py | touqir14/Nexus_Game | train | 0 |
478df1f0ecc46a8b6e012018adfd89319f6eb807 | [
"if not matrix or len(matrix) <= 0 or len(matrix[0]) <= 0:\n return None\nstart = 0\nrows = len(matrix)\ncols = len(matrix[0])\nres = []\nwhile rows > start * 2 and cols > start * 2:\n self.printCircleMatrix(matrix, rows, cols, start, res)\n start += 1",
"endX = rows - start - 1\nendY = cols - start - 1\... | <|body_start_0|>
if not matrix or len(matrix) <= 0 or len(matrix[0]) <= 0:
return None
start = 0
rows = len(matrix)
cols = len(matrix[0])
res = []
while rows > start * 2 and cols > start * 2:
self.printCircleMatrix(matrix, rows, cols, start, res)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def printMatrix(self, matrix):
"""顺时针打印矩阵 输入: - matrix: 输入矩阵 输出: -"""
<|body_0|>
def printCircleMatrix(self, matrix, start, rows, cols, res):
"""打印一圈 输入: - matrix: 输出矩阵 - start: 起点 - rows: 矩阵行数 - cols: 矩阵列数 - res: 返回打印队列 输出: - res"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_007111 | 1,659 | no_license | [
{
"docstring": "顺时针打印矩阵 输入: - matrix: 输入矩阵 输出: -",
"name": "printMatrix",
"signature": "def printMatrix(self, matrix)"
},
{
"docstring": "打印一圈 输入: - matrix: 输出矩阵 - start: 起点 - rows: 矩阵行数 - cols: 矩阵列数 - res: 返回打印队列 输出: - res",
"name": "printCircleMatrix",
"signature": "def printCircleMatr... | 2 | stack_v2_sparse_classes_30k_train_015636 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def printMatrix(self, matrix): 顺时针打印矩阵 输入: - matrix: 输入矩阵 输出: -
- def printCircleMatrix(self, matrix, start, rows, cols, res): 打印一圈 输入: - matrix: 输出矩阵 - start: 起点 - rows: 矩阵行数 - ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def printMatrix(self, matrix): 顺时针打印矩阵 输入: - matrix: 输入矩阵 输出: -
- def printCircleMatrix(self, matrix, start, rows, cols, res): 打印一圈 输入: - matrix: 输出矩阵 - start: 起点 - rows: 矩阵行数 - ... | 3f64ced98ac04cd31d8863bb7844504a3a75ce1d | <|skeleton|>
class Solution:
def printMatrix(self, matrix):
"""顺时针打印矩阵 输入: - matrix: 输入矩阵 输出: -"""
<|body_0|>
def printCircleMatrix(self, matrix, start, rows, cols, res):
"""打印一圈 输入: - matrix: 输出矩阵 - start: 起点 - rows: 矩阵行数 - cols: 矩阵列数 - res: 返回打印队列 输出: - res"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def printMatrix(self, matrix):
"""顺时针打印矩阵 输入: - matrix: 输入矩阵 输出: -"""
if not matrix or len(matrix) <= 0 or len(matrix[0]) <= 0:
return None
start = 0
rows = len(matrix)
cols = len(matrix[0])
res = []
while rows > start * 2 and cols ... | the_stack_v2_python_sparse | 题目29:顺时针打印矩阵.py | LenHu0725/02_JZOffer-Notebook | train | 0 | |
64bfede34314aee498c898eedce8aac282af522f | [
"print_info('Creating kafka client')\ntry:\n self.kafka_client = KafkaAdminClient(**configs)\nexcept KafkaError as exc:\n print_error('kafka client - Exception during connecting to broker- {}'.format(exc))",
"timeout = kwargs.get('timeout', None)\nvalidate = kwargs.get('validate', False)\nnew_topics = [NewT... | <|body_start_0|>
print_info('Creating kafka client')
try:
self.kafka_client = KafkaAdminClient(**configs)
except KafkaError as exc:
print_error('kafka client - Exception during connecting to broker- {}'.format(exc))
<|end_body_0|>
<|body_start_1|>
timeout = kwarg... | This class contains all kafka admin client related methods | WarriorKafkaClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WarriorKafkaClient:
"""This class contains all kafka admin client related methods"""
def __init__(self, **configs):
"""create a kafka client"""
<|body_0|>
def create_topics(self, topic_sets, **kwargs):
"""create topics for the producer or consumer to use Argument... | stack_v2_sparse_classes_36k_train_007112 | 11,178 | permissive | [
{
"docstring": "create a kafka client",
"name": "__init__",
"signature": "def __init__(self, **configs)"
},
{
"docstring": "create topics for the producer or consumer to use Arguments: topic_sets(list) : list of ['topic_name', 'num_partitions', 'replication_factor'] lists example : ['topic1',1,1... | 4 | null | Implement the Python class `WarriorKafkaClient` described below.
Class description:
This class contains all kafka admin client related methods
Method signatures and docstrings:
- def __init__(self, **configs): create a kafka client
- def create_topics(self, topic_sets, **kwargs): create topics for the producer or con... | Implement the Python class `WarriorKafkaClient` described below.
Class description:
This class contains all kafka admin client related methods
Method signatures and docstrings:
- def __init__(self, **configs): create a kafka client
- def create_topics(self, topic_sets, **kwargs): create topics for the producer or con... | 685761cf044182ec88ce86a942d4be1e150a1256 | <|skeleton|>
class WarriorKafkaClient:
"""This class contains all kafka admin client related methods"""
def __init__(self, **configs):
"""create a kafka client"""
<|body_0|>
def create_topics(self, topic_sets, **kwargs):
"""create topics for the producer or consumer to use Argument... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WarriorKafkaClient:
"""This class contains all kafka admin client related methods"""
def __init__(self, **configs):
"""create a kafka client"""
print_info('Creating kafka client')
try:
self.kafka_client = KafkaAdminClient(**configs)
except KafkaError as exc:
... | the_stack_v2_python_sparse | warrior/Framework/ClassUtils/kafka_utils_class.py | warriorframework/warriorframework | train | 25 |
aa7b62aca0826b4cb65751144e446510b3c1b4c4 | [
"if not root:\n return 0\nreturn 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))",
"if not root:\n return 0\nreturn max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1"
] | <|body_start_0|>
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
<|end_body_0|>
<|body_start_1|>
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Feb 28, 2022 12:02"""
<|body_0|>
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Mar 20, 2023 23:27"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
re... | stack_v2_sparse_classes_36k_train_007113 | 1,582 | no_license | [
{
"docstring": "Feb 28, 2022 12:02",
"name": "maxDepth",
"signature": "def maxDepth(self, root: Optional[TreeNode]) -> int"
},
{
"docstring": "Mar 20, 2023 23:27",
"name": "maxDepth",
"signature": "def maxDepth(self, root: Optional[TreeNode]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_020816 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root: Optional[TreeNode]) -> int: Feb 28, 2022 12:02
- def maxDepth(self, root: Optional[TreeNode]) -> int: Mar 20, 2023 23:27 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root: Optional[TreeNode]) -> int: Feb 28, 2022 12:02
- def maxDepth(self, root: Optional[TreeNode]) -> int: Mar 20, 2023 23:27
<|skeleton|>
class Solution:
... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Feb 28, 2022 12:02"""
<|body_0|>
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Mar 20, 2023 23:27"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Feb 28, 2022 12:02"""
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Mar 20, 2023 23:27"""
... | the_stack_v2_python_sparse | leetcode/solved/104_Maximum_Depth_of_Binary_Tree/solution.py | sungminoh/algorithms | train | 0 | |
62e2e89457b99a554f399862454490b58fafda11 | [
"super(NameGenerator, self).__init__()\nself.lstm_dims = n_hidden_dims\nself.lstm_layers = n_lstm_layers\nself.input_lookup = nn.Embedding(num_embeddings=input_vocab_size, embedding_dim=n_embedding_dims)\nself.lstm = nn.LSTM(input_size=n_embedding_dims, hidden_size=n_hidden_dims, num_layers=n_lstm_layers, batch_fir... | <|body_start_0|>
super(NameGenerator, self).__init__()
self.lstm_dims = n_hidden_dims
self.lstm_layers = n_lstm_layers
self.input_lookup = nn.Embedding(num_embeddings=input_vocab_size, embedding_dim=n_embedding_dims)
self.lstm = nn.LSTM(input_size=n_embedding_dims, hidden_size=n_... | NameGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NameGenerator:
def __init__(self, input_vocab_size, n_embedding_dims, n_hidden_dims, n_lstm_layers, output_vocab_size):
"""Initialize our name generator, following the equations laid out in the assignment. In other words, we'll need an Embedding layer, an LSTM layer, a Linear layer, and ... | stack_v2_sparse_classes_36k_train_007114 | 5,650 | no_license | [
{
"docstring": "Initialize our name generator, following the equations laid out in the assignment. In other words, we'll need an Embedding layer, an LSTM layer, a Linear layer, and LogSoftmax layer. Note: Remember to set batch_first=True when initializing your LSTM layer! Also note: When you build your LogSoftm... | 3 | null | Implement the Python class `NameGenerator` described below.
Class description:
Implement the NameGenerator class.
Method signatures and docstrings:
- def __init__(self, input_vocab_size, n_embedding_dims, n_hidden_dims, n_lstm_layers, output_vocab_size): Initialize our name generator, following the equations laid out... | Implement the Python class `NameGenerator` described below.
Class description:
Implement the NameGenerator class.
Method signatures and docstrings:
- def __init__(self, input_vocab_size, n_embedding_dims, n_hidden_dims, n_lstm_layers, output_vocab_size): Initialize our name generator, following the equations laid out... | 2ded61191a5e5ec215ec187c468a1f1ae1adf412 | <|skeleton|>
class NameGenerator:
def __init__(self, input_vocab_size, n_embedding_dims, n_hidden_dims, n_lstm_layers, output_vocab_size):
"""Initialize our name generator, following the equations laid out in the assignment. In other words, we'll need an Embedding layer, an LSTM layer, a Linear layer, and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NameGenerator:
def __init__(self, input_vocab_size, n_embedding_dims, n_hidden_dims, n_lstm_layers, output_vocab_size):
"""Initialize our name generator, following the equations laid out in the assignment. In other words, we'll need an Embedding layer, an LSTM layer, a Linear layer, and LogSoftmax lay... | the_stack_v2_python_sparse | OHSU_Winter_2019/CS562/HW3/hw3_utils/lm.py | Eric-D-Stevens/OHSU | train | 1 | |
88f0c96ae54c8810920b11236cc288b05059c353 | [
"prod = [1 for _ in range(len(nums))]\ntmp = 1\nfor i in range(len(nums)):\n prod[i] = tmp\n tmp *= nums[i]\ntmp = 1\nfor i in reversed(range(len(nums))):\n prod[i] *= tmp\n tmp *= nums[i]\nreturn prod",
"left, right = ([1 for _ in range(len(nums))], [1 for _ in range(len(nums))])\nfor i in range(1, l... | <|body_start_0|>
prod = [1 for _ in range(len(nums))]
tmp = 1
for i in range(len(nums)):
prod[i] = tmp
tmp *= nums[i]
tmp = 1
for i in reversed(range(len(nums))):
prod[i] *= tmp
tmp *= nums[i]
return prod
<|end_body_0|>
<|b... | Algorithm: 1. Construct `left`, with `left[i]` contains product of all elements on `left` of `nums[i]` excluding `nums[i]` 2. Construct `right`, with `right[i]` contains product of all elements on `right` of `nums[i]` excluding `nums[i]` 3. return multiply of `left` and `right` | Solution | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Algorithm: 1. Construct `left`, with `left[i]` contains product of all elements on `left` of `nums[i]` excluding `nums[i]` 2. Construct `right`, with `right[i]` contains product of all elements on `right` of `nums[i]` excluding `nums[i]` 3. return multiply of `left` and `right`"""
... | stack_v2_sparse_classes_36k_train_007115 | 1,594 | permissive | [
{
"docstring": "Time Complexity: O(n) Space Complexity: O(n) Auxiliary Space: O(1)",
"name": "crack",
"signature": "def crack(self, nums)"
},
{
"docstring": "Time Complexity: O(n) Space Complexity: O(n) Auxiliary Space: O(n)",
"name": "crack2",
"signature": "def crack2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012283 | Implement the Python class `Solution` described below.
Class description:
Algorithm: 1. Construct `left`, with `left[i]` contains product of all elements on `left` of `nums[i]` excluding `nums[i]` 2. Construct `right`, with `right[i]` contains product of all elements on `right` of `nums[i]` excluding `nums[i]` 3. retu... | Implement the Python class `Solution` described below.
Class description:
Algorithm: 1. Construct `left`, with `left[i]` contains product of all elements on `left` of `nums[i]` excluding `nums[i]` 2. Construct `right`, with `right[i]` contains product of all elements on `right` of `nums[i]` excluding `nums[i]` 3. retu... | 812859a982da666daecedbb1197afed21485a432 | <|skeleton|>
class Solution:
"""Algorithm: 1. Construct `left`, with `left[i]` contains product of all elements on `left` of `nums[i]` excluding `nums[i]` 2. Construct `right`, with `right[i]` contains product of all elements on `right` of `nums[i]` excluding `nums[i]` 3. return multiply of `left` and `right`"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Algorithm: 1. Construct `left`, with `left[i]` contains product of all elements on `left` of `nums[i]` excluding `nums[i]` 2. Construct `right`, with `right[i]` contains product of all elements on `right` of `nums[i]` excluding `nums[i]` 3. return multiply of `left` and `right`"""
def crack(... | the_stack_v2_python_sparse | dcp/002/solution.py | dantin/daylight | train | 0 |
4555e93ea8bba9cb799a03c3179614a8fe0a1e7b | [
"visited = [False] * len(arr)\n\ndef dfs(index):\n if arr[index] == 0:\n return True\n for j in [index - arr[index], index + arr[index]]:\n if 0 <= j < len(arr) and (not visited[j]):\n visited[j] = True\n if dfs(j):\n return True\n visited[j] = Fal... | <|body_start_0|>
visited = [False] * len(arr)
def dfs(index):
if arr[index] == 0:
return True
for j in [index - arr[index], index + arr[index]]:
if 0 <= j < len(arr) and (not visited[j]):
visited[j] = True
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canReach_dfs(self, arr, start):
""":type arr: List[int] :type start: int :rtype: bool"""
<|body_0|>
def canReach(self, arr, start):
""":type arr: List[int] :type start: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
v... | stack_v2_sparse_classes_36k_train_007116 | 1,214 | no_license | [
{
"docstring": ":type arr: List[int] :type start: int :rtype: bool",
"name": "canReach_dfs",
"signature": "def canReach_dfs(self, arr, start)"
},
{
"docstring": ":type arr: List[int] :type start: int :rtype: bool",
"name": "canReach",
"signature": "def canReach(self, arr, start)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canReach_dfs(self, arr, start): :type arr: List[int] :type start: int :rtype: bool
- def canReach(self, arr, start): :type arr: List[int] :type start: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canReach_dfs(self, arr, start): :type arr: List[int] :type start: int :rtype: bool
- def canReach(self, arr, start): :type arr: List[int] :type start: int :rtype: bool
<|ske... | b5c25f976866eefec33b96c638a4c5e127319e74 | <|skeleton|>
class Solution:
def canReach_dfs(self, arr, start):
""":type arr: List[int] :type start: int :rtype: bool"""
<|body_0|>
def canReach(self, arr, start):
""":type arr: List[int] :type start: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canReach_dfs(self, arr, start):
""":type arr: List[int] :type start: int :rtype: bool"""
visited = [False] * len(arr)
def dfs(index):
if arr[index] == 0:
return True
for j in [index - arr[index], index + arr[index]]:
... | the_stack_v2_python_sparse | Python/1306_Jump Game III.py | Eddie02582/Leetcode | train | 1 | |
9bc0e5788345cca6d77b7b1463622f186d7ab828 | [
"method_map = kwargs['method_map'] if kwargs.get('method_map', None) else self.method_map\nfor request_method, mapped_method in method_map.items():\n mapped_method = getattr(self, mapped_method)\n method_proxy = self.view_proxy(mapped_method)\n setattr(self, request_method, method_proxy)\nsuper(APIMethodMa... | <|body_start_0|>
method_map = kwargs['method_map'] if kwargs.get('method_map', None) else self.method_map
for request_method, mapped_method in method_map.items():
mapped_method = getattr(self, mapped_method)
method_proxy = self.view_proxy(mapped_method)
setattr(self, ... | 将请求方法映射到子类属性上 :method_map: dict, 方法映射字典。 如将 get 方法映射到 list 方法,其值则为 {'get':'list'} | APIMethodMapMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIMethodMapMixin:
"""将请求方法映射到子类属性上 :method_map: dict, 方法映射字典。 如将 get 方法映射到 list 方法,其值则为 {'get':'list'}"""
def __init__(self, *args, **kwargs):
"""映射请求方法。会从传入子类的关键字参数中寻找 method_map 参数,期望值为 dict类型。寻找对应参数值。 若在类属性和传入参数中同时定义了 method_map ,则以传入参数为准。 :param args: 传入的位置参数 :param kwargs: 传入的关... | stack_v2_sparse_classes_36k_train_007117 | 9,950 | no_license | [
{
"docstring": "映射请求方法。会从传入子类的关键字参数中寻找 method_map 参数,期望值为 dict类型。寻找对应参数值。 若在类属性和传入参数中同时定义了 method_map ,则以传入参数为准。 :param args: 传入的位置参数 :param kwargs: 传入的关键字参数",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "代理被映射方法,并代理接收传入视图函数的其他参数。 :param mapped_method... | 2 | stack_v2_sparse_classes_30k_train_007358 | Implement the Python class `APIMethodMapMixin` described below.
Class description:
将请求方法映射到子类属性上 :method_map: dict, 方法映射字典。 如将 get 方法映射到 list 方法,其值则为 {'get':'list'}
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 映射请求方法。会从传入子类的关键字参数中寻找 method_map 参数,期望值为 dict类型。寻找对应参数值。 若在类属性和传入参数中同时定义了 metho... | Implement the Python class `APIMethodMapMixin` described below.
Class description:
将请求方法映射到子类属性上 :method_map: dict, 方法映射字典。 如将 get 方法映射到 list 方法,其值则为 {'get':'list'}
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 映射请求方法。会从传入子类的关键字参数中寻找 method_map 参数,期望值为 dict类型。寻找对应参数值。 若在类属性和传入参数中同时定义了 metho... | 9821516dc739a1fdeca688454831728b64461999 | <|skeleton|>
class APIMethodMapMixin:
"""将请求方法映射到子类属性上 :method_map: dict, 方法映射字典。 如将 get 方法映射到 list 方法,其值则为 {'get':'list'}"""
def __init__(self, *args, **kwargs):
"""映射请求方法。会从传入子类的关键字参数中寻找 method_map 参数,期望值为 dict类型。寻找对应参数值。 若在类属性和传入参数中同时定义了 method_map ,则以传入参数为准。 :param args: 传入的位置参数 :param kwargs: 传入的关... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class APIMethodMapMixin:
"""将请求方法映射到子类属性上 :method_map: dict, 方法映射字典。 如将 get 方法映射到 list 方法,其值则为 {'get':'list'}"""
def __init__(self, *args, **kwargs):
"""映射请求方法。会从传入子类的关键字参数中寻找 method_map 参数,期望值为 dict类型。寻找对应参数值。 若在类属性和传入参数中同时定义了 method_map ,则以传入参数为准。 :param args: 传入的位置参数 :param kwargs: 传入的关键字参数"""
... | the_stack_v2_python_sparse | online_intepreter/mixins.py | Arithmeticjia/MyBlog | train | 5 |
af97957f393c91009252ec567731a228c9a09ba1 | [
"super().__init__(name, id, image)\nself.maxDepth = currentMaxDepth\nself.absoluteMaxDepth = absoluteMaxDepth\nself.takeBest = takeBest\nself.count = 0\nself.increaseThreshold = 12\nself.boxScoring = boxScoring\nself.sectionScoring = sectionScoring",
"self.count += 1\nif self.count >= self.increaseThreshold and s... | <|body_start_0|>
super().__init__(name, id, image)
self.maxDepth = currentMaxDepth
self.absoluteMaxDepth = absoluteMaxDepth
self.takeBest = takeBest
self.count = 0
self.increaseThreshold = 12
self.boxScoring = boxScoring
self.sectionScoring = sectionScorin... | This player will use a varient of the MiniMax method A more complete description can be found in the readme in this directory. | AIPlayerMiniMax | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AIPlayerMiniMax:
"""This player will use a varient of the MiniMax method A more complete description can be found in the readme in this directory."""
def __init__(self, name, id, image, currentMaxDepth, absoluteMaxDepth, boxScoring, sectionScoring, takeBest):
"""maxDepth is how deep ... | stack_v2_sparse_classes_36k_train_007118 | 13,220 | no_license | [
{
"docstring": "maxDepth is how deep this player will check overtime, the maxDepth will slowly increase, based on the count and increaseThreshold",
"name": "__init__",
"signature": "def __init__(self, name, id, image, currentMaxDepth, absoluteMaxDepth, boxScoring, sectionScoring, takeBest)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_004505 | Implement the Python class `AIPlayerMiniMax` described below.
Class description:
This player will use a varient of the MiniMax method A more complete description can be found in the readme in this directory.
Method signatures and docstrings:
- def __init__(self, name, id, image, currentMaxDepth, absoluteMaxDepth, box... | Implement the Python class `AIPlayerMiniMax` described below.
Class description:
This player will use a varient of the MiniMax method A more complete description can be found in the readme in this directory.
Method signatures and docstrings:
- def __init__(self, name, id, image, currentMaxDepth, absoluteMaxDepth, box... | cf4431f45513bdb0362131b39875d8148f8124de | <|skeleton|>
class AIPlayerMiniMax:
"""This player will use a varient of the MiniMax method A more complete description can be found in the readme in this directory."""
def __init__(self, name, id, image, currentMaxDepth, absoluteMaxDepth, boxScoring, sectionScoring, takeBest):
"""maxDepth is how deep ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AIPlayerMiniMax:
"""This player will use a varient of the MiniMax method A more complete description can be found in the readme in this directory."""
def __init__(self, name, id, image, currentMaxDepth, absoluteMaxDepth, boxScoring, sectionScoring, takeBest):
"""maxDepth is how deep this player w... | the_stack_v2_python_sparse | TicTacToe/player.py | Diusrex/275-Final-Project | train | 0 |
e661330204e9fe0062cfb9fc6c7a668abb66c9b2 | [
"self.barcode = barcode\nself.location = location\nself.online = online",
"if dictionary is None:\n return None\nbarcode = dictionary.get('barcode')\nlocation = dictionary.get('location')\nonline = dictionary.get('online')\nreturn cls(barcode, location, online)"
] | <|body_start_0|>
self.barcode = barcode
self.location = location
self.online = online
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
barcode = dictionary.get('barcode')
location = dictionary.get('location')
online = dictionary.get(... | Implementation of the 'TapeMediaInformation' model. Provides information about a single tape media in a QStar Archive Vault. Attributes: barcode (string): Specifies a unique identifier for the media. location (string): Specifies the location of the offline media as recorded by the backup administrator using media manag... | TapeMediaInformation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TapeMediaInformation:
"""Implementation of the 'TapeMediaInformation' model. Provides information about a single tape media in a QStar Archive Vault. Attributes: barcode (string): Specifies a unique identifier for the media. location (string): Specifies the location of the offline media as record... | stack_v2_sparse_classes_36k_train_007119 | 2,046 | permissive | [
{
"docstring": "Constructor for the TapeMediaInformation class",
"name": "__init__",
"signature": "def __init__(self, barcode=None, location=None, online=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of th... | 2 | stack_v2_sparse_classes_30k_train_009511 | Implement the Python class `TapeMediaInformation` described below.
Class description:
Implementation of the 'TapeMediaInformation' model. Provides information about a single tape media in a QStar Archive Vault. Attributes: barcode (string): Specifies a unique identifier for the media. location (string): Specifies the ... | Implement the Python class `TapeMediaInformation` described below.
Class description:
Implementation of the 'TapeMediaInformation' model. Provides information about a single tape media in a QStar Archive Vault. Attributes: barcode (string): Specifies a unique identifier for the media. location (string): Specifies the ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class TapeMediaInformation:
"""Implementation of the 'TapeMediaInformation' model. Provides information about a single tape media in a QStar Archive Vault. Attributes: barcode (string): Specifies a unique identifier for the media. location (string): Specifies the location of the offline media as record... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TapeMediaInformation:
"""Implementation of the 'TapeMediaInformation' model. Provides information about a single tape media in a QStar Archive Vault. Attributes: barcode (string): Specifies a unique identifier for the media. location (string): Specifies the location of the offline media as recorded by the bac... | the_stack_v2_python_sparse | cohesity_management_sdk/models/tape_media_information.py | cohesity/management-sdk-python | train | 24 |
124964c672594895f5b587b76cdbc2c9522dfa25 | [
"cur = head\nprev = None\nif not head:\n return None\ntotal_count = 0\nwhile cur:\n cur = cur.next\n total_count += 1\nneed_remove_index = total_count - n\nif need_remove_index == 0:\n return head.next\ncur = head\nfor i in range(0, need_remove_index):\n prev, cur = (cur, cur.next)\nprev.next = cur.n... | <|body_start_0|>
cur = head
prev = None
if not head:
return None
total_count = 0
while cur:
cur = cur.next
total_count += 1
need_remove_index = total_count - n
if need_remove_index == 0:
return head.next
cur ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd2(self, head: ListNode, n: int) -> ListNode:
"""解法1,遍历统计数量,算出要删除的位置,然后遍历删除 :param head: :param n: :return:"""
<|body_0|>
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""解法2,遍历统计数量,同时将下表和节点对应缓存起来,算出要删除的位置 :param head: :... | stack_v2_sparse_classes_36k_train_007120 | 1,518 | no_license | [
{
"docstring": "解法1,遍历统计数量,算出要删除的位置,然后遍历删除 :param head: :param n: :return:",
"name": "removeNthFromEnd2",
"signature": "def removeNthFromEnd2(self, head: ListNode, n: int) -> ListNode"
},
{
"docstring": "解法2,遍历统计数量,同时将下表和节点对应缓存起来,算出要删除的位置 :param head: :param n: :return:",
"name": "removeNthF... | 2 | stack_v2_sparse_classes_30k_train_003317 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd2(self, head: ListNode, n: int) -> ListNode: 解法1,遍历统计数量,算出要删除的位置,然后遍历删除 :param head: :param n: :return:
- def removeNthFromEnd(self, head: ListNode, n: int) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd2(self, head: ListNode, n: int) -> ListNode: 解法1,遍历统计数量,算出要删除的位置,然后遍历删除 :param head: :param n: :return:
- def removeNthFromEnd(self, head: ListNode, n: int) -... | cd9a4d261830180a59bc92cc706fe0dd2f1746f9 | <|skeleton|>
class Solution:
def removeNthFromEnd2(self, head: ListNode, n: int) -> ListNode:
"""解法1,遍历统计数量,算出要删除的位置,然后遍历删除 :param head: :param n: :return:"""
<|body_0|>
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""解法2,遍历统计数量,同时将下表和节点对应缓存起来,算出要删除的位置 :param head: :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeNthFromEnd2(self, head: ListNode, n: int) -> ListNode:
"""解法1,遍历统计数量,算出要删除的位置,然后遍历删除 :param head: :param n: :return:"""
cur = head
prev = None
if not head:
return None
total_count = 0
while cur:
cur = cur.next
... | the_stack_v2_python_sparse | 19_remove_nth_node_from_end_of_list.py | csliubo/leetcode | train | 0 | |
9ac820e719879ea9a506e07561ee38ed360dc004 | [
"game_object: GameObject = CommonObjectUtils.get_root_parent(game_object)\nslot_component = cls.get_slot_component(game_object)\nif slot_component is None:\n return tuple()\ncontainment_slot_list: List[CommonObjectContainmentSlot] = list()\nfor slot_hash, slot_types in tuple(slot_component.get_containment_slot_i... | <|body_start_0|>
game_object: GameObject = CommonObjectUtils.get_root_parent(game_object)
slot_component = cls.get_slot_component(game_object)
if slot_component is None:
return tuple()
containment_slot_list: List[CommonObjectContainmentSlot] = list()
for slot_hash, sl... | Utilities for manipulating object slots. | CommonObjectSlotUtils | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonObjectSlotUtils:
"""Utilities for manipulating object slots."""
def get_containment_slots(cls, game_object: GameObject) -> Tuple[CommonObjectContainmentSlot]:
"""get_containment_slots(game_object) Retrieve the containment slots of an object. :param game_object: An instance of a... | stack_v2_sparse_classes_36k_train_007121 | 9,030 | permissive | [
{
"docstring": "get_containment_slots(game_object) Retrieve the containment slots of an object. :param game_object: An instance of an Object. :type game_object: GameObject :return: A collection of containment slots on the specified object. :rtype: Tuple[CommonObjectContainmentSlot]",
"name": "get_containmen... | 6 | stack_v2_sparse_classes_30k_train_009699 | Implement the Python class `CommonObjectSlotUtils` described below.
Class description:
Utilities for manipulating object slots.
Method signatures and docstrings:
- def get_containment_slots(cls, game_object: GameObject) -> Tuple[CommonObjectContainmentSlot]: get_containment_slots(game_object) Retrieve the containment... | Implement the Python class `CommonObjectSlotUtils` described below.
Class description:
Utilities for manipulating object slots.
Method signatures and docstrings:
- def get_containment_slots(cls, game_object: GameObject) -> Tuple[CommonObjectContainmentSlot]: get_containment_slots(game_object) Retrieve the containment... | 58e7beb30b9c818b294d35abd2436a0192cd3e82 | <|skeleton|>
class CommonObjectSlotUtils:
"""Utilities for manipulating object slots."""
def get_containment_slots(cls, game_object: GameObject) -> Tuple[CommonObjectContainmentSlot]:
"""get_containment_slots(game_object) Retrieve the containment slots of an object. :param game_object: An instance of a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommonObjectSlotUtils:
"""Utilities for manipulating object slots."""
def get_containment_slots(cls, game_object: GameObject) -> Tuple[CommonObjectContainmentSlot]:
"""get_containment_slots(game_object) Retrieve the containment slots of an object. :param game_object: An instance of an Object. :ty... | the_stack_v2_python_sparse | Scripts/sims4communitylib/utils/objects/common_object_slot_utils.py | ColonolNutty/Sims4CommunityLibrary | train | 183 |
1b33f769a396a595f4406b1818e49d4728e6b818 | [
"if N == 1:\n return [i for i in range(10)]\nans_list = set()\n\ndef dpfunc(cur_N, cur_list, cur_value):\n if cur_N >= N:\n ans_list.add(int(''.join(cur_list)))\n return\n temp = cur_value + K\n if temp <= 9:\n cur_list.append(str(temp))\n dpfunc(cur_N + 1, cur_list, temp)\n ... | <|body_start_0|>
if N == 1:
return [i for i in range(10)]
ans_list = set()
def dpfunc(cur_N, cur_list, cur_value):
if cur_N >= N:
ans_list.add(int(''.join(cur_list)))
return
temp = cur_value + K
if temp <= 9:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numsSameConsecDiff(self, N, K):
""":type N: int :type K: int :rtype: List[int] 44 ms 11.9 MB"""
<|body_0|>
def numsSameConsecDiff_1(self, N, K):
"""48ms 12.1 MB :param N: :param K: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_007122 | 2,219 | no_license | [
{
"docstring": ":type N: int :type K: int :rtype: List[int] 44 ms 11.9 MB",
"name": "numsSameConsecDiff",
"signature": "def numsSameConsecDiff(self, N, K)"
},
{
"docstring": "48ms 12.1 MB :param N: :param K: :return:",
"name": "numsSameConsecDiff_1",
"signature": "def numsSameConsecDiff_... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numsSameConsecDiff(self, N, K): :type N: int :type K: int :rtype: List[int] 44 ms 11.9 MB
- def numsSameConsecDiff_1(self, N, K): 48ms 12.1 MB :param N: :param K: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numsSameConsecDiff(self, N, K): :type N: int :type K: int :rtype: List[int] 44 ms 11.9 MB
- def numsSameConsecDiff_1(self, N, K): 48ms 12.1 MB :param N: :param K: :return:
<... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def numsSameConsecDiff(self, N, K):
""":type N: int :type K: int :rtype: List[int] 44 ms 11.9 MB"""
<|body_0|>
def numsSameConsecDiff_1(self, N, K):
"""48ms 12.1 MB :param N: :param K: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numsSameConsecDiff(self, N, K):
""":type N: int :type K: int :rtype: List[int] 44 ms 11.9 MB"""
if N == 1:
return [i for i in range(10)]
ans_list = set()
def dpfunc(cur_N, cur_list, cur_value):
if cur_N >= N:
ans_list.add(i... | the_stack_v2_python_sparse | NumbersWithSameConsecutiveDifferences_MID_967.py | 953250587/leetcode-python | train | 2 | |
8431db3bad62aacbd7405b7ee770cd8e2f7bc28c | [
"self.input_str = input_str\nself.output_str = output_str\nself.metadata = metadata",
"tf_example = tf.train.Example()\nadd_text_feature('inputs', self.input_str, tf_example)\nadd_text_feature('targets', self.output_str, tf_example)\nadd_bytes_feature('metadata', pickle.dumps(self.metadata), tf_example)\nreturn t... | <|body_start_0|>
self.input_str = input_str
self.output_str = output_str
self.metadata = metadata
<|end_body_0|>
<|body_start_1|>
tf_example = tf.train.Example()
add_text_feature('inputs', self.input_str, tf_example)
add_text_feature('targets', self.output_str, tf_exampl... | Represents a sequence-to-sequence training example. | Seq2SeqExample | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Seq2SeqExample:
"""Represents a sequence-to-sequence training example."""
def __init__(self, input_str: Text, output_str: Text, metadata: Any=None):
"""Constructs a Seq2SeqExample. Args: input_str: input text. Not tokenized into a sequence yet. output_str: output text. Not tokenized ... | stack_v2_sparse_classes_36k_train_007123 | 2,997 | permissive | [
{
"docstring": "Constructs a Seq2SeqExample. Args: input_str: input text. Not tokenized into a sequence yet. output_str: output text. Not tokenized into a sequence yet. metadata: arbitrary metadata, must be pickle-able.",
"name": "__init__",
"signature": "def __init__(self, input_str: Text, output_str: ... | 2 | null | Implement the Python class `Seq2SeqExample` described below.
Class description:
Represents a sequence-to-sequence training example.
Method signatures and docstrings:
- def __init__(self, input_str: Text, output_str: Text, metadata: Any=None): Constructs a Seq2SeqExample. Args: input_str: input text. Not tokenized int... | Implement the Python class `Seq2SeqExample` described below.
Class description:
Represents a sequence-to-sequence training example.
Method signatures and docstrings:
- def __init__(self, input_str: Text, output_str: Text, metadata: Any=None): Constructs a Seq2SeqExample. Args: input_str: input text. Not tokenized int... | f5f6f50f82bd441339c9d9efbef3f09e72c5fef6 | <|skeleton|>
class Seq2SeqExample:
"""Represents a sequence-to-sequence training example."""
def __init__(self, input_str: Text, output_str: Text, metadata: Any=None):
"""Constructs a Seq2SeqExample. Args: input_str: input text. Not tokenized into a sequence yet. output_str: output text. Not tokenized ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Seq2SeqExample:
"""Represents a sequence-to-sequence training example."""
def __init__(self, input_str: Text, output_str: Text, metadata: Any=None):
"""Constructs a Seq2SeqExample. Args: input_str: input text. Not tokenized into a sequence yet. output_str: output text. Not tokenized into a sequen... | the_stack_v2_python_sparse | baselines/t5/data/deepbank/data_utils.py | google/uncertainty-baselines | train | 1,235 |
77ba90c78ddf3ae9705a4a5125a93a88d3df265e | [
"if Translator.__language == language:\n return True\nif language == QLocale.German:\n Translator.__translator = None\nelse:\n try:\n items = minidom.parse(SystemInfo.RESOURCES + 'languages/' + QLocale(language).name() + '.xml').getElementsByTagName('item')\n except (FileNotFoundError, OverflowEr... | <|body_start_0|>
if Translator.__language == language:
return True
if language == QLocale.German:
Translator.__translator = None
else:
try:
items = minidom.parse(SystemInfo.RESOURCES + 'languages/' + QLocale(language).name() + '.xml').getElemen... | Static class for getting translations and changing languages Attributes: language_changed (Signal): Emits updates when the language is changed. | Translator | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Translator:
"""Static class for getting translations and changing languages Attributes: language_changed (Signal): Emits updates when the language is changed."""
def install_translator(language: int) -> bool:
"""Installs a translator with the given language Args: language (int): A Qt... | stack_v2_sparse_classes_36k_train_007124 | 2,379 | permissive | [
{
"docstring": "Installs a translator with the given language Args: language (int): A Qt language from QLocale. (e.g.: QLocale.English) Returns: bool: If the installation was successful. Mostly depends on if the given language has a language file in /resources/languages/.",
"name": "install_translator",
... | 2 | null | Implement the Python class `Translator` described below.
Class description:
Static class for getting translations and changing languages Attributes: language_changed (Signal): Emits updates when the language is changed.
Method signatures and docstrings:
- def install_translator(language: int) -> bool: Installs a tran... | Implement the Python class `Translator` described below.
Class description:
Static class for getting translations and changing languages Attributes: language_changed (Signal): Emits updates when the language is changed.
Method signatures and docstrings:
- def install_translator(language: int) -> bool: Installs a tran... | 5c4f19b1dbce8facd87919dc81d7d1eccb16b552 | <|skeleton|>
class Translator:
"""Static class for getting translations and changing languages Attributes: language_changed (Signal): Emits updates when the language is changed."""
def install_translator(language: int) -> bool:
"""Installs a translator with the given language Args: language (int): A Qt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Translator:
"""Static class for getting translations and changing languages Attributes: language_changed (Signal): Emits updates when the language is changed."""
def install_translator(language: int) -> bool:
"""Installs a translator with the given language Args: language (int): A Qt language fro... | the_stack_v2_python_sparse | phypigui/python/src/view/Translator.py | osl2/PhyPiDAQ | train | 3 |
5265436fd6837890e0f653fabd6f78032b6254a4 | [
"self.N = N\nself.n_avg = n_avg\nself.Nbars = Nbars\nself.bar_char = char\nself.i_step = 0\nself.start_time = time.time()\nself.prev_time = self.start_time\nself.total_duration = 0.0\nself.time_per_step = 0.0\nself.avg_time_per_step = 0.0\nself.eta = None",
"self.i_step = i_step\ncurr_time = time.time()\nself.tot... | <|body_start_0|>
self.N = N
self.n_avg = n_avg
self.Nbars = Nbars
self.bar_char = char
self.i_step = 0
self.start_time = time.time()
self.prev_time = self.start_time
self.total_duration = 0.0
self.time_per_step = 0.0
self.avg_time_per_step ... | ProgressBar class that keeps track of the time spent by the algorithm. It handles the calculation and printing of the progress bar and a summary of the total runtime. | ProgressBar | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgressBar:
"""ProgressBar class that keeps track of the time spent by the algorithm. It handles the calculation and printing of the progress bar and a summary of the total runtime."""
def __init__(self, N, n_avg=20, Nbars=35, char=progress_char):
"""Initializes a timer / progressio... | stack_v2_sparse_classes_36k_train_007125 | 12,668 | permissive | [
{
"docstring": "Initializes a timer / progression bar. Timing is done with respect to the absolute time at initialization. Parameters ---------- N: int The total number of iterations performed by the step loop n_avg: int, optional The amount of recent timesteps used to calculate the average time taken by a step... | 4 | null | Implement the Python class `ProgressBar` described below.
Class description:
ProgressBar class that keeps track of the time spent by the algorithm. It handles the calculation and printing of the progress bar and a summary of the total runtime.
Method signatures and docstrings:
- def __init__(self, N, n_avg=20, Nbars=... | Implement the Python class `ProgressBar` described below.
Class description:
ProgressBar class that keeps track of the time spent by the algorithm. It handles the calculation and printing of the progress bar and a summary of the total runtime.
Method signatures and docstrings:
- def __init__(self, N, n_avg=20, Nbars=... | 5744598571eab40c4fb45cc3db21f346b69b1f37 | <|skeleton|>
class ProgressBar:
"""ProgressBar class that keeps track of the time spent by the algorithm. It handles the calculation and printing of the progress bar and a summary of the total runtime."""
def __init__(self, N, n_avg=20, Nbars=35, char=progress_char):
"""Initializes a timer / progressio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProgressBar:
"""ProgressBar class that keeps track of the time spent by the algorithm. It handles the calculation and printing of the progress bar and a summary of the total runtime."""
def __init__(self, N, n_avg=20, Nbars=35, char=progress_char):
"""Initializes a timer / progression bar. Timing... | the_stack_v2_python_sparse | fbpic/utils/printing.py | fbpic/fbpic | train | 163 |
4c565bcf14d62808df7d09952fc54d2e0063cbc3 | [
"molecule = Molecule().from_adjacency_list('\\n1 C u0 p0 c0 {2,B} {6,B} {7,S}\\n2 C u0 p0 c0 {1,B} {3,B} {8,S}\\n3 C u0 p0 c0 {2,B} {4,B} {9,S}\\n4 C u0 p0 c0 {3,B} {5,B} {10,S}\\n5 C u0 p0 c0 {4,B} {6,B} {11,S}\\n6 C u0 p0 c0 {1,B} {5,B} {12,S}\\n7 H u0 p0 c0 {1,S}\\n8 H u0 p0 c0 {2,S}\\n9 H u0 p0 c0 {3,S... | <|body_start_0|>
molecule = Molecule().from_adjacency_list('\n1 C u0 p0 c0 {2,B} {6,B} {7,S}\n2 C u0 p0 c0 {1,B} {3,B} {8,S}\n3 C u0 p0 c0 {2,B} {4,B} {9,S}\n4 C u0 p0 c0 {3,B} {5,B} {10,S}\n5 C u0 p0 c0 {4,B} {6,B} {11,S}\n6 C u0 p0 c0 {1,B} {5,B} {12,S}\n7 H u0 p0 c0 {1,S}\n8 H u0 p0 c0 {2,S}\n9 H u0... | KekulizeTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KekulizeTest:
def setUp(self):
"""To be run before each test."""
<|body_0|>
def test_aromatic_ring(self):
"""Test that the AromaticRing class works properly for kekulization."""
<|body_1|>
def test_aromatic_bond(self):
"""Test that the AromaticBo... | stack_v2_sparse_classes_36k_train_007126 | 3,911 | permissive | [
{
"docstring": "To be run before each test.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that the AromaticRing class works properly for kekulization.",
"name": "test_aromatic_ring",
"signature": "def test_aromatic_ring(self)"
},
{
"docstring": "Test t... | 3 | null | Implement the Python class `KekulizeTest` described below.
Class description:
Implement the KekulizeTest class.
Method signatures and docstrings:
- def setUp(self): To be run before each test.
- def test_aromatic_ring(self): Test that the AromaticRing class works properly for kekulization.
- def test_aromatic_bond(se... | Implement the Python class `KekulizeTest` described below.
Class description:
Implement the KekulizeTest class.
Method signatures and docstrings:
- def setUp(self): To be run before each test.
- def test_aromatic_ring(self): Test that the AromaticRing class works properly for kekulization.
- def test_aromatic_bond(se... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class KekulizeTest:
def setUp(self):
"""To be run before each test."""
<|body_0|>
def test_aromatic_ring(self):
"""Test that the AromaticRing class works properly for kekulization."""
<|body_1|>
def test_aromatic_bond(self):
"""Test that the AromaticBo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KekulizeTest:
def setUp(self):
"""To be run before each test."""
molecule = Molecule().from_adjacency_list('\n1 C u0 p0 c0 {2,B} {6,B} {7,S}\n2 C u0 p0 c0 {1,B} {3,B} {8,S}\n3 C u0 p0 c0 {2,B} {4,B} {9,S}\n4 C u0 p0 c0 {3,B} {5,B} {10,S}\n5 C u0 p0 c0 {4,B} {6,B} {11,S}\n6 C u0 p0 c0 {1,... | the_stack_v2_python_sparse | rmgpy/molecule/kekulizeTest.py | CanePan-cc/CanePanWorkshop | train | 2 | |
5b879393af55381501926d50908df27c824a29c8 | [
"self._short_name = 'Webcam'\nself._capture = cv.VideoCapture(camera_id)\nself._capture.set(cv.CAP_PROP_FRAME_WIDTH, 1280)\nself._capture.set(cv.CAP_PROP_FRAME_HEIGHT, 720)\nself._capture.set(cv.CAP_PROP_FOURCC, cv.VideoWriter_fourcc(*'MJPG'))\nself._capture.set(cv.CAP_PROP_FPS, fps)\nsuper().__init__(**kwargs)",
... | <|body_start_0|>
self._short_name = 'Webcam'
self._capture = cv.VideoCapture(camera_id)
self._capture.set(cv.CAP_PROP_FRAME_WIDTH, 1280)
self._capture.set(cv.CAP_PROP_FRAME_HEIGHT, 720)
self._capture.set(cv.CAP_PROP_FOURCC, cv.VideoWriter_fourcc(*'MJPG'))
self._capture.se... | Webcam frame grabbing and preprocessing. | Webcam | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Webcam:
"""Webcam frame grabbing and preprocessing."""
def __init__(self, camera_id=0, fps=60, **kwargs):
"""Create queues and threads to read and preprocess data."""
<|body_0|>
def frame_generator(self):
"""Read frame from webcam."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_007127 | 887 | permissive | [
{
"docstring": "Create queues and threads to read and preprocess data.",
"name": "__init__",
"signature": "def __init__(self, camera_id=0, fps=60, **kwargs)"
},
{
"docstring": "Read frame from webcam.",
"name": "frame_generator",
"signature": "def frame_generator(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004177 | Implement the Python class `Webcam` described below.
Class description:
Webcam frame grabbing and preprocessing.
Method signatures and docstrings:
- def __init__(self, camera_id=0, fps=60, **kwargs): Create queues and threads to read and preprocess data.
- def frame_generator(self): Read frame from webcam. | Implement the Python class `Webcam` described below.
Class description:
Webcam frame grabbing and preprocessing.
Method signatures and docstrings:
- def __init__(self, camera_id=0, fps=60, **kwargs): Create queues and threads to read and preprocess data.
- def frame_generator(self): Read frame from webcam.
<|skeleto... | 2b4a15b95b4e1f2e9e8c7359416747fd4d26d4a9 | <|skeleton|>
class Webcam:
"""Webcam frame grabbing and preprocessing."""
def __init__(self, camera_id=0, fps=60, **kwargs):
"""Create queues and threads to read and preprocess data."""
<|body_0|>
def frame_generator(self):
"""Read frame from webcam."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Webcam:
"""Webcam frame grabbing and preprocessing."""
def __init__(self, camera_id=0, fps=60, **kwargs):
"""Create queues and threads to read and preprocess data."""
self._short_name = 'Webcam'
self._capture = cv.VideoCapture(camera_id)
self._capture.set(cv.CAP_PROP_FRAME... | the_stack_v2_python_sparse | watcher/from_internet_or_for_from_internet/GazeML/src/datasources/webcam.py | framaz/eye_control | train | 3 |
aa35bdcbcfdfc6d14c728a6e069d98747a89aa07 | [
"l = 0\nr = len(nums) - 1\nwhile l < r:\n if target > nums[r] or target < nums[l]:\n return [-1, -1]\n k = (r + l) // 2\n if nums[k] == target:\n tl = tr = k\n while tl - 1 >= 0 and nums[tl - 1] == target:\n tl -= 1\n while tr + 1 < len(nums) and nums[tr + 1] == targe... | <|body_start_0|>
l = 0
r = len(nums) - 1
while l < r:
if target > nums[r] or target < nums[l]:
return [-1, -1]
k = (r + l) // 2
if nums[k] == target:
tl = tr = k
while tl - 1 >= 0 and nums[tl - 1] == target:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchRange(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def searchRange1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_007128 | 1,924 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "searchRange",
"signature": "def searchRange(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "searchRange1",
"signature": "def searchRange1(self... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def searchRange1(self, nums, target): :type nums: List[int] :type target: int :rt... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def searchRange1(self, nums, target): :type nums: List[int] :type target: int :rt... | 863b89be674a82eef60c0f33d726ac08d43f2e01 | <|skeleton|>
class Solution:
def searchRange(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def searchRange1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchRange(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
l = 0
r = len(nums) - 1
while l < r:
if target > nums[r] or target < nums[l]:
return [-1, -1]
k = (r + l) // 2
if n... | the_stack_v2_python_sparse | q34_Search_for_a_Range.py | Ryuya1995/leetcode | train | 0 | |
4939ec7ab0c75fa91d1dbea1455e4815f5580360 | [
"super().__init__()\ncheck_pos_int(n_samples, 'n_samples')\nself.n_samples = n_samples\nself.near = near\nself.far = far\nself.is_perturb = is_perturb",
"zs = torch.linspace(0.0, 1.0, self.n_samples, device=rays_d.device)\nnear = torch.as_tensor(self.near, device=rays_d.device)\nfar = torch.as_tensor(self.far, de... | <|body_start_0|>
super().__init__()
check_pos_int(n_samples, 'n_samples')
self.n_samples = n_samples
self.near = near
self.far = far
self.is_perturb = is_perturb
<|end_body_0|>
<|body_start_1|>
zs = torch.linspace(0.0, 1.0, self.n_samples, device=rays_d.device)
... | Randomly samples a ray. Takes as input a ray origin and direction, `near`, `far`, the number of points to sample and generates point coordinates across each given ray. Usage: .. code-block:: python near = 0.1 far = 5.0 n_samples = 1000 sampler = UniformRaySampler(near, far, n_samples) points, z_vals = sampler(ray_direc... | UniformRaySampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UniformRaySampler:
"""Randomly samples a ray. Takes as input a ray origin and direction, `near`, `far`, the number of points to sample and generates point coordinates across each given ray. Usage: .. code-block:: python near = 0.1 far = 5.0 n_samples = 1000 sampler = UniformRaySampler(near, far, ... | stack_v2_sparse_classes_36k_train_007129 | 2,882 | permissive | [
{
"docstring": "Args: near (float): Minimum depth value corresponding to the sampled points. far (float): Maximum depth value corresponding to the sampled points. n_samples (int): Number of sampled points along the ray. is_perturb (bool): Boolean flag indicating whether to perturb the sampled points (True) or n... | 2 | stack_v2_sparse_classes_30k_train_016727 | Implement the Python class `UniformRaySampler` described below.
Class description:
Randomly samples a ray. Takes as input a ray origin and direction, `near`, `far`, the number of points to sample and generates point coordinates across each given ray. Usage: .. code-block:: python near = 0.1 far = 5.0 n_samples = 1000 ... | Implement the Python class `UniformRaySampler` described below.
Class description:
Randomly samples a ray. Takes as input a ray origin and direction, `near`, `far`, the number of points to sample and generates point coordinates across each given ray. Usage: .. code-block:: python near = 0.1 far = 5.0 n_samples = 1000 ... | da3680cce7e8fc4c194f13a1528cddbad9a18ab0 | <|skeleton|>
class UniformRaySampler:
"""Randomly samples a ray. Takes as input a ray origin and direction, `near`, `far`, the number of points to sample and generates point coordinates across each given ray. Usage: .. code-block:: python near = 0.1 far = 5.0 n_samples = 1000 sampler = UniformRaySampler(near, far, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UniformRaySampler:
"""Randomly samples a ray. Takes as input a ray origin and direction, `near`, `far`, the number of points to sample and generates point coordinates across each given ray. Usage: .. code-block:: python near = 0.1 far = 5.0 n_samples = 1000 sampler = UniformRaySampler(near, far, n_samples) po... | the_stack_v2_python_sparse | pynif3d/sampling/ray/uniform.py | pfnet/pynif3d | train | 72 |
069bf51e910ef7f9a397305137ca4742a7eab939 | [
"self.__mongo = mongodb()\nself.code = code\nself.ratetype = ratetype",
"key = {'index': True}\nTime = strTostr(getNow('%Y'), '%Y')\ninitial = {'rate': 0, 'datadate': Time}\nreduces = 'function(doc,prev){\\n \\n if (prev.datadate<doc.datadate){\\n prev.rate = doc.rate;... | <|body_start_0|>
self.__mongo = mongodb()
self.code = code
self.ratetype = ratetype
<|end_body_0|>
<|body_start_1|>
key = {'index': True}
Time = strTostr(getNow('%Y'), '%Y')
initial = {'rate': 0, 'datadate': Time}
reduces = 'function(doc,prev){\n \n ... | 获取银行拆借利率 | BankRate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BankRate:
"""获取银行拆借利率"""
def __init__(self, code, ratetype):
"""code:货币 ratetype:拆借利率期限"""
<|body_0|>
def getMax(self):
"""获取利率最大的日期对应的日期"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.__mongo = mongodb()
self.code = code
s... | stack_v2_sparse_classes_36k_train_007130 | 3,173 | no_license | [
{
"docstring": "code:货币 ratetype:拆借利率期限",
"name": "__init__",
"signature": "def __init__(self, code, ratetype)"
},
{
"docstring": "获取利率最大的日期对应的日期",
"name": "getMax",
"signature": "def getMax(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013516 | Implement the Python class `BankRate` described below.
Class description:
获取银行拆借利率
Method signatures and docstrings:
- def __init__(self, code, ratetype): code:货币 ratetype:拆借利率期限
- def getMax(self): 获取利率最大的日期对应的日期 | Implement the Python class `BankRate` described below.
Class description:
获取银行拆借利率
Method signatures and docstrings:
- def __init__(self, code, ratetype): code:货币 ratetype:拆借利率期限
- def getMax(self): 获取利率最大的日期对应的日期
<|skeleton|>
class BankRate:
"""获取银行拆借利率"""
def __init__(self, code, ratetype):
"""cod... | 37e0cfced06746b50a687b502937773f11eefb99 | <|skeleton|>
class BankRate:
"""获取银行拆借利率"""
def __init__(self, code, ratetype):
"""code:货币 ratetype:拆借利率期限"""
<|body_0|>
def getMax(self):
"""获取利率最大的日期对应的日期"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BankRate:
"""获取银行拆借利率"""
def __init__(self, code, ratetype):
"""code:货币 ratetype:拆借利率期限"""
self.__mongo = mongodb()
self.code = code
self.ratetype = ratetype
def getMax(self):
"""获取利率最大的日期对应的日期"""
key = {'index': True}
Time = strTostr(getNow('%... | the_stack_v2_python_sparse | webseriver/database/mongodb.py | 12jk-M/test | train | 0 |
eaeb84405f61cd96cef3f102fd390e44f2dd989e | [
"self.ensure_one()\nres = {'name': self.name, 'sequence': self.sequence, 'origin': self.order_id.name, 'account_id': self.product_id.product_tmpl_id._get_product_accounts()['stock_input'].id, 'price_unit': self.price_unit, 'quantity': qty, 'uom_id': self.product_uom.id, 'product_id': self.product_id.id or False, 'i... | <|body_start_0|>
self.ensure_one()
res = {'name': self.name, 'sequence': self.sequence, 'origin': self.order_id.name, 'account_id': self.product_id.product_tmpl_id._get_product_accounts()['stock_input'].id, 'price_unit': self.price_unit, 'quantity': qty, 'uom_id': self.product_uom.id, 'product_id': self... | PurchaseOrderLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PurchaseOrderLine:
def _prepare_invoice_line(self, qty):
"""Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice"""
<|body_0|>
def invoice_line_create(self, invoice_id, qty):
"""Create an invoice line... | stack_v2_sparse_classes_36k_train_007131 | 6,989 | no_license | [
{
"docstring": "Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice",
"name": "_prepare_invoice_line",
"signature": "def _prepare_invoice_line(self, qty)"
},
{
"docstring": "Create an invoice line. The quantity to invoice can be... | 2 | stack_v2_sparse_classes_30k_train_004569 | Implement the Python class `PurchaseOrderLine` described below.
Class description:
Implement the PurchaseOrderLine class.
Method signatures and docstrings:
- def _prepare_invoice_line(self, qty): Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice
- ... | Implement the Python class `PurchaseOrderLine` described below.
Class description:
Implement the PurchaseOrderLine class.
Method signatures and docstrings:
- def _prepare_invoice_line(self, qty): Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice
- ... | c355e18aeb3e7123fe184fcc7ec06485ab498343 | <|skeleton|>
class PurchaseOrderLine:
def _prepare_invoice_line(self, qty):
"""Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice"""
<|body_0|>
def invoice_line_create(self, invoice_id, qty):
"""Create an invoice line... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PurchaseOrderLine:
def _prepare_invoice_line(self, qty):
"""Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice"""
self.ensure_one()
res = {'name': self.name, 'sequence': self.sequence, 'origin': self.order_id.name, 'a... | the_stack_v2_python_sparse | deliver_auto_invoice/models/purchase_order.py | rythe77/odoo11_customized | train | 5 | |
cbc5db4b2f9aaaac65e54d81baef2f57cf3dd060 | [
"try:\n function(*params, **kwargs)\n self.fail('Expected exception %s was not raised' % exception.__name__)\nexcept exception as err:\n match = bool(re.match(regexp, str(err)))\n self.assertTrue(match, 'Expected match \"%s\", found \"%s\"' % (regexp, err))",
"value1, params1 = cgi.parse_header(header... | <|body_start_0|>
try:
function(*params, **kwargs)
self.fail('Expected exception %s was not raised' % exception.__name__)
except exception as err:
match = bool(re.match(regexp, str(err)))
self.assertTrue(match, 'Expected match "%s", found "%s"' % (regexp, e... | TestCase | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCase:
def assertRaisesWithRegexpMatch(self, exception, regexp, function, *params, **kwargs):
"""Check that exception is raised and text matches regular expression. Args: exception: Exception type that is expected. regexp: String regular expression that is expected in error message. f... | stack_v2_sparse_classes_36k_train_007132 | 23,309 | permissive | [
{
"docstring": "Check that exception is raised and text matches regular expression. Args: exception: Exception type that is expected. regexp: String regular expression that is expected in error message. function: Callable to test. params: Parameters to forward to function. kwargs: Keyword arguments to forward t... | 3 | null | Implement the Python class `TestCase` described below.
Class description:
Implement the TestCase class.
Method signatures and docstrings:
- def assertRaisesWithRegexpMatch(self, exception, regexp, function, *params, **kwargs): Check that exception is raised and text matches regular expression. Args: exception: Except... | Implement the Python class `TestCase` described below.
Class description:
Implement the TestCase class.
Method signatures and docstrings:
- def assertRaisesWithRegexpMatch(self, exception, regexp, function, *params, **kwargs): Check that exception is raised and text matches regular expression. Args: exception: Except... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class TestCase:
def assertRaisesWithRegexpMatch(self, exception, regexp, function, *params, **kwargs):
"""Check that exception is raised and text matches regular expression. Args: exception: Exception type that is expected. regexp: String regular expression that is expected in error message. f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCase:
def assertRaisesWithRegexpMatch(self, exception, regexp, function, *params, **kwargs):
"""Check that exception is raised and text matches regular expression. Args: exception: Exception type that is expected. regexp: String regular expression that is expected in error message. function: Calla... | the_stack_v2_python_sparse | third_party/google-endpoints/apitools/base/protorpclite/test_util.py | catapult-project/catapult | train | 2,032 | |
eb4b47cb6f27ba9d8a6588ceda68177ad7208028 | [
"u = usermanage(self.driver)\nu.open_usermanage()\nself.assertEqual(u.verify(), True)\nu.delete()\nself.assertEqual(u.reason(), '请选择一条数据')\nfunction.screenshot(self.driver, 'user_unselect.jpg')",
"u = usermanage(self.driver)\nu.open_usermanage()\nself.assertEqual(u.verify(), True)\nu.multi_select()\nu.modify()\ns... | <|body_start_0|>
u = usermanage(self.driver)
u.open_usermanage()
self.assertEqual(u.verify(), True)
u.delete()
self.assertEqual(u.reason(), '请选择一条数据')
function.screenshot(self.driver, 'user_unselect.jpg')
<|end_body_0|>
<|body_start_1|>
u = usermanage(self.driver... | Test012_User_List_Error | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test012_User_List_Error:
def test_unselect(self):
"""不选择任何用户"""
<|body_0|>
def test_multiselect(self):
"""选择两个用户"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
u = usermanage(self.driver)
u.open_usermanage()
self.assertEqual(u.verif... | stack_v2_sparse_classes_36k_train_007133 | 910 | no_license | [
{
"docstring": "不选择任何用户",
"name": "test_unselect",
"signature": "def test_unselect(self)"
},
{
"docstring": "选择两个用户",
"name": "test_multiselect",
"signature": "def test_multiselect(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012415 | Implement the Python class `Test012_User_List_Error` described below.
Class description:
Implement the Test012_User_List_Error class.
Method signatures and docstrings:
- def test_unselect(self): 不选择任何用户
- def test_multiselect(self): 选择两个用户 | Implement the Python class `Test012_User_List_Error` described below.
Class description:
Implement the Test012_User_List_Error class.
Method signatures and docstrings:
- def test_unselect(self): 不选择任何用户
- def test_multiselect(self): 选择两个用户
<|skeleton|>
class Test012_User_List_Error:
def test_unselect(self):
... | 6f42c25249fc642cecc270578a180820988d45b5 | <|skeleton|>
class Test012_User_List_Error:
def test_unselect(self):
"""不选择任何用户"""
<|body_0|>
def test_multiselect(self):
"""选择两个用户"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test012_User_List_Error:
def test_unselect(self):
"""不选择任何用户"""
u = usermanage(self.driver)
u.open_usermanage()
self.assertEqual(u.verify(), True)
u.delete()
self.assertEqual(u.reason(), '请选择一条数据')
function.screenshot(self.driver, 'user_unselect.jpg')
... | the_stack_v2_python_sparse | GlxssLive_web/TestCase/Manage_User/Test012_user_list_error.py | rrmiracle/GlxssLive | train | 0 | |
b11e588dca325eca9295a6c2502c26034556c028 | [
"self.name = name\nself.factory = factory\nself.no_cache = no_cache",
"if inst is None:\n return self\n\ndef method():\n try:\n resource_path_names = inst.path_names + (self.name,)\n cached_resource = inst.acquire.resource_cache_get(resource_path_names)\n except AttributeError:\n cac... | <|body_start_0|>
self.name = name
self.factory = factory
self.no_cache = no_cache
<|end_body_0|>
<|body_start_1|>
if inst is None:
return self
def method():
try:
resource_path_names = inst.path_names + (self.name,)
cached_... | NamedResourceFactoryDecorator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NamedResourceFactoryDecorator:
def __init__(self, name, factory, no_cache):
"""Initialize decorator"""
<|body_0|>
def __get__(self, inst, owner):
"""Some serious depp python stuff going on here.... The get magic method allows an object to behave as a class property s... | stack_v2_sparse_classes_36k_train_007134 | 5,320 | permissive | [
{
"docstring": "Initialize decorator",
"name": "__init__",
"signature": "def __init__(self, name, factory, no_cache)"
},
{
"docstring": "Some serious depp python stuff going on here.... The get magic method allows an object to behave as a class property such as @property. It returns the attribut... | 2 | stack_v2_sparse_classes_30k_train_008799 | Implement the Python class `NamedResourceFactoryDecorator` described below.
Class description:
Implement the NamedResourceFactoryDecorator class.
Method signatures and docstrings:
- def __init__(self, name, factory, no_cache): Initialize decorator
- def __get__(self, inst, owner): Some serious depp python stuff going... | Implement the Python class `NamedResourceFactoryDecorator` described below.
Class description:
Implement the NamedResourceFactoryDecorator class.
Method signatures and docstrings:
- def __init__(self, name, factory, no_cache): Initialize decorator
- def __get__(self, inst, owner): Some serious depp python stuff going... | 52f24d7f1f22c0ba14884fa84766b1c7084ef7bb | <|skeleton|>
class NamedResourceFactoryDecorator:
def __init__(self, name, factory, no_cache):
"""Initialize decorator"""
<|body_0|>
def __get__(self, inst, owner):
"""Some serious depp python stuff going on here.... The get magic method allows an object to behave as a class property s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NamedResourceFactoryDecorator:
def __init__(self, name, factory, no_cache):
"""Initialize decorator"""
self.name = name
self.factory = factory
self.no_cache = no_cache
def __get__(self, inst, owner):
"""Some serious depp python stuff going on here.... The get magic... | the_stack_v2_python_sparse | contextplus/behaviour/named_resource.py | olivelink/contextplus | train | 0 | |
a013fa0ff4da8a585245e58ef7e969e6e62b3b75 | [
"global channel_summary_page, admin_page\nchannel_summary_page = ChannelSummaryPage(self.driver)\nadmin_page = AdminPage(self.driver)\nadmin_page.into_subsystem('业务管理')\nadmin_page.select_menu('首页/渠道业务管理')",
"admin_page.select_menu('渠道汇总')\nchannel_summary_page.query_channel()\nassert '北京市' in channel_summary_pag... | <|body_start_0|>
global channel_summary_page, admin_page
channel_summary_page = ChannelSummaryPage(self.driver)
admin_page = AdminPage(self.driver)
admin_page.into_subsystem('业务管理')
admin_page.select_menu('首页/渠道业务管理')
<|end_body_0|>
<|body_start_1|>
admin_page.select_men... | TestChannelSummary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestChannelSummary:
def set_up(self):
"""前置操作 :return:"""
<|body_0|>
def test_query_channel_organization(self, set_up):
"""渠道机构查询 :return:"""
<|body_1|>
def test_view_channel_next_organization(self):
"""查看下级渠道机构 :return:"""
<|body_2|>
<|... | stack_v2_sparse_classes_36k_train_007135 | 1,546 | no_license | [
{
"docstring": "前置操作 :return:",
"name": "set_up",
"signature": "def set_up(self)"
},
{
"docstring": "渠道机构查询 :return:",
"name": "test_query_channel_organization",
"signature": "def test_query_channel_organization(self, set_up)"
},
{
"docstring": "查看下级渠道机构 :return:",
"name": "t... | 3 | stack_v2_sparse_classes_30k_train_016982 | Implement the Python class `TestChannelSummary` described below.
Class description:
Implement the TestChannelSummary class.
Method signatures and docstrings:
- def set_up(self): 前置操作 :return:
- def test_query_channel_organization(self, set_up): 渠道机构查询 :return:
- def test_view_channel_next_organization(self): 查看下级渠道机构... | Implement the Python class `TestChannelSummary` described below.
Class description:
Implement the TestChannelSummary class.
Method signatures and docstrings:
- def set_up(self): 前置操作 :return:
- def test_query_channel_organization(self, set_up): 渠道机构查询 :return:
- def test_view_channel_next_organization(self): 查看下级渠道机构... | 86d1b085af2d3808ac8472d541f4bf26d26591e0 | <|skeleton|>
class TestChannelSummary:
def set_up(self):
"""前置操作 :return:"""
<|body_0|>
def test_query_channel_organization(self, set_up):
"""渠道机构查询 :return:"""
<|body_1|>
def test_view_channel_next_organization(self):
"""查看下级渠道机构 :return:"""
<|body_2|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestChannelSummary:
def set_up(self):
"""前置操作 :return:"""
global channel_summary_page, admin_page
channel_summary_page = ChannelSummaryPage(self.driver)
admin_page = AdminPage(self.driver)
admin_page.into_subsystem('业务管理')
admin_page.select_menu('首页/渠道业务管理')
... | the_stack_v2_python_sparse | src/cases/business_manage/channel_business_manage/test_channel_summary_page_150.py | 102244653/SeleniumByPython | train | 2 | |
981db8e6227436fa28617cab2656a7401f230519 | [
"try:\n tags = TagDao().list_all_tags()\n self.finish(json_dumps({'status': 0, 'msg': 'ok', 'values': tags}))\nexcept Exception as err:\n logger.error(err)\n self.finish(json_dumps({'status': -1, 'msg': 'fail to get data from database'}))",
"body = self.request.body\ntry:\n tags = [dict(app='nebula... | <|body_start_0|>
try:
tags = TagDao().list_all_tags()
self.finish(json_dumps({'status': 0, 'msg': 'ok', 'values': tags}))
except Exception as err:
logger.error(err)
self.finish(json_dumps({'status': -1, 'msg': 'fail to get data from database'}))
<|end_body... | TagsHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagsHandler:
def get(self):
"""获取所有的tags @API summary: 获取所有的tags notes: 获取所有的tags tags: - nebula produces: - application/json"""
<|body_0|>
def post(self):
"""新增tag @API summary: add a list of tags notes: add new tags tags: - nebula parameters: - name: tags in: body ... | stack_v2_sparse_classes_36k_train_007136 | 20,036 | permissive | [
{
"docstring": "获取所有的tags @API summary: 获取所有的tags notes: 获取所有的tags tags: - nebula produces: - application/json",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "新增tag @API summary: add a list of tags notes: add new tags tags: - nebula parameters: - name: tags in: body required: tr... | 2 | stack_v2_sparse_classes_30k_test_000873 | Implement the Python class `TagsHandler` described below.
Class description:
Implement the TagsHandler class.
Method signatures and docstrings:
- def get(self): 获取所有的tags @API summary: 获取所有的tags notes: 获取所有的tags tags: - nebula produces: - application/json
- def post(self): 新增tag @API summary: add a list of tags notes... | Implement the Python class `TagsHandler` described below.
Class description:
Implement the TagsHandler class.
Method signatures and docstrings:
- def get(self): 获取所有的tags @API summary: 获取所有的tags notes: 获取所有的tags tags: - nebula produces: - application/json
- def post(self): 新增tag @API summary: add a list of tags notes... | 2e32e6e7b225e0bd87ee8c847c22862f12c51bb1 | <|skeleton|>
class TagsHandler:
def get(self):
"""获取所有的tags @API summary: 获取所有的tags notes: 获取所有的tags tags: - nebula produces: - application/json"""
<|body_0|>
def post(self):
"""新增tag @API summary: add a list of tags notes: add new tags tags: - nebula parameters: - name: tags in: body ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TagsHandler:
def get(self):
"""获取所有的tags @API summary: 获取所有的tags notes: 获取所有的tags tags: - nebula produces: - application/json"""
try:
tags = TagDao().list_all_tags()
self.finish(json_dumps({'status': 0, 'msg': 'ok', 'values': tags}))
except Exception as err:
... | the_stack_v2_python_sparse | nebula/views/strategy.py | threathunterX/nebula_web | train | 2 | |
fa4c7bf4224f2b13e4f02b76348002374384aa90 | [
"super().__init__(schema)\nhcs_cust = Customer.objects.filter(schema_name=schema).first()\nself._ebs_acct_num = hcs_cust.account_id\nself._org_id = hcs_cust.org_id",
"ctx = {'schema': self.schema, 'provider_type': provider, 'provider_uuid': provider_uuid, 'date': date, 'org_id': self._org_id, 'ebs_account': self.... | <|body_start_0|>
super().__init__(schema)
hcs_cust = Customer.objects.filter(schema_name=schema).first()
self._ebs_acct_num = hcs_cust.account_id
self._org_id = hcs_cust.org_id
<|end_body_0|>
<|body_start_1|>
ctx = {'schema': self.schema, 'provider_type': provider, 'provider_uui... | Class to interact with customer reporting tables. | HCSReportDBAccessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HCSReportDBAccessor:
"""Class to interact with customer reporting tables."""
def __init__(self, schema):
"""Establish the database connection. :param schema (str): The customer schema to associate with"""
<|body_0|>
def get_hcs_daily_summary(self, date, provider, provide... | stack_v2_sparse_classes_36k_train_007137 | 4,327 | permissive | [
{
"docstring": "Establish the database connection. :param schema (str): The customer schema to associate with",
"name": "__init__",
"signature": "def __init__(self, schema)"
},
{
"docstring": "Build HCS daily report. :param date (datetime.date) The date to process :param provider (str) The provi... | 2 | stack_v2_sparse_classes_30k_test_000020 | Implement the Python class `HCSReportDBAccessor` described below.
Class description:
Class to interact with customer reporting tables.
Method signatures and docstrings:
- def __init__(self, schema): Establish the database connection. :param schema (str): The customer schema to associate with
- def get_hcs_daily_summa... | Implement the Python class `HCSReportDBAccessor` described below.
Class description:
Class to interact with customer reporting tables.
Method signatures and docstrings:
- def __init__(self, schema): Establish the database connection. :param schema (str): The customer schema to associate with
- def get_hcs_daily_summa... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class HCSReportDBAccessor:
"""Class to interact with customer reporting tables."""
def __init__(self, schema):
"""Establish the database connection. :param schema (str): The customer schema to associate with"""
<|body_0|>
def get_hcs_daily_summary(self, date, provider, provide... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HCSReportDBAccessor:
"""Class to interact with customer reporting tables."""
def __init__(self, schema):
"""Establish the database connection. :param schema (str): The customer schema to associate with"""
super().__init__(schema)
hcs_cust = Customer.objects.filter(schema_name=sche... | the_stack_v2_python_sparse | koku/hcs/database/report_db_accessor.py | project-koku/koku | train | 225 |
93b2672e00d2ecace8046d2daca17449173d9003 | [
"super(PositionEmbedding, self).__init__()\nself.dim = dim\nself.freq = freq",
"device = inputs.device\nmax_length = inputs.shape[1]\nembedding_store = PositionEmbedding._embeddings.__dict__\ndevice_store = embedding_store.get(device, {})\nif not device_store or self.dim not in device_store or device_store[self.d... | <|body_start_0|>
super(PositionEmbedding, self).__init__()
self.dim = dim
self.freq = freq
<|end_body_0|>
<|body_start_1|>
device = inputs.device
max_length = inputs.shape[1]
embedding_store = PositionEmbedding._embeddings.__dict__
device_store = embedding_store.... | Produce position embeddings | PositionEmbedding | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionEmbedding:
"""Produce position embeddings"""
def __init__(self, dim, freq=10000.0):
"""Initialize the PositionEmbedding"""
<|body_0|>
def forward(self, inputs):
"""Implement the forward pass of the embedding"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_007138 | 3,716 | permissive | [
{
"docstring": "Initialize the PositionEmbedding",
"name": "__init__",
"signature": "def __init__(self, dim, freq=10000.0)"
},
{
"docstring": "Implement the forward pass of the embedding",
"name": "forward",
"signature": "def forward(self, inputs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009714 | Implement the Python class `PositionEmbedding` described below.
Class description:
Produce position embeddings
Method signatures and docstrings:
- def __init__(self, dim, freq=10000.0): Initialize the PositionEmbedding
- def forward(self, inputs): Implement the forward pass of the embedding | Implement the Python class `PositionEmbedding` described below.
Class description:
Produce position embeddings
Method signatures and docstrings:
- def __init__(self, dim, freq=10000.0): Initialize the PositionEmbedding
- def forward(self, inputs): Implement the forward pass of the embedding
<|skeleton|>
class Positi... | 0fa4adffa825af4a62b6e739b59c4125a7b6698e | <|skeleton|>
class PositionEmbedding:
"""Produce position embeddings"""
def __init__(self, dim, freq=10000.0):
"""Initialize the PositionEmbedding"""
<|body_0|>
def forward(self, inputs):
"""Implement the forward pass of the embedding"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PositionEmbedding:
"""Produce position embeddings"""
def __init__(self, dim, freq=10000.0):
"""Initialize the PositionEmbedding"""
super(PositionEmbedding, self).__init__()
self.dim = dim
self.freq = freq
def forward(self, inputs):
"""Implement the forward pas... | the_stack_v2_python_sparse | models/embeddings.py | fallcat/synst | train | 1 |
764d87469e90fc895cb74ad4131ac855430a9730 | [
"if clock is None:\n clock = time.clock\nself.current = clock()\nself.clock = clock",
"next = self.clock()\ndelta = next - self.current\nself.current = next\nreturn delta"
] | <|body_start_0|>
if clock is None:
clock = time.clock
self.current = clock()
self.clock = clock
<|end_body_0|>
<|body_start_1|>
next = self.clock()
delta = next - self.current
self.current = next
return delta
<|end_body_1|>
| A callable object that tracks the time elapsed between calls | Timer | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Timer:
"""A callable object that tracks the time elapsed between calls"""
def __init__(self, clock=None):
"""Create a timer based on the given clock function."""
<|body_0|>
def __call__(self):
"""Compute the time elapsed since the last call and reset the timer.""... | stack_v2_sparse_classes_36k_train_007139 | 1,584 | permissive | [
{
"docstring": "Create a timer based on the given clock function.",
"name": "__init__",
"signature": "def __init__(self, clock=None)"
},
{
"docstring": "Compute the time elapsed since the last call and reset the timer.",
"name": "__call__",
"signature": "def __call__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008591 | Implement the Python class `Timer` described below.
Class description:
A callable object that tracks the time elapsed between calls
Method signatures and docstrings:
- def __init__(self, clock=None): Create a timer based on the given clock function.
- def __call__(self): Compute the time elapsed since the last call a... | Implement the Python class `Timer` described below.
Class description:
A callable object that tracks the time elapsed between calls
Method signatures and docstrings:
- def __init__(self, clock=None): Create a timer based on the given clock function.
- def __call__(self): Compute the time elapsed since the last call a... | c7a147037b806058d18d9a200ffa4a14f3402d04 | <|skeleton|>
class Timer:
"""A callable object that tracks the time elapsed between calls"""
def __init__(self, clock=None):
"""Create a timer based on the given clock function."""
<|body_0|>
def __call__(self):
"""Compute the time elapsed since the last call and reset the timer.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Timer:
"""A callable object that tracks the time elapsed between calls"""
def __init__(self, clock=None):
"""Create a timer based on the given clock function."""
if clock is None:
clock = time.clock
self.current = clock()
self.clock = clock
def __call__(se... | the_stack_v2_python_sparse | util/time.py | gregr/old-and-miscellaneous | train | 2 |
a45bd42e3b29a6af758443782d1d7d411982823b | [
"super(EncoderBlock, self).__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(... | <|body_start_0|>
super(EncoderBlock, self).__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)
... | [summary] Args: tf ([type]): [description] | EncoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
... | stack_v2_sparse_classes_36k_train_007140 | 12,086 | no_license | [
{
"docstring": "[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "[summary] Args... | 2 | stack_v2_sparse_classes_30k_train_014199 | Implement the Python class `EncoderBlock` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (... | Implement the Python class `EncoderBlock` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class EncoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
super(Enc... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
143b033b69e4e546c8f1efdae4886d005000bc85 | [
"parser.add_argument('--network', metavar='NETWORK', required=True, help='Network in the consumer project peered with the service.')\nparser.add_argument('--service', metavar='SERVICE', default='servicenetworking.googleapis.com', help='Name of the service to list the peered DNS domains for.')\nparser.display_info.A... | <|body_start_0|>
parser.add_argument('--network', metavar='NETWORK', required=True, help='Network in the consumer project peered with the service.')
parser.add_argument('--service', metavar='SERVICE', default='servicenetworking.googleapis.com', help='Name of the service to list the peered DNS domains fo... | List the peered DNS domains for a private service connection. | List | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class List:
"""List the peered DNS domains for a private service connection."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positiona... | stack_v2_sparse_classes_36k_train_007141 | 3,130 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring"... | 2 | null | Implement the Python class `List` described below.
Class description:
List the peered DNS domains for a private service connection.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments ... | Implement the Python class `List` described below.
Class description:
List the peered DNS domains for a private service connection.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments ... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class List:
"""List the peered DNS domains for a private service connection."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positiona... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class List:
"""List the peered DNS domains for a private service connection."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments a... | the_stack_v2_python_sparse | lib/surface/services/peered_dns_domains/list.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
f8bb3e91da6541b197aad0efae6ec0c9126fb60f | [
"self.pr_state = pr_state\nself._default_min = 0.8 * self.pr_state.d_max\nself._default_max = 1.2 * self.pr_state.d_max",
"if dmin is None:\n dmin = self._default_min\nif dmax is None:\n dmax = self._default_max\nresults = Results()\nfor i in range(npts):\n d = dmin + i * (dmax - dmin) / (npts - 1.0)\n ... | <|body_start_0|>
self.pr_state = pr_state
self._default_min = 0.8 * self.pr_state.d_max
self._default_max = 1.2 * self.pr_state.d_max
<|end_body_0|>
<|body_start_1|>
if dmin is None:
dmin = self._default_min
if dmax is None:
dmax = self._default_max
... | The explorer class | DistExplorer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistExplorer:
"""The explorer class"""
def __init__(self, pr_state):
"""Initialization. :param pr_state: sas.sascalc.pr.invertor.Invertor object"""
<|body_0|>
def __call__(self, dmin=None, dmax=None, npts=10):
"""Compute the outputs as a function of D_max. :param... | stack_v2_sparse_classes_36k_train_007142 | 3,307 | permissive | [
{
"docstring": "Initialization. :param pr_state: sas.sascalc.pr.invertor.Invertor object",
"name": "__init__",
"signature": "def __init__(self, pr_state)"
},
{
"docstring": "Compute the outputs as a function of D_max. :param dmin: minimum value for D_max :param dmax: maximum value for D_max :par... | 2 | stack_v2_sparse_classes_30k_train_009348 | Implement the Python class `DistExplorer` described below.
Class description:
The explorer class
Method signatures and docstrings:
- def __init__(self, pr_state): Initialization. :param pr_state: sas.sascalc.pr.invertor.Invertor object
- def __call__(self, dmin=None, dmax=None, npts=10): Compute the outputs as a func... | Implement the Python class `DistExplorer` described below.
Class description:
The explorer class
Method signatures and docstrings:
- def __init__(self, pr_state): Initialization. :param pr_state: sas.sascalc.pr.invertor.Invertor object
- def __call__(self, dmin=None, dmax=None, npts=10): Compute the outputs as a func... | 55b1e9f6db58e33729f2a93b7dd1d8bf255b46f7 | <|skeleton|>
class DistExplorer:
"""The explorer class"""
def __init__(self, pr_state):
"""Initialization. :param pr_state: sas.sascalc.pr.invertor.Invertor object"""
<|body_0|>
def __call__(self, dmin=None, dmax=None, npts=10):
"""Compute the outputs as a function of D_max. :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DistExplorer:
"""The explorer class"""
def __init__(self, pr_state):
"""Initialization. :param pr_state: sas.sascalc.pr.invertor.Invertor object"""
self.pr_state = pr_state
self._default_min = 0.8 * self.pr_state.d_max
self._default_max = 1.2 * self.pr_state.d_max
def... | the_stack_v2_python_sparse | src/sas/sascalc/pr/distance_explorer.py | SasView/sasview | train | 48 |
bae78ab33726e914ded362670fb4a2f24c8da2f7 | [
"self.input = inputList\nself.nodes = dict()\nself.edges = dict()\nself.topOrder = []\nself.nodesCopy = dict()\nself.startNode = -1\nself.endNode = -1\nself.path = []",
"for line in range(0, len(self.input)):\n if line == 0:\n self.startNode = self.input[line]\n elif line == 1:\n self.endNode ... | <|body_start_0|>
self.input = inputList
self.nodes = dict()
self.edges = dict()
self.topOrder = []
self.nodesCopy = dict()
self.startNode = -1
self.endNode = -1
self.path = []
<|end_body_0|>
<|body_start_1|>
for line in range(0, len(self.input)):
... | A class to represent a directed acyclic graph (DAG). Contains the methods that construct the longest path and its score. Methods ------- parseInput() topOrdering() maxPredecessor() longestPath() outputPath() | DAG | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DAG:
"""A class to represent a directed acyclic graph (DAG). Contains the methods that construct the longest path and its score. Methods ------- parseInput() topOrdering() maxPredecessor() longestPath() outputPath()"""
def __init__(self, inputList):
"""Constructs all the necessary at... | stack_v2_sparse_classes_36k_train_007143 | 11,112 | no_license | [
{
"docstring": "Constructs all the necessary attributes for the DAG object. Parameters ---------- :param inputList: list of strings contains the start node, end node, and all edges with their weights Attributes ---------- input : list assigned to inputList nodes : dict contains all of the nodes in the DAG (keys... | 6 | stack_v2_sparse_classes_30k_train_006135 | Implement the Python class `DAG` described below.
Class description:
A class to represent a directed acyclic graph (DAG). Contains the methods that construct the longest path and its score. Methods ------- parseInput() topOrdering() maxPredecessor() longestPath() outputPath()
Method signatures and docstrings:
- def _... | Implement the Python class `DAG` described below.
Class description:
A class to represent a directed acyclic graph (DAG). Contains the methods that construct the longest path and its score. Methods ------- parseInput() topOrdering() maxPredecessor() longestPath() outputPath()
Method signatures and docstrings:
- def _... | 205e38dccf95d4be43ed542e46c2265689ca2cdf | <|skeleton|>
class DAG:
"""A class to represent a directed acyclic graph (DAG). Contains the methods that construct the longest path and its score. Methods ------- parseInput() topOrdering() maxPredecessor() longestPath() outputPath()"""
def __init__(self, inputList):
"""Constructs all the necessary at... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DAG:
"""A class to represent a directed acyclic graph (DAG). Contains the methods that construct the longest path and its score. Methods ------- parseInput() topOrdering() maxPredecessor() longestPath() outputPath()"""
def __init__(self, inputList):
"""Constructs all the necessary attributes for ... | the_stack_v2_python_sparse | problem18.py | tianap/bme-205 | train | 0 |
4db84f8344e83c343e90cb02baccf9d94e51e45c | [
"try:\n import base64\nexcept Exception:\n self.m_textCtrl1.SetValue(\"ERROR: Could not load module 'base64'\")\n return\n_ysstr = self.m_textCtrl1.GetValue()\nbyte_ysstr = _ysstr.encode('utf-8')\n_jgstr = None\ntry:\n _jgstr = base64.b64encode(byte_ysstr)\nexcept Exception:\n self.m_textCtrl2.SetVal... | <|body_start_0|>
try:
import base64
except Exception:
self.m_textCtrl1.SetValue("ERROR: Could not load module 'base64'")
return
_ysstr = self.m_textCtrl1.GetValue()
byte_ysstr = _ysstr.encode('utf-8')
_jgstr = None
try:
_jgs... | 继承wxFormBuilder的框架,实现交互函数即可 | Base64_Decode_Demo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base64_Decode_Demo:
"""继承wxFormBuilder的框架,实现交互函数即可"""
def Encode_Str(self, event):
"""点击字符串加密按钮"""
<|body_0|>
def Decode_Str(self, event):
"""base64 解密"""
<|body_1|>
def Encode_File(self, event):
"""读取文件并加密"""
<|body_2|>
def Deco... | stack_v2_sparse_classes_36k_train_007144 | 2,894 | no_license | [
{
"docstring": "点击字符串加密按钮",
"name": "Encode_Str",
"signature": "def Encode_Str(self, event)"
},
{
"docstring": "base64 解密",
"name": "Decode_Str",
"signature": "def Decode_Str(self, event)"
},
{
"docstring": "读取文件并加密",
"name": "Encode_File",
"signature": "def Encode_File(s... | 4 | null | Implement the Python class `Base64_Decode_Demo` described below.
Class description:
继承wxFormBuilder的框架,实现交互函数即可
Method signatures and docstrings:
- def Encode_Str(self, event): 点击字符串加密按钮
- def Decode_Str(self, event): base64 解密
- def Encode_File(self, event): 读取文件并加密
- def Decode_File(self, event): 解密文件 | Implement the Python class `Base64_Decode_Demo` described below.
Class description:
继承wxFormBuilder的框架,实现交互函数即可
Method signatures and docstrings:
- def Encode_Str(self, event): 点击字符串加密按钮
- def Decode_Str(self, event): base64 解密
- def Encode_File(self, event): 读取文件并加密
- def Decode_File(self, event): 解密文件
<|skeleton|>... | 182ed5ed9c9838c1be694d058ba6c3c52a761feb | <|skeleton|>
class Base64_Decode_Demo:
"""继承wxFormBuilder的框架,实现交互函数即可"""
def Encode_Str(self, event):
"""点击字符串加密按钮"""
<|body_0|>
def Decode_Str(self, event):
"""base64 解密"""
<|body_1|>
def Encode_File(self, event):
"""读取文件并加密"""
<|body_2|>
def Deco... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base64_Decode_Demo:
"""继承wxFormBuilder的框架,实现交互函数即可"""
def Encode_Str(self, event):
"""点击字符串加密按钮"""
try:
import base64
except Exception:
self.m_textCtrl1.SetValue("ERROR: Could not load module 'base64'")
return
_ysstr = self.m_textCtrl1.G... | the_stack_v2_python_sparse | Devetool/test_Base64Decode.py | cjdxsxd/pythonProject | train | 0 |
1534b481be05ed944634dffa13463d00a8e5970a | [
"re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])\nresult = re\nAssertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])",
"re = MonthTicketBill(userLogin).openMonthTicketBill(send_data['c... | <|body_start_0|>
re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])
result = re
Assertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])
<|end_body_0|>
<|body_start_1|>
... | 智泊云自然月票创建,开通,续费。车辆进出是月票(在进出场记录中查看到VIP类型为售卖的月票类型) | TestNaturalMonthTicketConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNaturalMonthTicketConfig:
"""智泊云自然月票创建,开通,续费。车辆进出是月票(在进出场记录中查看到VIP类型为售卖的月票类型)"""
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自然月月票类型"""
<|body_0|>
def test_openMonthTicketBill(self, userLogin, send_data, expect):
"""用自然月月票类型开通月票... | stack_v2_sparse_classes_36k_train_007145 | 3,265 | no_license | [
{
"docstring": "创建自然月月票类型",
"name": "test_createMonthTicketConfig",
"signature": "def test_createMonthTicketConfig(self, userLogin, send_data, expect)"
},
{
"docstring": "用自然月月票类型开通月票",
"name": "test_openMonthTicketBill",
"signature": "def test_openMonthTicketBill(self, userLogin, send_d... | 6 | null | Implement the Python class `TestNaturalMonthTicketConfig` described below.
Class description:
智泊云自然月票创建,开通,续费。车辆进出是月票(在进出场记录中查看到VIP类型为售卖的月票类型)
Method signatures and docstrings:
- def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自然月月票类型
- def test_openMonthTicketBill(self, userLogin, send_data, ... | Implement the Python class `TestNaturalMonthTicketConfig` described below.
Class description:
智泊云自然月票创建,开通,续费。车辆进出是月票(在进出场记录中查看到VIP类型为售卖的月票类型)
Method signatures and docstrings:
- def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自然月月票类型
- def test_openMonthTicketBill(self, userLogin, send_data, ... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestNaturalMonthTicketConfig:
"""智泊云自然月票创建,开通,续费。车辆进出是月票(在进出场记录中查看到VIP类型为售卖的月票类型)"""
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自然月月票类型"""
<|body_0|>
def test_openMonthTicketBill(self, userLogin, send_data, expect):
"""用自然月月票类型开通月票... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestNaturalMonthTicketConfig:
"""智泊云自然月票创建,开通,续费。车辆进出是月票(在进出场记录中查看到VIP类型为售卖的月票类型)"""
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自然月月票类型"""
re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_dat... | the_stack_v2_python_sparse | test_suite/parkingManage/monthTicket/test_naturalMonthTicketConfigRenew.py | oyebino/pomp_api | train | 1 |
46b2195d1cc5a150a34b6d467f9948c0b2ab5d57 | [
"n = len(friends)\nqueue = deque([id])\nvisited = [False] * n\nvisited[id] = True\nc = Counter()\nk = 0\nwhile queue:\n q = deque()\n while queue:\n cur = queue.popleft()\n for i in friends[cur]:\n if not visited[i]:\n visited[i] = True\n q.append(i)\n ... | <|body_start_0|>
n = len(friends)
queue = deque([id])
visited = [False] * n
visited[id] = True
c = Counter()
k = 0
while queue:
q = deque()
while queue:
cur = queue.popleft()
for i in friends[cur]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def watchedVideosByFriends(self, watchedVideos, friends, id, level):
""":type watchedVideos: List[List[str]] :type friends: List[List[int]] :type id: int :type level: int :rtype: List[str]"""
<|body_0|>
def watchedVideosByFriendsFast(self, watchedVideos, friends, i... | stack_v2_sparse_classes_36k_train_007146 | 3,535 | no_license | [
{
"docstring": ":type watchedVideos: List[List[str]] :type friends: List[List[int]] :type id: int :type level: int :rtype: List[str]",
"name": "watchedVideosByFriends",
"signature": "def watchedVideosByFriends(self, watchedVideos, friends, id, level)"
},
{
"docstring": ":type watchedVideos: List... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def watchedVideosByFriends(self, watchedVideos, friends, id, level): :type watchedVideos: List[List[str]] :type friends: List[List[int]] :type id: int :type level: int :rtype: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def watchedVideosByFriends(self, watchedVideos, friends, id, level): :type watchedVideos: List[List[str]] :type friends: List[List[int]] :type id: int :type level: int :rtype: Li... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def watchedVideosByFriends(self, watchedVideos, friends, id, level):
""":type watchedVideos: List[List[str]] :type friends: List[List[int]] :type id: int :type level: int :rtype: List[str]"""
<|body_0|>
def watchedVideosByFriendsFast(self, watchedVideos, friends, i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def watchedVideosByFriends(self, watchedVideos, friends, id, level):
""":type watchedVideos: List[List[str]] :type friends: List[List[int]] :type id: int :type level: int :rtype: List[str]"""
n = len(friends)
queue = deque([id])
visited = [False] * n
visited[i... | the_stack_v2_python_sparse | G/GetWatchedVideosbyYourFriends.py | bssrdf/pyleet | train | 2 | |
999b54a39b4e7fa0d7599d40bf997d8e59dde5ef | [
"for v in nums:\n index = abs(v) - 1\n if nums[index] > 0:\n nums[index] *= -1\n else:\n return nums[index]\nreturn None",
"tortoise = hare = nums[0]\nwhile True:\n '\\n here we are detecting cycle\\n '\n tortoise = nums[tortoise]\n hare = nums[nums[hare]]\n ... | <|body_start_0|>
for v in nums:
index = abs(v) - 1
if nums[index] > 0:
nums[index] *= -1
else:
return nums[index]
return None
<|end_body_0|>
<|body_start_1|>
tortoise = hare = nums[0]
while True:
'\n ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate_approach1(self, nums: List[int]) -> int:
"""Cycle detection since the values of the array will essntially be within the index range (0..n) we can mark the visited element and once we visit it again we found the duplicate"""
<|body_0|>
def findDupl... | stack_v2_sparse_classes_36k_train_007147 | 2,114 | no_license | [
{
"docstring": "Cycle detection since the values of the array will essntially be within the index range (0..n) we can mark the visited element and once we visit it again we found the duplicate",
"name": "findDuplicate_approach1",
"signature": "def findDuplicate_approach1(self, nums: List[int]) -> int"
... | 2 | stack_v2_sparse_classes_30k_val_000026 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate_approach1(self, nums: List[int]) -> int: Cycle detection since the values of the array will essntially be within the index range (0..n) we can mark the visited ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate_approach1(self, nums: List[int]) -> int: Cycle detection since the values of the array will essntially be within the index range (0..n) we can mark the visited ... | 59f70dc4466e15df591ba285317e4a1fe808ed60 | <|skeleton|>
class Solution:
def findDuplicate_approach1(self, nums: List[int]) -> int:
"""Cycle detection since the values of the array will essntially be within the index range (0..n) we can mark the visited element and once we visit it again we found the duplicate"""
<|body_0|>
def findDupl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate_approach1(self, nums: List[int]) -> int:
"""Cycle detection since the values of the array will essntially be within the index range (0..n) we can mark the visited element and once we visit it again we found the duplicate"""
for v in nums:
index = abs(v) ... | the_stack_v2_python_sparse | leet/facebook/strings_arrays/find_duplicate_number.py | arsamigullin/problem_solving_python | train | 0 | |
4421c886cdc9ae97fe333e9f8637bc60551d01fa | [
"self.shooter_platform = shooter_platfrom\nself.feeder = feeder\nself.driver = driver\nself.state = None\nself.min_calls = wpilib.Timer\nself.manual_feed = False",
"self.feeder.set_auto_mode(True)\nif self.shooter_platform.is_ready() and self.feeder.has_frisbee():\n self.feeder.feed_auto()\nelif self.shooter_p... | <|body_start_0|>
self.shooter_platform = shooter_platfrom
self.feeder = feeder
self.driver = driver
self.state = None
self.min_calls = wpilib.Timer
self.manual_feed = False
<|end_body_0|>
<|body_start_1|>
self.feeder.set_auto_mode(True)
if self.shooter_pl... | shooter class which controls the interactions of the feeder and the shooter_platform | Shooter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Shooter:
"""shooter class which controls the interactions of the feeder and the shooter_platform"""
def __init__(self, shooter_platfrom, feeder, driver=None):
"""Initializes shooter class param:shooter_platform - a shooter_platform object, all setup param:feeder - a feeder object all... | stack_v2_sparse_classes_36k_train_007148 | 1,673 | no_license | [
{
"docstring": "Initializes shooter class param:shooter_platform - a shooter_platform object, all setup param:feeder - a feeder object all setup",
"name": "__init__",
"signature": "def __init__(self, shooter_platfrom, feeder, driver=None)"
},
{
"docstring": "if motor is ready and there are frisb... | 2 | stack_v2_sparse_classes_30k_train_005114 | Implement the Python class `Shooter` described below.
Class description:
shooter class which controls the interactions of the feeder and the shooter_platform
Method signatures and docstrings:
- def __init__(self, shooter_platfrom, feeder, driver=None): Initializes shooter class param:shooter_platform - a shooter_plat... | Implement the Python class `Shooter` described below.
Class description:
shooter class which controls the interactions of the feeder and the shooter_platform
Method signatures and docstrings:
- def __init__(self, shooter_platfrom, feeder, driver=None): Initializes shooter class param:shooter_platform - a shooter_plat... | 43d9572b62444ef1667d7f66c4b0043be49590d5 | <|skeleton|>
class Shooter:
"""shooter class which controls the interactions of the feeder and the shooter_platform"""
def __init__(self, shooter_platfrom, feeder, driver=None):
"""Initializes shooter class param:shooter_platform - a shooter_platform object, all setup param:feeder - a feeder object all... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Shooter:
"""shooter class which controls the interactions of the feeder and the shooter_platform"""
def __init__(self, shooter_platfrom, feeder, driver=None):
"""Initializes shooter class param:shooter_platform - a shooter_platform object, all setup param:feeder - a feeder object all setup"""
... | the_stack_v2_python_sparse | robot/source/systems/shooter.py | frc2423/2013 | train | 0 |
2e5d51a677b7e35781c8214c4b9983a6d62ca5a6 | [
"data = self.get_json()\nwith self.Session() as session:\n stmt = DefaultObservationPlanRequest.select(session.user_or_token).where(DefaultObservationPlanRequest.id == data['default_observationplan_request_id'])\n default_observation_plan = session.scalars(stmt).first()\n if default_observation_plan is Non... | <|body_start_0|>
data = self.get_json()
with self.Session() as session:
stmt = DefaultObservationPlanRequest.select(session.user_or_token).where(DefaultObservationPlanRequest.id == data['default_observationplan_request_id'])
default_observation_plan = session.scalars(stmt).first(... | DefaultSurveyEfficiencyRequestHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultSurveyEfficiencyRequestHandler:
def post(self):
"""--- description: Create default survey efficiency requests. tags: - default_survey_efficiency requestBody: content: application/json: schema: DefaultSurveyEfficiencyPost responses: 200: content: application/json: schema: allOf: - ... | stack_v2_sparse_classes_36k_train_007149 | 12,003 | permissive | [
{
"docstring": "--- description: Create default survey efficiency requests. tags: - default_survey_efficiency requestBody: content: application/json: schema: DefaultSurveyEfficiencyPost responses: 200: content: application/json: schema: allOf: - $ref: '#/components/schemas/Success' - type: object properties: da... | 3 | null | Implement the Python class `DefaultSurveyEfficiencyRequestHandler` described below.
Class description:
Implement the DefaultSurveyEfficiencyRequestHandler class.
Method signatures and docstrings:
- def post(self): --- description: Create default survey efficiency requests. tags: - default_survey_efficiency requestBod... | Implement the Python class `DefaultSurveyEfficiencyRequestHandler` described below.
Class description:
Implement the DefaultSurveyEfficiencyRequestHandler class.
Method signatures and docstrings:
- def post(self): --- description: Create default survey efficiency requests. tags: - default_survey_efficiency requestBod... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class DefaultSurveyEfficiencyRequestHandler:
def post(self):
"""--- description: Create default survey efficiency requests. tags: - default_survey_efficiency requestBody: content: application/json: schema: DefaultSurveyEfficiencyPost responses: 200: content: application/json: schema: allOf: - ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefaultSurveyEfficiencyRequestHandler:
def post(self):
"""--- description: Create default survey efficiency requests. tags: - default_survey_efficiency requestBody: content: application/json: schema: DefaultSurveyEfficiencyPost responses: 200: content: application/json: schema: allOf: - $ref: '#/compo... | the_stack_v2_python_sparse | skyportal/handlers/api/survey_efficiency.py | skyportal/skyportal | train | 80 | |
9fb2c1b5fa8cc6e1a0b8314c7c9794b617b3698a | [
"super().__init__(xsize, ysize)\nif self.xsize % 2 == 0 or self.ysize % 2 == 0:\n raise ValueError('xsize and ysize must be odd')\nself.grid = [['@'] * self.xsize for _ in range(self.ysize)]\nself.generate()\nself.start = (1, 1)\nself.goal = (self.xsize - 2, self.ysize - 2)\nassert self.is_free(*self.start)\nass... | <|body_start_0|>
super().__init__(xsize, ysize)
if self.xsize % 2 == 0 or self.ysize % 2 == 0:
raise ValueError('xsize and ysize must be odd')
self.grid = [['@'] * self.xsize for _ in range(self.ysize)]
self.generate()
self.start = (1, 1)
self.goal = (self.xsi... | Randomly generated maze using Prim's algorithm: https://en.wikipedia.org/wiki/Prim%27s_algorithm (Known for producing mazes with lots of short dead ends, only moderately challenging for humans.) | PrimRandomMaze | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrimRandomMaze:
"""Randomly generated maze using Prim's algorithm: https://en.wikipedia.org/wiki/Prim%27s_algorithm (Known for producing mazes with lots of short dead ends, only moderately challenging for humans.)"""
def __init__(self, xsize, ysize):
"""Create a new random maze of si... | stack_v2_sparse_classes_36k_train_007150 | 8,089 | no_license | [
{
"docstring": "Create a new random maze of size (xsize,ysize). Both dimensions must be odd.",
"name": "__init__",
"signature": "def __init__(self, xsize, ysize)"
},
{
"docstring": "Make the maze using Prim's algorithm",
"name": "generate",
"signature": "def generate(self)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_008330 | Implement the Python class `PrimRandomMaze` described below.
Class description:
Randomly generated maze using Prim's algorithm: https://en.wikipedia.org/wiki/Prim%27s_algorithm (Known for producing mazes with lots of short dead ends, only moderately challenging for humans.)
Method signatures and docstrings:
- def __i... | Implement the Python class `PrimRandomMaze` described below.
Class description:
Randomly generated maze using Prim's algorithm: https://en.wikipedia.org/wiki/Prim%27s_algorithm (Known for producing mazes with lots of short dead ends, only moderately challenging for humans.)
Method signatures and docstrings:
- def __i... | 6886dab8fe2a62d0bf2668d783a8fdc35b62d6de | <|skeleton|>
class PrimRandomMaze:
"""Randomly generated maze using Prim's algorithm: https://en.wikipedia.org/wiki/Prim%27s_algorithm (Known for producing mazes with lots of short dead ends, only moderately challenging for humans.)"""
def __init__(self, xsize, ysize):
"""Create a new random maze of si... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrimRandomMaze:
"""Randomly generated maze using Prim's algorithm: https://en.wikipedia.org/wiki/Prim%27s_algorithm (Known for producing mazes with lots of short dead ends, only moderately challenging for humans.)"""
def __init__(self, xsize, ysize):
"""Create a new random maze of size (xsize,ysi... | the_stack_v2_python_sparse | samplecode/recursion/maze.py | daviddumas/mcs275spring2021 | train | 0 |
663579c7eceb0130e977d35681f5fb4b4bccf0b1 | [
"if model._meta.app_label == 'admin':\n return 'default'\nelif model._meta.app_label == 'auth':\n return 'voter_auth'\nelif model._meta.app_label == 'reg1':\n return 'region1'\nelif model._meta.app_label == 'reg2':\n return 'region2'\nelif model._meta.app_label == 'people':\n return 'people'\nelif mo... | <|body_start_0|>
if model._meta.app_label == 'admin':
return 'default'
elif model._meta.app_label == 'auth':
return 'voter_auth'
elif model._meta.app_label == 'reg1':
return 'region1'
elif model._meta.app_label == 'reg2':
return 'region2'
... | A router to control all database operations on models in the auth application. | dbRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dbRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read auth models go to auth_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write auth mo... | stack_v2_sparse_classes_36k_train_007151 | 2,597 | no_license | [
{
"docstring": "Attempts to read auth models go to auth_db.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write auth models go to auth_db.",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)"
},
... | 4 | null | Implement the Python class `dbRouter` described below.
Class description:
A router to control all database operations on models in the auth application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read auth models go to auth_db.
- def db_for_write(self, model, **hints): Atte... | Implement the Python class `dbRouter` described below.
Class description:
A router to control all database operations on models in the auth application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read auth models go to auth_db.
- def db_for_write(self, model, **hints): Atte... | 5d115e66b36c0a1cf5fdeca271c22ffba17a8412 | <|skeleton|>
class dbRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read auth models go to auth_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write auth mo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class dbRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read auth models go to auth_db."""
if model._meta.app_label == 'admin':
return 'default'
elif model._meta.app_label == '... | the_stack_v2_python_sparse | voting_system/routers.py | IoanaBob/voting-system | train | 3 |
4e4d351f64702f06e7c165d910a518098a47c400 | [
"if self._async_current_entries():\n return self.async_abort(reason='single_instance_allowed')\nif user_input is None:\n return self.async_show_form(step_id='user')\ntry:\n webhook_id, webhook_url, cloudhook = await self._get_webhook_id()\nexcept cloud.CloudNotConnected:\n return self.async_abort(reason... | <|body_start_0|>
if self._async_current_entries():
return self.async_abort(reason='single_instance_allowed')
if user_input is None:
return self.async_show_form(step_id='user')
try:
webhook_id, webhook_url, cloudhook = await self._get_webhook_id()
excep... | Set up OwnTracks. | OwnTracksFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OwnTracksFlow:
"""Set up OwnTracks."""
async def async_step_user(self, user_input=None):
"""Handle a user initiated set up flow to create OwnTracks webhook."""
<|body_0|>
async def _get_webhook_id(self):
"""Generate webhook ID."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_007152 | 2,396 | permissive | [
{
"docstring": "Handle a user initiated set up flow to create OwnTracks webhook.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_input=None)"
},
{
"docstring": "Generate webhook ID.",
"name": "_get_webhook_id",
"signature": "async def _get_webhook_id(self)... | 2 | null | Implement the Python class `OwnTracksFlow` described below.
Class description:
Set up OwnTracks.
Method signatures and docstrings:
- async def async_step_user(self, user_input=None): Handle a user initiated set up flow to create OwnTracks webhook.
- async def _get_webhook_id(self): Generate webhook ID. | Implement the Python class `OwnTracksFlow` described below.
Class description:
Set up OwnTracks.
Method signatures and docstrings:
- async def async_step_user(self, user_input=None): Handle a user initiated set up flow to create OwnTracks webhook.
- async def _get_webhook_id(self): Generate webhook ID.
<|skeleton|>
... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OwnTracksFlow:
"""Set up OwnTracks."""
async def async_step_user(self, user_input=None):
"""Handle a user initiated set up flow to create OwnTracks webhook."""
<|body_0|>
async def _get_webhook_id(self):
"""Generate webhook ID."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OwnTracksFlow:
"""Set up OwnTracks."""
async def async_step_user(self, user_input=None):
"""Handle a user initiated set up flow to create OwnTracks webhook."""
if self._async_current_entries():
return self.async_abort(reason='single_instance_allowed')
if user_input is ... | the_stack_v2_python_sparse | homeassistant/components/owntracks/config_flow.py | home-assistant/core | train | 35,501 |
8ccfb420dba0b5dc26683daba4ecfd299ee4fce0 | [
"self.pi = pi\nself.n_states = n_states\nself.n_actions = n_actions\nself.gamma = gamma\nself.alpha = 0.3\nself.p = p\nself.r = r\nself.n_iterations = 100",
"q = np.random.rand(self.n_states, self.n_actions)\nfor _ in range(100):\n v = np.zeros(self.n_states)\n for state in range(self.n_states):\n fo... | <|body_start_0|>
self.pi = pi
self.n_states = n_states
self.n_actions = n_actions
self.gamma = gamma
self.alpha = 0.3
self.p = p
self.r = r
self.n_iterations = 100
<|end_body_0|>
<|body_start_1|>
q = np.random.rand(self.n_states, self.n_actions)
... | SPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SPI:
def __init__(self, pi, n_states, n_actions, gamma, p, r):
"""pi = S*A p = A*S*S r = A*S"""
<|body_0|>
def update(self):
"""Soft Policy iteration"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pi = pi
self.n_states = n_states
... | stack_v2_sparse_classes_36k_train_007153 | 1,406 | permissive | [
{
"docstring": "pi = S*A p = A*S*S r = A*S",
"name": "__init__",
"signature": "def __init__(self, pi, n_states, n_actions, gamma, p, r)"
},
{
"docstring": "Soft Policy iteration",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020534 | Implement the Python class `SPI` described below.
Class description:
Implement the SPI class.
Method signatures and docstrings:
- def __init__(self, pi, n_states, n_actions, gamma, p, r): pi = S*A p = A*S*S r = A*S
- def update(self): Soft Policy iteration | Implement the Python class `SPI` described below.
Class description:
Implement the SPI class.
Method signatures and docstrings:
- def __init__(self, pi, n_states, n_actions, gamma, p, r): pi = S*A p = A*S*S r = A*S
- def update(self): Soft Policy iteration
<|skeleton|>
class SPI:
def __init__(self, pi, n_states... | e862324816c57dd5d07691ee8583259a6a62116c | <|skeleton|>
class SPI:
def __init__(self, pi, n_states, n_actions, gamma, p, r):
"""pi = S*A p = A*S*S r = A*S"""
<|body_0|>
def update(self):
"""Soft Policy iteration"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SPI:
def __init__(self, pi, n_states, n_actions, gamma, p, r):
"""pi = S*A p = A*S*S r = A*S"""
self.pi = pi
self.n_states = n_states
self.n_actions = n_actions
self.gamma = gamma
self.alpha = 0.3
self.p = p
self.r = r
self.n_iterations =... | the_stack_v2_python_sparse | gridworld/algorithms/SPI.py | Silviatulli/LOGEL | train | 0 | |
2328ea021016837fb5391277e2d0e8bc9a646ad8 | [
"if len(lists) == 0:\n return []\nif len(lists) == 1:\n return lists[0]\nmerge_node = ListNode(0)\nresult = merge_node\nnode_list = []\nfor node in lists:\n while node:\n node_list.append(node.val)\n node = node.next\nnode_list.sort()\nwhile node_list:\n merge_node.next = ListNode(node_lis... | <|body_start_0|>
if len(lists) == 0:
return []
if len(lists) == 1:
return lists[0]
merge_node = ListNode(0)
result = merge_node
node_list = []
for node in lists:
while node:
node_list.append(node.val)
nod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists: [ListNode]) -> ListNode:
"""将所有元素取出来放在列表中排序再逐个添加至新链表 :param lists: :return:"""
<|body_0|>
def showNode(self, node: ListNode) -> list:
"""show all value of ListNode :param node: :return:"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_007154 | 3,032 | no_license | [
{
"docstring": "将所有元素取出来放在列表中排序再逐个添加至新链表 :param lists: :return:",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists: [ListNode]) -> ListNode"
},
{
"docstring": "show all value of ListNode :param node: :return:",
"name": "showNode",
"signature": "def showNode(self, node: Li... | 2 | stack_v2_sparse_classes_30k_train_015429 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists: [ListNode]) -> ListNode: 将所有元素取出来放在列表中排序再逐个添加至新链表 :param lists: :return:
- def showNode(self, node: ListNode) -> list: show all value of ListNode :pa... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists: [ListNode]) -> ListNode: 将所有元素取出来放在列表中排序再逐个添加至新链表 :param lists: :return:
- def showNode(self, node: ListNode) -> list: show all value of ListNode :pa... | fa45cd44c3d4e7b0205833efcdc708d1638cbbe4 | <|skeleton|>
class Solution:
def mergeKLists(self, lists: [ListNode]) -> ListNode:
"""将所有元素取出来放在列表中排序再逐个添加至新链表 :param lists: :return:"""
<|body_0|>
def showNode(self, node: ListNode) -> list:
"""show all value of ListNode :param node: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists: [ListNode]) -> ListNode:
"""将所有元素取出来放在列表中排序再逐个添加至新链表 :param lists: :return:"""
if len(lists) == 0:
return []
if len(lists) == 1:
return lists[0]
merge_node = ListNode(0)
result = merge_node
node_list... | the_stack_v2_python_sparse | Python/t23.py | g-lyc/LeetCode | train | 15 | |
a639412340c7c976da22e0ae2f1cb875ddf94df8 | [
"r = Round.query.get(round_id)\nif r is not None:\n return r.move_couple_data(dance_id)\nabort(404, 'Unknown round_id')",
"r = Round.query.get(round_id)\nif r is not None:\n from_heat = Heat.query.filter(Heat.heat_id == api.payload['from_id']).first()\n to_heat = Heat.query.filter(Heat.heat_id == api.pay... | <|body_start_0|>
r = Round.query.get(round_id)
if r is not None:
return r.move_couple_data(dance_id)
abort(404, 'Unknown round_id')
<|end_body_0|>
<|body_start_1|>
r = Round.query.get(round_id)
if r is not None:
from_heat = Heat.query.filter(Heat.heat_id ... | RoundAPIFloorManagementDanceMove | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoundAPIFloorManagementDanceMove:
def get(self, round_id, dance_id):
"""Get floor management data for a specific dance"""
<|body_0|>
def patch(self, round_id, dance_id):
"""Moves a couple between heats"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_007155 | 25,303 | no_license | [
{
"docstring": "Get floor management data for a specific dance",
"name": "get",
"signature": "def get(self, round_id, dance_id)"
},
{
"docstring": "Moves a couple between heats",
"name": "patch",
"signature": "def patch(self, round_id, dance_id)"
}
] | 2 | null | Implement the Python class `RoundAPIFloorManagementDanceMove` described below.
Class description:
Implement the RoundAPIFloorManagementDanceMove class.
Method signatures and docstrings:
- def get(self, round_id, dance_id): Get floor management data for a specific dance
- def patch(self, round_id, dance_id): Moves a c... | Implement the Python class `RoundAPIFloorManagementDanceMove` described below.
Class description:
Implement the RoundAPIFloorManagementDanceMove class.
Method signatures and docstrings:
- def get(self, round_id, dance_id): Get floor management data for a specific dance
- def patch(self, round_id, dance_id): Moves a c... | 079b109fd13683a31d1d632faa5ab72cf0e78ddf | <|skeleton|>
class RoundAPIFloorManagementDanceMove:
def get(self, round_id, dance_id):
"""Get floor management data for a specific dance"""
<|body_0|>
def patch(self, round_id, dance_id):
"""Moves a couple between heats"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoundAPIFloorManagementDanceMove:
def get(self, round_id, dance_id):
"""Get floor management data for a specific dance"""
r = Round.query.get(round_id)
if r is not None:
return r.move_couple_data(dance_id)
abort(404, 'Unknown round_id')
def patch(self, round_id... | the_stack_v2_python_sparse | backend/apis/round/apis.py | AlenAlic/DANCE | train | 0 | |
c779b3b2fe1aefbd73d28436290dc56c38c6cfd3 | [
"if not nums:\n return 0\nif len(nums) == 1:\n return nums[0]\nreturn max(self.helper(nums[:-1]), self.helper(nums[1:]))",
"if not nums:\n return 0\nif len(nums) == 1:\n return nums[0]\ndp = [0] * len(nums)\ndp[0] = nums[0]\ndp[1] = max(nums[0], nums[1])\nfor i in range(2, len(nums)):\n dp[i] = max... | <|body_start_0|>
if not nums:
return 0
if len(nums) == 1:
return nums[0]
return max(self.helper(nums[:-1]), self.helper(nums[1:]))
<|end_body_0|>
<|body_start_1|>
if not nums:
return 0
if len(nums) == 1:
return nums[0]
dp =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def helper(self, nums):
"""套用198题解题思路 :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
if le... | stack_v2_sparse_classes_36k_train_007156 | 909 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": "套用198题解题思路 :type nums: List[int] :rtype: int",
"name": "helper",
"signature": "def helper(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000189 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def helper(self, nums): 套用198题解题思路 :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def helper(self, nums): 套用198题解题思路 :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, num... | 6ae85bf79c5a21735e3c245c0c256f29c1c60926 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def helper(self, nums):
"""套用198题解题思路 :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
if len(nums) == 1:
return nums[0]
return max(self.helper(nums[:-1]), self.helper(nums[1:]))
def helper(self, nums):
"""套用198题解题思路 :type nums: List[i... | the_stack_v2_python_sparse | algorithms/201-300/213.house-robber-ii.py | huilizhou/Leetcode-pyhton | train | 8 | |
53108f54cb2a9967363dede539dfd5bd736d7542 | [
"seen = set()\nfor n in nums:\n if n in seen:\n return n\n else:\n seen.add(n)",
"slow = nums[0]\nfast = nums[nums[0]]\nwhile slow != fast:\n slow = nums[slow]\n fast = nums[nums[fast]]\nfast = 0\nwhile slow != fast:\n slow = nums[slow]\n fast = nums[fast]\nreturn slow"
] | <|body_start_0|>
seen = set()
for n in nums:
if n in seen:
return n
else:
seen.add(n)
<|end_body_0|>
<|body_start_1|>
slow = nums[0]
fast = nums[nums[0]]
while slow != fast:
slow = nums[slow]
fast = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""allowing extra space"""
<|body_0|>
def findDuplicate(self, nums: List[int]) -> int:
"""constant space, non mutable array, only works with positive, Floyd's algorithm"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_007157 | 700 | no_license | [
{
"docstring": "allowing extra space",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums: List[int]) -> int"
},
{
"docstring": "constant space, non mutable array, only works with positive, Floyd's algorithm",
"name": "findDuplicate",
"signature": "def findDuplicate(self... | 2 | stack_v2_sparse_classes_30k_train_015550 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums: List[int]) -> int: allowing extra space
- def findDuplicate(self, nums: List[int]) -> int: constant space, non mutable array, only works with positi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums: List[int]) -> int: allowing extra space
- def findDuplicate(self, nums: List[int]) -> int: constant space, non mutable array, only works with positi... | e50dc0642f087f37ab3234390be3d8a0ed48fe62 | <|skeleton|>
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""allowing extra space"""
<|body_0|>
def findDuplicate(self, nums: List[int]) -> int:
"""constant space, non mutable array, only works with positive, Floyd's algorithm"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""allowing extra space"""
seen = set()
for n in nums:
if n in seen:
return n
else:
seen.add(n)
def findDuplicate(self, nums: List[int]) -> int:
"""constant s... | the_stack_v2_python_sparse | Leetcode/287. Find the Diplicate Element.py | brlala/Educative-Grokking-Coding-Exercise | train | 3 | |
7483eb54a882871c5430e3e7c5e6a15daa08af82 | [
"score = sorted(nums, reverse=True)\nrank = ['Gold Medal', 'Silver Medal', 'Bronze Medal'] + map(str, range(4, len(nums) + 1))\nreturn map(dict(zip(score, rank)).get, nums)",
"c = [-1] * (max(nums) + 1)\nn = len(nums)\nfor i in xrange(n):\n x = nums[i]\n c[x] = i\nrank = n\nfor each in c:\n if each > -1:... | <|body_start_0|>
score = sorted(nums, reverse=True)
rank = ['Gold Medal', 'Silver Medal', 'Bronze Medal'] + map(str, range(4, len(nums) + 1))
return map(dict(zip(score, rank)).get, nums)
<|end_body_0|>
<|body_start_1|>
c = [-1] * (max(nums) + 1)
n = len(nums)
for i in xr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findRelativeRanks(self, nums):
""":type nums: List[int] :rtype: List[str]"""
<|body_0|>
def findRelativeRanks(self, nums):
""":type nums: List[int] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
score = sorted(nums, ... | stack_v2_sparse_classes_36k_train_007158 | 1,566 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[str]",
"name": "findRelativeRanks",
"signature": "def findRelativeRanks(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[str]",
"name": "findRelativeRanks",
"signature": "def findRelativeRanks(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRelativeRanks(self, nums): :type nums: List[int] :rtype: List[str]
- def findRelativeRanks(self, nums): :type nums: List[int] :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRelativeRanks(self, nums): :type nums: List[int] :rtype: List[str]
- def findRelativeRanks(self, nums): :type nums: List[int] :rtype: List[str]
<|skeleton|>
class Soluti... | 8bb17099be02d997d554519be360ef4aa1c028e3 | <|skeleton|>
class Solution:
def findRelativeRanks(self, nums):
""":type nums: List[int] :rtype: List[str]"""
<|body_0|>
def findRelativeRanks(self, nums):
""":type nums: List[int] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findRelativeRanks(self, nums):
""":type nums: List[int] :rtype: List[str]"""
score = sorted(nums, reverse=True)
rank = ['Gold Medal', 'Silver Medal', 'Bronze Medal'] + map(str, range(4, len(nums) + 1))
return map(dict(zip(score, rank)).get, nums)
def findRela... | the_stack_v2_python_sparse | Google/1. easy/506. Relative Ranks.py | yemao616/summer18 | train | 0 | |
9257dc633287bc51e40c6c492dfa4cc02c4ca9ca | [
"line = self._complete_cleanup(line)\nline = self._cleanup_setup(line)\nif not self.minimal:\n line = self._prepare_patch(line)\n line = self._remove_dephell_call(line)\nSection.add(self, line)",
"if line.startswith('%setup'):\n line = line.replace(' -qn', ' -q -n')\n line = line.replace(' -q', '')\n ... | <|body_start_0|>
line = self._complete_cleanup(line)
line = self._cleanup_setup(line)
if not self.minimal:
line = self._prepare_patch(line)
line = self._remove_dephell_call(line)
Section.add(self, line)
<|end_body_0|>
<|body_start_1|>
if line.startswith('... | A class providing methods for %prep section cleaning. It simplifies %setup and %patch lines. | RpmPrep | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RpmPrep:
"""A class providing methods for %prep section cleaning. It simplifies %setup and %patch lines."""
def add(self, line):
"""Executes the format operations for the Prep phase."""
<|body_0|>
def _cleanup_setup(self, line: str) -> str:
"""Remove the useless ... | stack_v2_sparse_classes_36k_train_007159 | 2,509 | permissive | [
{
"docstring": "Executes the format operations for the Prep phase.",
"name": "add",
"signature": "def add(self, line)"
},
{
"docstring": "Remove the useless stuff from %setup line. Args: line: A string representing a line to process. Return: The processed line.",
"name": "_cleanup_setup",
... | 4 | stack_v2_sparse_classes_30k_train_008322 | Implement the Python class `RpmPrep` described below.
Class description:
A class providing methods for %prep section cleaning. It simplifies %setup and %patch lines.
Method signatures and docstrings:
- def add(self, line): Executes the format operations for the Prep phase.
- def _cleanup_setup(self, line: str) -> str... | Implement the Python class `RpmPrep` described below.
Class description:
A class providing methods for %prep section cleaning. It simplifies %setup and %patch lines.
Method signatures and docstrings:
- def add(self, line): Executes the format operations for the Prep phase.
- def _cleanup_setup(self, line: str) -> str... | 281db12db757fee9d120e8d084c246d056b474e7 | <|skeleton|>
class RpmPrep:
"""A class providing methods for %prep section cleaning. It simplifies %setup and %patch lines."""
def add(self, line):
"""Executes the format operations for the Prep phase."""
<|body_0|>
def _cleanup_setup(self, line: str) -> str:
"""Remove the useless ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RpmPrep:
"""A class providing methods for %prep section cleaning. It simplifies %setup and %patch lines."""
def add(self, line):
"""Executes the format operations for the Prep phase."""
line = self._complete_cleanup(line)
line = self._cleanup_setup(line)
if not self.minima... | the_stack_v2_python_sparse | spec_cleaner/rpmprep.py | rpm-software-management/spec-cleaner | train | 9 |
829dd54892233d00e5c6af248b0fb5dd266110d3 | [
"filename = file_check.check_file(filename)\nkey = clazz._check_key(key)\nclazz.check_file_is_readable(filename)\nreturn linux_attr.has_key(filename, key)",
"filename = file_check.check_file(filename)\nkey = clazz._check_key(key)\nclazz.check_file_is_readable(filename)\nif not linux_attr.has_key(filename, key):\n... | <|body_start_0|>
filename = file_check.check_file(filename)
key = clazz._check_key(key)
clazz.check_file_is_readable(filename)
return linux_attr.has_key(filename, key)
<|end_body_0|>
<|body_start_1|>
filename = file_check.check_file(filename)
key = clazz._check_key(key)
... | _file_attributes_linux_attr_exe | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _file_attributes_linux_attr_exe:
def has_key(clazz, filename, key):
"""Return True if filename has an attributed with key."""
<|body_0|>
def get_bytes(clazz, filename, key):
"""Return the attribute value with key for filename."""
<|body_1|>
def set_bytes... | stack_v2_sparse_classes_36k_train_007160 | 2,330 | permissive | [
{
"docstring": "Return True if filename has an attributed with key.",
"name": "has_key",
"signature": "def has_key(clazz, filename, key)"
},
{
"docstring": "Return the attribute value with key for filename.",
"name": "get_bytes",
"signature": "def get_bytes(clazz, filename, key)"
},
... | 6 | null | Implement the Python class `_file_attributes_linux_attr_exe` described below.
Class description:
Implement the _file_attributes_linux_attr_exe class.
Method signatures and docstrings:
- def has_key(clazz, filename, key): Return True if filename has an attributed with key.
- def get_bytes(clazz, filename, key): Return... | Implement the Python class `_file_attributes_linux_attr_exe` described below.
Class description:
Implement the _file_attributes_linux_attr_exe class.
Method signatures and docstrings:
- def has_key(clazz, filename, key): Return True if filename has an attributed with key.
- def get_bytes(clazz, filename, key): Return... | b9dd35b518848cea82e43d5016e425cc7dac32e5 | <|skeleton|>
class _file_attributes_linux_attr_exe:
def has_key(clazz, filename, key):
"""Return True if filename has an attributed with key."""
<|body_0|>
def get_bytes(clazz, filename, key):
"""Return the attribute value with key for filename."""
<|body_1|>
def set_bytes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _file_attributes_linux_attr_exe:
def has_key(clazz, filename, key):
"""Return True if filename has an attributed with key."""
filename = file_check.check_file(filename)
key = clazz._check_key(key)
clazz.check_file_is_readable(filename)
return linux_attr.has_key(filename... | the_stack_v2_python_sparse | lib/bes/fs/_detail/_file_attributes_linux_attr_exe.py | reconstruir/bes | train | 0 | |
41623a96c425fe216b040c5af44646a32cd773a2 | [
"super().__init__(message_type, message_text)\nif action_label is not None:\n if not isinstance(action_label, str):\n raise TypeError('Action label must be unicode.')\n self.action_label = action_label\nif action_class is not None:\n if not isinstance(action_class, str):\n raise TypeError('Ac... | <|body_start_0|>
super().__init__(message_type, message_text)
if action_label is not None:
if not isinstance(action_label, str):
raise TypeError('Action label must be unicode.')
self.action_label = action_label
if action_class is not None:
if n... | A message containing validation information about an xblock, extended to provide Studio-specific fields. | StudioValidationMessage | [
"MIT",
"AGPL-3.0-only",
"AGPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudioValidationMessage:
"""A message containing validation information about an xblock, extended to provide Studio-specific fields."""
def __init__(self, message_type, message_text, action_label=None, action_class=None, action_runtime_event=None):
"""Create a new message. Args: mess... | stack_v2_sparse_classes_36k_train_007161 | 5,012 | permissive | [
{
"docstring": "Create a new message. Args: message_type (str): The type associated with this message. Most be `WARNING` or `ERROR`. message_text (unicode): The textual message. action_label (unicode): Text to show on a \"fix-up\" action (optional). If present, either `action_class` or `action_runtime_event` sh... | 2 | null | Implement the Python class `StudioValidationMessage` described below.
Class description:
A message containing validation information about an xblock, extended to provide Studio-specific fields.
Method signatures and docstrings:
- def __init__(self, message_type, message_text, action_label=None, action_class=None, act... | Implement the Python class `StudioValidationMessage` described below.
Class description:
A message containing validation information about an xblock, extended to provide Studio-specific fields.
Method signatures and docstrings:
- def __init__(self, message_type, message_text, action_label=None, action_class=None, act... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class StudioValidationMessage:
"""A message containing validation information about an xblock, extended to provide Studio-specific fields."""
def __init__(self, message_type, message_text, action_label=None, action_class=None, action_runtime_event=None):
"""Create a new message. Args: mess... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StudioValidationMessage:
"""A message containing validation information about an xblock, extended to provide Studio-specific fields."""
def __init__(self, message_type, message_text, action_label=None, action_class=None, action_runtime_event=None):
"""Create a new message. Args: message_type (str... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/lib/xmodule/xmodule/validation.py | luque/better-ways-of-thinking-about-software | train | 3 |
8d81bb9c8b41ab14b36a03783502ac168b695308 | [
"if x == 0:\n return x\nif x > 0:\n str_x = str(x)\n reverse_str_x = str_x[::-1]\n reverse_x = int(reverse_str_x)\n if reverse_x < (-2) ** 31 or reverse_x > 2 ** 31 - 1:\n return 0\nelse:\n str_x = str(x)\n reverse_str_x = str_x[::-1]\n reverse_str_x = '-' + reverse_str_x.replace('-',... | <|body_start_0|>
if x == 0:
return x
if x > 0:
str_x = str(x)
reverse_str_x = str_x[::-1]
reverse_x = int(reverse_str_x)
if reverse_x < (-2) ** 31 or reverse_x > 2 ** 31 - 1:
return 0
else:
str_x = str(x)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
"""这个思路是将int转成str"""
<|body_0|>
def reverse2(self, x):
"""取余再除以10向下取整,这样可以逆序获取数字的各个位,再迭代乘以10就能计算出逆序数了"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x == 0:
return x
if x > 0:
str_x... | stack_v2_sparse_classes_36k_train_007162 | 1,691 | no_license | [
{
"docstring": "这个思路是将int转成str",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": "取余再除以10向下取整,这样可以逆序获取数字的各个位,再迭代乘以10就能计算出逆序数了",
"name": "reverse2",
"signature": "def reverse2(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017999 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): 这个思路是将int转成str
- def reverse2(self, x): 取余再除以10向下取整,这样可以逆序获取数字的各个位,再迭代乘以10就能计算出逆序数了 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): 这个思路是将int转成str
- def reverse2(self, x): 取余再除以10向下取整,这样可以逆序获取数字的各个位,再迭代乘以10就能计算出逆序数了
<|skeleton|>
class Solution:
def reverse(self, x):
"""这个思路... | 86e4a46de635c74d7c80c3d186d21d79cfb7a640 | <|skeleton|>
class Solution:
def reverse(self, x):
"""这个思路是将int转成str"""
<|body_0|>
def reverse2(self, x):
"""取余再除以10向下取整,这样可以逆序获取数字的各个位,再迭代乘以10就能计算出逆序数了"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse(self, x):
"""这个思路是将int转成str"""
if x == 0:
return x
if x > 0:
str_x = str(x)
reverse_str_x = str_x[::-1]
reverse_x = int(reverse_str_x)
if reverse_x < (-2) ** 31 or reverse_x > 2 ** 31 - 1:
... | the_stack_v2_python_sparse | leetcode/02整数反转.py | fairypeng/a_python_note | train | 0 | |
970480e836f1a0dd15ff86308dd87b679ef9a4af | [
"st = {}\ni, ans = (0, 0)\nfor j in range(len(s)):\n if s[j] in st:\n i = max(st[s[j]], i)\n ans = max(ans, j - i + 1)\n st[s[j]] = j + 1\nreturn ans",
"l = 0\nstart = 0\ndic = {}\nfor i in range(len(s)):\n cur = s[i]\n if cur not in dic.keys():\n dic[cur] = i\n else:\n if d... | <|body_start_0|>
st = {}
i, ans = (0, 0)
for j in range(len(s)):
if s[j] in st:
i = max(st[s[j]], i)
ans = max(ans, j - i + 1)
st[s[j]] = j + 1
return ans
<|end_body_0|>
<|body_start_1|>
l = 0
start = 0
dic = {}... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def LongSubstring(s):
""":param target:string :return: int"""
<|body_0|>
def lengthOfLongestSubstring(s):
""":param s: str :return: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
st = {}
i, ans = (0, 0)
for j in range(... | stack_v2_sparse_classes_36k_train_007163 | 1,341 | no_license | [
{
"docstring": ":param target:string :return: int",
"name": "LongSubstring",
"signature": "def LongSubstring(s)"
},
{
"docstring": ":param s: str :return: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def LongSubstring(s): :param target:string :return: int
- def lengthOfLongestSubstring(s): :param s: str :return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def LongSubstring(s): :param target:string :return: int
- def lengthOfLongestSubstring(s): :param s: str :return: int
<|skeleton|>
class Solution:
def LongSubstring(s):
... | 3326f8d65df682cad984912ac6ace0c815628867 | <|skeleton|>
class Solution:
def LongSubstring(s):
""":param target:string :return: int"""
<|body_0|>
def lengthOfLongestSubstring(s):
""":param s: str :return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def LongSubstring(s):
""":param target:string :return: int"""
st = {}
i, ans = (0, 0)
for j in range(len(s)):
if s[j] in st:
i = max(st[s[j]], i)
ans = max(ans, j - i + 1)
st[s[j]] = j + 1
return ans
def... | the_stack_v2_python_sparse | LongSubstring/LongSubstring.py | sheyvwei/algorithm | train | 0 | |
69cc0b61d83b54ff2507ecf58441f73b8def71a9 | [
"from mpl_toolkits.basemap import Basemap\nsuper(DaffyMapHelper, self).__init__(usage_string=usage_string)\nif axes is None:\n axes = plt.gca()\nself.basemap = Basemap(llcrnrlon=self.cfg.map_options['western_longitude'], llcrnrlat=self.cfg.map_options['southern_latitude'], urcrnrlon=self.cfg.map_options['eastern... | <|body_start_0|>
from mpl_toolkits.basemap import Basemap
super(DaffyMapHelper, self).__init__(usage_string=usage_string)
if axes is None:
axes = plt.gca()
self.basemap = Basemap(llcrnrlon=self.cfg.map_options['western_longitude'], llcrnrlat=self.cfg.map_options['southern_lat... | Provides routines for plotting stuff on maps | DaffyMapHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DaffyMapHelper:
"""Provides routines for plotting stuff on maps"""
def __init__(self, usage_string=None, axes=None):
"""Instantiate a DaffyMapHelper. This will create the `basemap' member variable according to the settings in self.cfg"""
<|body_0|>
def decorate_map(self)... | stack_v2_sparse_classes_36k_train_007164 | 27,841 | no_license | [
{
"docstring": "Instantiate a DaffyMapHelper. This will create the `basemap' member variable according to the settings in self.cfg",
"name": "__init__",
"signature": "def __init__(self, usage_string=None, axes=None)"
},
{
"docstring": "Decorates the map according to the settings in the DaffyPlot... | 2 | stack_v2_sparse_classes_30k_train_007962 | Implement the Python class `DaffyMapHelper` described below.
Class description:
Provides routines for plotting stuff on maps
Method signatures and docstrings:
- def __init__(self, usage_string=None, axes=None): Instantiate a DaffyMapHelper. This will create the `basemap' member variable according to the settings in s... | Implement the Python class `DaffyMapHelper` described below.
Class description:
Provides routines for plotting stuff on maps
Method signatures and docstrings:
- def __init__(self, usage_string=None, axes=None): Instantiate a DaffyMapHelper. This will create the `basemap' member variable according to the settings in s... | ea02c68f30a61b8a8048b7801f3d0433b9adecc9 | <|skeleton|>
class DaffyMapHelper:
"""Provides routines for plotting stuff on maps"""
def __init__(self, usage_string=None, axes=None):
"""Instantiate a DaffyMapHelper. This will create the `basemap' member variable according to the settings in self.cfg"""
<|body_0|>
def decorate_map(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DaffyMapHelper:
"""Provides routines for plotting stuff on maps"""
def __init__(self, usage_string=None, axes=None):
"""Instantiate a DaffyMapHelper. This will create the `basemap' member variable according to the settings in self.cfg"""
from mpl_toolkits.basemap import Basemap
su... | the_stack_v2_python_sparse | daffy_plot/plot_helper.py | JavierDelgadoNoaa/daffyplot | train | 0 |
feefabeb6afe949d8f7faf0cf316c3db122a2505 | [
"self.constrained = False\nself.bounds = [-inf, inf]\nvalidateName(name)\nArgument.__init__(self, name, value, const)\nreturn",
"Argument.setValue(self, val)\nif lb is not None:\n self.bounds[0] = lb\nif ub is not None:\n self.bounds[1] = ub\nreturn self",
"self.const = bool(const)\nif value is not None:\... | <|body_start_0|>
self.constrained = False
self.bounds = [-inf, inf]
validateName(name)
Argument.__init__(self, name, value, const)
return
<|end_body_0|>
<|body_start_1|>
Argument.setValue(self, val)
if lb is not None:
self.bounds[0] = lb
if ub... | Parameter class. Attributes name -- A name for this Parameter. const -- A flag indicating whether this is considered a constant. _value -- The value of the Parameter. Modified with 'setValue'. value -- Property for 'getValue' and 'setValue'. constrained -- A flag indicating if the Parameter is constrained (default Fals... | Parameter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parameter:
"""Parameter class. Attributes name -- A name for this Parameter. const -- A flag indicating whether this is considered a constant. _value -- The value of the Parameter. Modified with 'setValue'. value -- Property for 'getValue' and 'setValue'. constrained -- A flag indicating if the P... | stack_v2_sparse_classes_36k_train_007165 | 9,432 | no_license | [
{
"docstring": "Initialization. name -- The name of this Parameter (must be a valid attribute identifier) value -- The initial value of this Parameter (default 0). const -- A flag inticating whether the Parameter is a constant (like pi). Raises ValueError if the name is not a valid attribute identifier",
"n... | 5 | stack_v2_sparse_classes_30k_train_020356 | Implement the Python class `Parameter` described below.
Class description:
Parameter class. Attributes name -- A name for this Parameter. const -- A flag indicating whether this is considered a constant. _value -- The value of the Parameter. Modified with 'setValue'. value -- Property for 'getValue' and 'setValue'. co... | Implement the Python class `Parameter` described below.
Class description:
Parameter class. Attributes name -- A name for this Parameter. const -- A flag indicating whether this is considered a constant. _value -- The value of the Parameter. Modified with 'setValue'. value -- Property for 'getValue' and 'setValue'. co... | 303f73c570c1d756106aa69724898d5b119c4ead | <|skeleton|>
class Parameter:
"""Parameter class. Attributes name -- A name for this Parameter. const -- A flag indicating whether this is considered a constant. _value -- The value of the Parameter. Modified with 'setValue'. value -- Property for 'getValue' and 'setValue'. constrained -- A flag indicating if the P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Parameter:
"""Parameter class. Attributes name -- A name for this Parameter. const -- A flag indicating whether this is considered a constant. _value -- The value of the Parameter. Modified with 'setValue'. value -- Property for 'getValue' and 'setValue'. constrained -- A flag indicating if the Parameter is c... | the_stack_v2_python_sparse | diffpy/srfit/fitbase/parameter.py | cfarrow/diffpy.srfit | train | 0 |
47f3dc0d9132d74572235216c330a28e86d0bd34 | [
"n = len(nums)\nif n == 0:\n return 0\nl = 0\nr = 0\nc = nums[0]\nans = 0\nwhile l < n:\n while c < k:\n r += 1\n if r >= n:\n break\n c += nums[r]\n if c == k:\n ans += 1\n c -= nums[l]\n if l < r:\n l += 1\n else:\n l += 1\n r = l\n ... | <|body_start_0|>
n = len(nums)
if n == 0:
return 0
l = 0
r = 0
c = nums[0]
ans = 0
while l < n:
while c < k:
r += 1
if r >= n:
break
c += nums[r]
if c == k:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarraySumWA(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def subarraySumT(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
def subarraySum(self, nums, k):
""":type ... | stack_v2_sparse_classes_36k_train_007166 | 2,230 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "subarraySumWA",
"signature": "def subarraySumWA(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "subarraySumT",
"signature": "def subarraySumT(self, nums, k)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_008998 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySumWA(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def subarraySumT(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def subarrayS... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySumWA(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def subarraySumT(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def subarrayS... | 02ebe56cd92b9f4baeee132c5077892590018650 | <|skeleton|>
class Solution:
def subarraySumWA(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def subarraySumT(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
def subarraySum(self, nums, k):
""":type ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subarraySumWA(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
n = len(nums)
if n == 0:
return 0
l = 0
r = 0
c = nums[0]
ans = 0
while l < n:
while c < k:
r += 1
... | the_stack_v2_python_sparse | python/leetcode.560.py | CalvinNeo/LeetCode | train | 3 | |
f4f87afcd2d9a2d79e99e764dec261398a562be5 | [
"GObject.GObject.__init__(self)\nmsg = long_op_status.get_msg()\nself._old_val = -1\nself._lbl = Gtk.Label(label=msg)\nself._lbl.set_use_markup(True)\nself._pbar = Gtk.ProgressBar()\nself._hbox = Gtk.HBox()\nif long_op_status.can_cancel():\n self._cancel = Gtk.Button(stock=Gtk.STOCK_CANCEL)\n self._cancel.con... | <|body_start_0|>
GObject.GObject.__init__(self)
msg = long_op_status.get_msg()
self._old_val = -1
self._lbl = Gtk.Label(label=msg)
self._lbl.set_use_markup(True)
self._pbar = Gtk.ProgressBar()
self._hbox = Gtk.HBox()
if long_op_status.can_cancel():
... | This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar. | _GtkProgressBar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _GtkProgressBar:
"""This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar."""
def __init__(self, long_op_status):
""":param long_op_status: the status of the operation. :type long_op_status: :class:`.LongOpSta... | stack_v2_sparse_classes_36k_train_007167 | 20,395 | no_license | [
{
"docstring": ":param long_op_status: the status of the operation. :type long_op_status: :class:`.LongOpStatus`",
"name": "__init__",
"signature": "def __init__(self, long_op_status)"
},
{
"docstring": "Move the progress bar on a step.",
"name": "step",
"signature": "def step(self)"
}... | 2 | null | Implement the Python class `_GtkProgressBar` described below.
Class description:
This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar.
Method signatures and docstrings:
- def __init__(self, long_op_status): :param long_op_status: the status o... | Implement the Python class `_GtkProgressBar` described below.
Class description:
This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar.
Method signatures and docstrings:
- def __init__(self, long_op_status): :param long_op_status: the status o... | 0c79561bed7ff42c88714edbc85197fa9235e188 | <|skeleton|>
class _GtkProgressBar:
"""This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar."""
def __init__(self, long_op_status):
""":param long_op_status: the status of the operation. :type long_op_status: :class:`.LongOpSta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _GtkProgressBar:
"""This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar."""
def __init__(self, long_op_status):
""":param long_op_status: the status of the operation. :type long_op_status: :class:`.LongOpStatus`"""
... | the_stack_v2_python_sparse | gui/widgets/progressdialog.py | balrok/gramps_addon | train | 2 |
fd99c1151b9dd722ff6e98ad6d49851dcfc4bda4 | [
"if len(nums) == 0:\n return\nsumto = [0] * len(nums)\nsumto[0] = nums[0]\nfor i in range(1, len(nums)):\n sumto[i] = sumto[i - 1] + nums[i]\nself.sumto = sumto\nself.nums = nums",
"bet = val - self.nums[i]\nfor j in range(i, len(self.sumto)):\n self.sumto[j] += bet\nself.nums[i] = val",
"if len(self.n... | <|body_start_0|>
if len(nums) == 0:
return
sumto = [0] * len(nums)
sumto[0] = nums[0]
for i in range(1, len(nums)):
sumto[i] = sumto[i - 1] + nums[i]
self.sumto = sumto
self.nums = nums
<|end_body_0|>
<|body_start_1|>
bet = val - self.nums... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k_train_007168 | 967 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 48b43999fb7e2ed82d922e1f64ac76f8fabe4baa | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
if len(nums) == 0:
return
sumto = [0] * len(nums)
sumto[0] = nums[0]
for i in range(1, len(nums)):
sumto[i] = sumto[i - 1] + nums[i]
self.sumto = sumto
self.nums = nu... | the_stack_v2_python_sparse | 307.py | saleed/LeetCode | train | 2 | |
8f09ded99e1de928e0f7f0e92dc31a778d31605d | [
"query = '\\n select distinct * where {\\n\\n BIND (\"%s\" AS ?pid)\\n BIND (%s as ?sessionid)\\n BIND (\"%s\" as ?shortname)\\n \\n ?participant austalk:id ?pid .\\n ?rc rdf:type austalk:RecordedComponent .\\n ?rc... | <|body_start_0|>
query = '\n select distinct * where {\n\n BIND ("%s" AS ?pid)\n BIND (%s as ?sessionid)\n BIND ("%s" as ?shortname)\n \n ?participant austalk:id ?pid .\n ?rc rdf:type austalk:RecordedComponent .\n ... | ComponentManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComponentManager:
def get(self, participant_id, session_id, component_id):
"""Return the component for this participant/session/component id or None if none exists participant_id is like 1_123 session_id is 1, 2, 3 component_id is shortname words-1, conversation"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_007169 | 6,817 | no_license | [
{
"docstring": "Return the component for this participant/session/component id or None if none exists participant_id is like 1_123 session_id is 1, 2, 3 component_id is shortname words-1, conversation",
"name": "get",
"signature": "def get(self, participant_id, session_id, component_id)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_003658 | Implement the Python class `ComponentManager` described below.
Class description:
Implement the ComponentManager class.
Method signatures and docstrings:
- def get(self, participant_id, session_id, component_id): Return the component for this participant/session/component id or None if none exists participant_id is l... | Implement the Python class `ComponentManager` described below.
Class description:
Implement the ComponentManager class.
Method signatures and docstrings:
- def get(self, participant_id, session_id, component_id): Return the component for this participant/session/component id or None if none exists participant_id is l... | 88000a79f0a18c92de0092814de3dbb2409f5515 | <|skeleton|>
class ComponentManager:
def get(self, participant_id, session_id, component_id):
"""Return the component for this participant/session/component id or None if none exists participant_id is like 1_123 session_id is 1, 2, 3 component_id is shortname words-1, conversation"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComponentManager:
def get(self, participant_id, session_id, component_id):
"""Return the component for this participant/session/component id or None if none exists participant_id is like 1_123 session_id is 1, 2, 3 component_id is shortname words-1, conversation"""
query = '\n selec... | the_stack_v2_python_sparse | browse/modelspackage/components.py | Alveo/smallasc | train | 0 | |
400d546aa8c73009197c0223e9cc584590af0b42 | [
"self.sums_dp = [None] * len(nums)\nif len(nums) > 0:\n self.sums_dp[0] = nums[0]\n for i in range(1, len(nums)):\n self.sums_dp[i] = self.sums_dp[i - 1] + nums[i]",
"if i == 0:\n return self.sums_dp[j]\nelse:\n return self.sums_dp[j] - self.sums_dp[i - 1]"
] | <|body_start_0|>
self.sums_dp = [None] * len(nums)
if len(nums) > 0:
self.sums_dp[0] = nums[0]
for i in range(1, len(nums)):
self.sums_dp[i] = self.sums_dp[i - 1] + nums[i]
<|end_body_0|>
<|body_start_1|>
if i == 0:
return self.sums_dp[j]
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int] # sum range dp solution # sum[i] means sum from 0 to i inclusively. # ai...aj sum will be sum[j] - sum[i-1] # if i = 0, a0...ai will be sum[j]. No need to minus sum[0-1]"""
<|body_0|... | stack_v2_sparse_classes_36k_train_007170 | 1,045 | no_license | [
{
"docstring": "initialize your data structure here. :type nums: List[int] # sum range dp solution # sum[i] means sum from 0 to i inclusively. # ai...aj sum will be sum[j] - sum[i-1] # if i = 0, a0...ai will be sum[j]. No need to minus sum[0-1]",
"name": "__init__",
"signature": "def __init__(self, nums... | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int] # sum range dp solution # sum[i] means sum from 0 to i inclusively. # ai...aj sum will be sum... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int] # sum range dp solution # sum[i] means sum from 0 to i inclusively. # ai...aj sum will be sum... | 26e2a812d86b4c09b2917d983df76d3ece69b074 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int] # sum range dp solution # sum[i] means sum from 0 to i inclusively. # ai...aj sum will be sum[j] - sum[i-1] # if i = 0, a0...ai will be sum[j]. No need to minus sum[0-1]"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int] # sum range dp solution # sum[i] means sum from 0 to i inclusively. # ai...aj sum will be sum[j] - sum[i-1] # if i = 0, a0...ai will be sum[j]. No need to minus sum[0-1]"""
self.sums_dp = [None] *... | the_stack_v2_python_sparse | dp_desigh_rangeSumQuery.py | YusiZhang/leetcode-python | train | 1 | |
72d68c9497cd13a71902617bad99393114ec4f23 | [
"component_spc = kwargs['spc'] if 'spc' in kwargs else spc.SPC\nobject.iqObject.__init__(self, parent=parent, resource=resource, spc=component_spc, context=context)\ncryptopro.iqCryptoProManagerProto.__init__(self)",
"find_paths = self.getAttribute('find_paths')\nif find_paths is None:\n find_paths = cryptopro... | <|body_start_0|>
component_spc = kwargs['spc'] if 'spc' in kwargs else spc.SPC
object.iqObject.__init__(self, parent=parent, resource=resource, spc=component_spc, context=context)
cryptopro.iqCryptoProManagerProto.__init__(self)
<|end_body_0|>
<|body_start_1|>
find_paths = self.getAttri... | CryptoProManager component. | iqCryptoProManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class iqCryptoProManager:
"""CryptoProManager component."""
def __init__(self, parent=None, resource=None, context=None, *args, **kwargs):
"""Standard component constructor. :param parent: Parent object. :param resource: Object resource dictionary. :param context: Context dictionary."""
... | stack_v2_sparse_classes_36k_train_007171 | 1,156 | no_license | [
{
"docstring": "Standard component constructor. :param parent: Parent object. :param resource: Object resource dictionary. :param context: Context dictionary.",
"name": "__init__",
"signature": "def __init__(self, parent=None, resource=None, context=None, *args, **kwargs)"
},
{
"docstring": "Get... | 2 | stack_v2_sparse_classes_30k_train_017412 | Implement the Python class `iqCryptoProManager` described below.
Class description:
CryptoProManager component.
Method signatures and docstrings:
- def __init__(self, parent=None, resource=None, context=None, *args, **kwargs): Standard component constructor. :param parent: Parent object. :param resource: Object resou... | Implement the Python class `iqCryptoProManager` described below.
Class description:
CryptoProManager component.
Method signatures and docstrings:
- def __init__(self, parent=None, resource=None, context=None, *args, **kwargs): Standard component constructor. :param parent: Parent object. :param resource: Object resou... | 7550e242746cb2fb1219474463f8db21f8e3e114 | <|skeleton|>
class iqCryptoProManager:
"""CryptoProManager component."""
def __init__(self, parent=None, resource=None, context=None, *args, **kwargs):
"""Standard component constructor. :param parent: Parent object. :param resource: Object resource dictionary. :param context: Context dictionary."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class iqCryptoProManager:
"""CryptoProManager component."""
def __init__(self, parent=None, resource=None, context=None, *args, **kwargs):
"""Standard component constructor. :param parent: Parent object. :param resource: Object resource dictionary. :param context: Context dictionary."""
compone... | the_stack_v2_python_sparse | iq/components/cryptopro_manager/component.py | XHermitOne/iq_framework | train | 1 |
bbc48d786ea19f95c32e21a0dcb8780616a02c12 | [
"self.packages = []\nif from_file:\n log.debug('Loading RPM profile from file.')\n json_buffer = from_file.read()\n pkg_dicts = json.loads(json_buffer)\n for pkg_dict in pkg_dicts:\n self.packages.append(Package(name=pkg_dict['name'], version=pkg_dict['version'], release=pkg_dict['release'], arch... | <|body_start_0|>
self.packages = []
if from_file:
log.debug('Loading RPM profile from file.')
json_buffer = from_file.read()
pkg_dicts = json.loads(json_buffer)
for pkg_dict in pkg_dicts:
self.packages.append(Package(name=pkg_dict['name'], ... | RPMProfile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RPMProfile:
def __init__(self, from_file=None):
"""Load the RPM package profile from a given file, or from rpm itself. NOTE: from_file is a file descriptor, not a file name."""
<|body_0|>
def __accumulateProfile(self, rpm_header_list):
"""Accumulates list of installe... | stack_v2_sparse_classes_36k_train_007172 | 5,448 | no_license | [
{
"docstring": "Load the RPM package profile from a given file, or from rpm itself. NOTE: from_file is a file descriptor, not a file name.",
"name": "__init__",
"signature": "def __init__(self, from_file=None)"
},
{
"docstring": "Accumulates list of installed rpm info @param rpm_header_list: lis... | 4 | stack_v2_sparse_classes_30k_val_000098 | Implement the Python class `RPMProfile` described below.
Class description:
Implement the RPMProfile class.
Method signatures and docstrings:
- def __init__(self, from_file=None): Load the RPM package profile from a given file, or from rpm itself. NOTE: from_file is a file descriptor, not a file name.
- def __accumul... | Implement the Python class `RPMProfile` described below.
Class description:
Implement the RPMProfile class.
Method signatures and docstrings:
- def __init__(self, from_file=None): Load the RPM package profile from a given file, or from rpm itself. NOTE: from_file is a file descriptor, not a file name.
- def __accumul... | 81643aaaa084575f4e651d3de75a86a9d31a8f49 | <|skeleton|>
class RPMProfile:
def __init__(self, from_file=None):
"""Load the RPM package profile from a given file, or from rpm itself. NOTE: from_file is a file descriptor, not a file name."""
<|body_0|>
def __accumulateProfile(self, rpm_header_list):
"""Accumulates list of installe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RPMProfile:
def __init__(self, from_file=None):
"""Load the RPM package profile from a given file, or from rpm itself. NOTE: from_file is a file descriptor, not a file name."""
self.packages = []
if from_file:
log.debug('Loading RPM profile from file.')
json_buf... | the_stack_v2_python_sparse | pulp_rpm/src/pulp_rpm/repo_auth/rhsm/profile.py | jwmatthews/pulp_rpm | train | 0 | |
0d3eb1ab63e25bcac42adbda4ebc9241d32cd275 | [
"df = df.drop(['Ward', 'Pct'], axis=1)\ndf = df.drop([0])\nreturn df",
"for key in d:\n if '.' in key:\n newKey = key.replace('.', '')\n d[newKey] = d[key]\n del d[key]\nreturn d",
"data = StringIO(response)\ndf = pd.read_csv(data)\ndf = transformGeneral.projectGeneral(df)\nlol = df.valu... | <|body_start_0|>
df = df.drop(['Ward', 'Pct'], axis=1)
df = df.drop([0])
return df
<|end_body_0|>
<|body_start_1|>
for key in d:
if '.' in key:
newKey = key.replace('.', '')
d[newKey] = d[key]
del d[key]
return d
<|end_... | transformGeneral | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class transformGeneral:
def projectGeneral(df):
"""Takes pandas df for general election and removes Pct and Ward"""
<|body_0|>
def removePeriods(d):
"""Takes a dictionary and removes periods from the keys"""
<|body_1|>
def getAggByTownResponse(response):
... | stack_v2_sparse_classes_36k_train_007173 | 6,021 | no_license | [
{
"docstring": "Takes pandas df for general election and removes Pct and Ward",
"name": "projectGeneral",
"signature": "def projectGeneral(df)"
},
{
"docstring": "Takes a dictionary and removes periods from the keys",
"name": "removePeriods",
"signature": "def removePeriods(d)"
},
{
... | 5 | null | Implement the Python class `transformGeneral` described below.
Class description:
Implement the transformGeneral class.
Method signatures and docstrings:
- def projectGeneral(df): Takes pandas df for general election and removes Pct and Ward
- def removePeriods(d): Takes a dictionary and removes periods from the keys... | Implement the Python class `transformGeneral` described below.
Class description:
Implement the transformGeneral class.
Method signatures and docstrings:
- def projectGeneral(df): Takes pandas df for general election and removes Pct and Ward
- def removePeriods(d): Takes a dictionary and removes periods from the keys... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class transformGeneral:
def projectGeneral(df):
"""Takes pandas df for general election and removes Pct and Ward"""
<|body_0|>
def removePeriods(d):
"""Takes a dictionary and removes periods from the keys"""
<|body_1|>
def getAggByTownResponse(response):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class transformGeneral:
def projectGeneral(df):
"""Takes pandas df for general election and removes Pct and Ward"""
df = df.drop(['Ward', 'Pct'], axis=1)
df = df.drop([0])
return df
def removePeriods(d):
"""Takes a dictionary and removes periods from the keys"""
... | the_stack_v2_python_sparse | stathisk_simonwu_nathanmo_nikm/generalElection.py | maximega/course-2019-spr-proj | train | 2 | |
39e8d2a3f645fc432a2c0375e0ce01150aef9888 | [
"\"\"\"\n DFS + cache\n \"\"\"\ncache = {}\n\ndef findTarget(index, s):\n if (index, s) not in cache:\n result = 0\n if index == len(nums):\n if s == 0:\n result = 1\n else:\n result = findTarget(index + 1, s - nums[index]) + findTarget(inde... | <|body_start_0|>
"""
DFS + cache
"""
cache = {}
def findTarget(index, s):
if (index, s) not in cache:
result = 0
if index == len(nums):
if s == 0:
result = 1
e... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTargetSumWays(self, nums, S):
""":type nums: List[int] :type S: int :rtype: int"""
<|body_0|>
def fast(self, nums, S):
""":type nums: List[int] :type S: int :rtype: int 思路: 1、DFS:这道题目如果用DFS求解是最直观的。也可以通过,但是效率比较低, 因为其运行的时间复杂度是指数级的。 2、DP:该问题等价于:将nums中的... | stack_v2_sparse_classes_36k_train_007174 | 4,228 | no_license | [
{
"docstring": ":type nums: List[int] :type S: int :rtype: int",
"name": "findTargetSumWays",
"signature": "def findTargetSumWays(self, nums, S)"
},
{
"docstring": ":type nums: List[int] :type S: int :rtype: int 思路: 1、DFS:这道题目如果用DFS求解是最直观的。也可以通过,但是效率比较低, 因为其运行的时间复杂度是指数级的。 2、DP:该问题等价于:将nums中的元素划分... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTargetSumWays(self, nums, S): :type nums: List[int] :type S: int :rtype: int
- def fast(self, nums, S): :type nums: List[int] :type S: int :rtype: int 思路: 1、DFS:这道题目如果用DF... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTargetSumWays(self, nums, S): :type nums: List[int] :type S: int :rtype: int
- def fast(self, nums, S): :type nums: List[int] :type S: int :rtype: int 思路: 1、DFS:这道题目如果用DF... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def findTargetSumWays(self, nums, S):
""":type nums: List[int] :type S: int :rtype: int"""
<|body_0|>
def fast(self, nums, S):
""":type nums: List[int] :type S: int :rtype: int 思路: 1、DFS:这道题目如果用DFS求解是最直观的。也可以通过,但是效率比较低, 因为其运行的时间复杂度是指数级的。 2、DP:该问题等价于:将nums中的... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findTargetSumWays(self, nums, S):
""":type nums: List[int] :type S: int :rtype: int"""
"""
DFS + cache
"""
cache = {}
def findTarget(index, s):
if (index, s) not in cache:
result = 0
if i... | the_stack_v2_python_sparse | graph/494_Target_Sum.py | vsdrun/lc_public | train | 6 | |
6a7963139710969c04912c273660b44d432ea046 | [
"a = random.randint(1, 10)\nlogging.info('=============%s次测试医生界面健康宣教=============' % a)\nl = DoctorAdviceAndHealth(self.driver)\nself.assertTrue(l.login_doctor())\nfor i in range(a):\n l.doctorHealth(-1)",
"a = random.randint(1, 10)\nlogging.info('=============%s次测试医生界面注意事项=============' % a)\nl = DoctorAdvice... | <|body_start_0|>
a = random.randint(1, 10)
logging.info('=============%s次测试医生界面健康宣教=============' % a)
l = DoctorAdviceAndHealth(self.driver)
self.assertTrue(l.login_doctor())
for i in range(a):
l.doctorHealth(-1)
<|end_body_0|>
<|body_start_1|>
a = random.ra... | TestDoctorAdviceAndHealth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDoctorAdviceAndHealth:
def test_doctorHealth(self):
"""测试医生界面健康宣教 :return:"""
<|body_0|>
def test_doctorAdvice(self):
"""测试医生界面注意事项 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
a = random.randint(1, 10)
logging.info('========... | stack_v2_sparse_classes_36k_train_007175 | 1,297 | no_license | [
{
"docstring": "测试医生界面健康宣教 :return:",
"name": "test_doctorHealth",
"signature": "def test_doctorHealth(self)"
},
{
"docstring": "测试医生界面注意事项 :return:",
"name": "test_doctorAdvice",
"signature": "def test_doctorAdvice(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014755 | Implement the Python class `TestDoctorAdviceAndHealth` described below.
Class description:
Implement the TestDoctorAdviceAndHealth class.
Method signatures and docstrings:
- def test_doctorHealth(self): 测试医生界面健康宣教 :return:
- def test_doctorAdvice(self): 测试医生界面注意事项 :return: | Implement the Python class `TestDoctorAdviceAndHealth` described below.
Class description:
Implement the TestDoctorAdviceAndHealth class.
Method signatures and docstrings:
- def test_doctorHealth(self): 测试医生界面健康宣教 :return:
- def test_doctorAdvice(self): 测试医生界面注意事项 :return:
<|skeleton|>
class TestDoctorAdviceAndHealt... | d2b7819fd3687e0a011988fefab3e6fd70bb014a | <|skeleton|>
class TestDoctorAdviceAndHealth:
def test_doctorHealth(self):
"""测试医生界面健康宣教 :return:"""
<|body_0|>
def test_doctorAdvice(self):
"""测试医生界面注意事项 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDoctorAdviceAndHealth:
def test_doctorHealth(self):
"""测试医生界面健康宣教 :return:"""
a = random.randint(1, 10)
logging.info('=============%s次测试医生界面健康宣教=============' % a)
l = DoctorAdviceAndHealth(self.driver)
self.assertTrue(l.login_doctor())
for i in range(a):
... | the_stack_v2_python_sparse | care_user/test_case/test_doctorAdviceAndHealth.py | vothin/code | train | 0 | |
590818b9021b8044953baffcdb23423b10962eb0 | [
"super().__init__()\nself.k_list = k_list\nself.data = data\nself.d = data.shape[-1]\nself.init_centroids = init_centroids\nself.frozen_centroids = frozen_centroids\nself.logger = logging.getLogger('Kmeans')\nself.debug = False\nself.epoch = epoch + 1",
"data = self.data\nlabels = []\ncentroids = []\ntqdm_batch =... | <|body_start_0|>
super().__init__()
self.k_list = k_list
self.data = data
self.d = data.shape[-1]
self.init_centroids = init_centroids
self.frozen_centroids = frozen_centroids
self.logger = logging.getLogger('Kmeans')
self.debug = False
self.epoch ... | Kmeans | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Kmeans:
def __init__(self, k_list, data, epoch=0, init_centroids=None, frozen_centroids=False):
"""Performs many k-means clustering. Args: data (np.array N * dim): data to cluster"""
<|body_0|>
def compute_clusters(self):
"""compute cluster Returns: torch.tensor, lis... | stack_v2_sparse_classes_36k_train_007176 | 3,988 | no_license | [
{
"docstring": "Performs many k-means clustering. Args: data (np.array N * dim): data to cluster",
"name": "__init__",
"signature": "def __init__(self, k_list, data, epoch=0, init_centroids=None, frozen_centroids=False)"
},
{
"docstring": "compute cluster Returns: torch.tensor, list: clus_labels... | 2 | stack_v2_sparse_classes_30k_train_011387 | Implement the Python class `Kmeans` described below.
Class description:
Implement the Kmeans class.
Method signatures and docstrings:
- def __init__(self, k_list, data, epoch=0, init_centroids=None, frozen_centroids=False): Performs many k-means clustering. Args: data (np.array N * dim): data to cluster
- def compute... | Implement the Python class `Kmeans` described below.
Class description:
Implement the Kmeans class.
Method signatures and docstrings:
- def __init__(self, k_list, data, epoch=0, init_centroids=None, frozen_centroids=False): Performs many k-means clustering. Args: data (np.array N * dim): data to cluster
- def compute... | 1b82dd088e5475b45688bec44830f3e96ae65d32 | <|skeleton|>
class Kmeans:
def __init__(self, k_list, data, epoch=0, init_centroids=None, frozen_centroids=False):
"""Performs many k-means clustering. Args: data (np.array N * dim): data to cluster"""
<|body_0|>
def compute_clusters(self):
"""compute cluster Returns: torch.tensor, lis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Kmeans:
def __init__(self, k_list, data, epoch=0, init_centroids=None, frozen_centroids=False):
"""Performs many k-means clustering. Args: data (np.array N * dim): data to cluster"""
super().__init__()
self.k_list = k_list
self.data = data
self.d = data.shape[-1]
... | the_stack_v2_python_sparse | pcs/models/clustering.py | andyincode2/PCS-FUDA | train | 0 | |
397edfb02dceead037d10ab4b64b0088a568c026 | [
"if Config.validation:\n print('Skipping empirical distribution in validation run')\n self.distribution = zeros((313,))\n return\nprint('Finding empirical color distribution...')\nself.distribution = generator.get_bin_counts()\nself.distribution = self.distribution / max(self.distribution)\nself.distributi... | <|body_start_0|>
if Config.validation:
print('Skipping empirical distribution in validation run')
self.distribution = zeros((313,))
return
print('Finding empirical color distribution...')
self.distribution = generator.get_bin_counts()
self.distribution... | ColorfulLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorfulLoss:
def __init__(self, generator: BinnedImageGenerator, mix=0.5):
"""Find empirical color distribution in dataset"""
<|body_0|>
def get_loss(self):
"""Returns cross entropy between two distributions, balances classes using the saved distribution. :param mix... | stack_v2_sparse_classes_36k_train_007177 | 2,072 | no_license | [
{
"docstring": "Find empirical color distribution in dataset",
"name": "__init__",
"signature": "def __init__(self, generator: BinnedImageGenerator, mix=0.5)"
},
{
"docstring": "Returns cross entropy between two distributions, balances classes using the saved distribution. :param mix: How much o... | 2 | stack_v2_sparse_classes_30k_train_014016 | Implement the Python class `ColorfulLoss` described below.
Class description:
Implement the ColorfulLoss class.
Method signatures and docstrings:
- def __init__(self, generator: BinnedImageGenerator, mix=0.5): Find empirical color distribution in dataset
- def get_loss(self): Returns cross entropy between two distrib... | Implement the Python class `ColorfulLoss` described below.
Class description:
Implement the ColorfulLoss class.
Method signatures and docstrings:
- def __init__(self, generator: BinnedImageGenerator, mix=0.5): Find empirical color distribution in dataset
- def get_loss(self): Returns cross entropy between two distrib... | 5bdeeaeeaea5c0cfbca224ccbcf4134179b46e35 | <|skeleton|>
class ColorfulLoss:
def __init__(self, generator: BinnedImageGenerator, mix=0.5):
"""Find empirical color distribution in dataset"""
<|body_0|>
def get_loss(self):
"""Returns cross entropy between two distributions, balances classes using the saved distribution. :param mix... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColorfulLoss:
def __init__(self, generator: BinnedImageGenerator, mix=0.5):
"""Find empirical color distribution in dataset"""
if Config.validation:
print('Skipping empirical distribution in validation run')
self.distribution = zeros((313,))
return
p... | the_stack_v2_python_sparse | src/colorful_loss.py | flostellbrink/ColorfulCoherence | train | 0 | |
360d109e764ead839b15e772f7f034d271543b6c | [
"serializer = self.get_serializer(data=self.clean_data(request.data))\nserializer.is_valid(raise_exception=True)\nself.perform_create(serializer)\nheaders = self.get_success_headers(serializer.data)\nreturn Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)",
"partial = kwargs.pop('partial... | <|body_start_0|>
serializer = self.get_serializer(data=self.clean_data(request.data))
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, hea... | Model mixin class which cleans inputs using the Mozilla bleach tools. | CleanMixin | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CleanMixin:
"""Model mixin class which cleans inputs using the Mozilla bleach tools."""
def create(self, request, *args, **kwargs):
"""Override to clean data before processing it."""
<|body_0|>
def update(self, request, *args, **kwargs):
"""Override to clean data... | stack_v2_sparse_classes_36k_train_007178 | 6,138 | permissive | [
{
"docstring": "Override to clean data before processing it.",
"name": "create",
"signature": "def create(self, request, *args, **kwargs)"
},
{
"docstring": "Override to clean data before processing it.",
"name": "update",
"signature": "def update(self, request, *args, **kwargs)"
},
... | 4 | stack_v2_sparse_classes_30k_val_000705 | Implement the Python class `CleanMixin` described below.
Class description:
Model mixin class which cleans inputs using the Mozilla bleach tools.
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): Override to clean data before processing it.
- def update(self, request, *args, **kwargs): O... | Implement the Python class `CleanMixin` described below.
Class description:
Model mixin class which cleans inputs using the Mozilla bleach tools.
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): Override to clean data before processing it.
- def update(self, request, *args, **kwargs): O... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class CleanMixin:
"""Model mixin class which cleans inputs using the Mozilla bleach tools."""
def create(self, request, *args, **kwargs):
"""Override to clean data before processing it."""
<|body_0|>
def update(self, request, *args, **kwargs):
"""Override to clean data... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CleanMixin:
"""Model mixin class which cleans inputs using the Mozilla bleach tools."""
def create(self, request, *args, **kwargs):
"""Override to clean data before processing it."""
serializer = self.get_serializer(data=self.clean_data(request.data))
serializer.is_valid(raise_exc... | the_stack_v2_python_sparse | InvenTree/InvenTree/mixins.py | inventree/InvenTree | train | 3,077 |
f8b140da34b16442a8140e2f9d54191bd6efdd36 | [
"datasets = handler_get_request(request)\nfor dataset in datasets:\n if dataset.slug == dataset_name:\n return JsonResponse(serialize(dataset), safe=True)\nraise Http404()",
"request.PUT, request._files = parse_request(request)\nrequest.PUT._mutable = True\ntry:\n handle_pust_request(request, dataset... | <|body_start_0|>
datasets = handler_get_request(request)
for dataset in datasets:
if dataset.slug == dataset_name:
return JsonResponse(serialize(dataset), safe=True)
raise Http404()
<|end_body_0|>
<|body_start_1|>
request.PUT, request._files = parse_request(r... | DatasetShow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetShow:
def get(self, request, dataset_name):
"""Voir le jeu de données."""
<|body_0|>
def put(self, request, dataset_name):
"""Modifier le jeu de données."""
<|body_1|>
def delete(self, request, dataset_name):
"""Supprimer le jeu de données... | stack_v2_sparse_classes_36k_train_007179 | 14,797 | permissive | [
{
"docstring": "Voir le jeu de données.",
"name": "get",
"signature": "def get(self, request, dataset_name)"
},
{
"docstring": "Modifier le jeu de données.",
"name": "put",
"signature": "def put(self, request, dataset_name)"
},
{
"docstring": "Supprimer le jeu de données.",
"... | 3 | null | Implement the Python class `DatasetShow` described below.
Class description:
Implement the DatasetShow class.
Method signatures and docstrings:
- def get(self, request, dataset_name): Voir le jeu de données.
- def put(self, request, dataset_name): Modifier le jeu de données.
- def delete(self, request, dataset_name):... | Implement the Python class `DatasetShow` described below.
Class description:
Implement the DatasetShow class.
Method signatures and docstrings:
- def get(self, request, dataset_name): Voir le jeu de données.
- def put(self, request, dataset_name): Modifier le jeu de données.
- def delete(self, request, dataset_name):... | c73e67f22fa9bb38577c286271d02c2d9a708e40 | <|skeleton|>
class DatasetShow:
def get(self, request, dataset_name):
"""Voir le jeu de données."""
<|body_0|>
def put(self, request, dataset_name):
"""Modifier le jeu de données."""
<|body_1|>
def delete(self, request, dataset_name):
"""Supprimer le jeu de données... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatasetShow:
def get(self, request, dataset_name):
"""Voir le jeu de données."""
datasets = handler_get_request(request)
for dataset in datasets:
if dataset.slug == dataset_name:
return JsonResponse(serialize(dataset), safe=True)
raise Http404()
... | the_stack_v2_python_sparse | api/views/dataset.py | DataSud/DataSud-2017-2019 | train | 1 | |
469dc907ff57a759cd6bd5064b8344459de55089 | [
"super().__init__(fmc, **kwargs)\nlogging.debug('In __init__() for IKESettings class.')\nself.parse_kwargs(**kwargs)\nself.type = 'IKESetting'",
"logging.debug('In vpn_policy() for IKESettings class.')\nftd_s2s = FTDS2SVPNs(fmc=self.fmc)\nftd_s2s.get(name=pol_name)\nif 'id' in ftd_s2s.__dict__:\n self.vpn_id =... | <|body_start_0|>
super().__init__(fmc, **kwargs)
logging.debug('In __init__() for IKESettings class.')
self.parse_kwargs(**kwargs)
self.type = 'IKESetting'
<|end_body_0|>
<|body_start_1|>
logging.debug('In vpn_policy() for IKESettings class.')
ftd_s2s = FTDS2SVPNs(fmc=se... | The IKESettings Object in the FMC. | IKESettings | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IKESettings:
"""The IKESettings Object in the FMC."""
def __init__(self, fmc, **kwargs):
"""Initialize IKESettings object. Set self.type to "IKESetting", parse the kwargs, and set up the self.URL. :param fmc (object): FMC object :param **kwargs: Any other values passed during instant... | stack_v2_sparse_classes_36k_train_007180 | 4,268 | permissive | [
{
"docstring": "Initialize IKESettings object. Set self.type to \"IKESetting\", parse the kwargs, and set up the self.URL. :param fmc (object): FMC object :param **kwargs: Any other values passed during instantiation. :return: None",
"name": "__init__",
"signature": "def __init__(self, fmc, **kwargs)"
... | 4 | null | Implement the Python class `IKESettings` described below.
Class description:
The IKESettings Object in the FMC.
Method signatures and docstrings:
- def __init__(self, fmc, **kwargs): Initialize IKESettings object. Set self.type to "IKESetting", parse the kwargs, and set up the self.URL. :param fmc (object): FMC objec... | Implement the Python class `IKESettings` described below.
Class description:
The IKESettings Object in the FMC.
Method signatures and docstrings:
- def __init__(self, fmc, **kwargs): Initialize IKESettings object. Set self.type to "IKESetting", parse the kwargs, and set up the self.URL. :param fmc (object): FMC objec... | fd924de96e200ca8e0d5088b27a5abaf6f915bc6 | <|skeleton|>
class IKESettings:
"""The IKESettings Object in the FMC."""
def __init__(self, fmc, **kwargs):
"""Initialize IKESettings object. Set self.type to "IKESetting", parse the kwargs, and set up the self.URL. :param fmc (object): FMC object :param **kwargs: Any other values passed during instant... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IKESettings:
"""The IKESettings Object in the FMC."""
def __init__(self, fmc, **kwargs):
"""Initialize IKESettings object. Set self.type to "IKESetting", parse the kwargs, and set up the self.URL. :param fmc (object): FMC object :param **kwargs: Any other values passed during instantiation. :retu... | the_stack_v2_python_sparse | fmcapi/api_objects/policy_services/ikesettings.py | banzigaga/fmcapi | train | 1 |
720aecda378d1113a0aad723bf7d2fe6fb5d350d | [
"if not root:\n return []\nres = []\nif root.left:\n res += self.postorderTraversal1(root.left)\nif root.right:\n res += self.postorderTraversal1(root.right)\nres.append(root.val)\nreturn res",
"if not root:\n return []\nres = []\nstack = [(root, False)]\nwhile stack:\n node, visited = stack.pop()\... | <|body_start_0|>
if not root:
return []
res = []
if root.left:
res += self.postorderTraversal1(root.left)
if root.right:
res += self.postorderTraversal1(root.right)
res.append(root.val)
return res
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def postorderTraversal1(self, root: TreeNode) -> List[int]:
"""递归"""
<|body_0|>
def postorderTraversal2(self, root: TreeNode) -> List[int]:
"""迭代"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return []
re... | stack_v2_sparse_classes_36k_train_007181 | 1,598 | no_license | [
{
"docstring": "递归",
"name": "postorderTraversal1",
"signature": "def postorderTraversal1(self, root: TreeNode) -> List[int]"
},
{
"docstring": "迭代",
"name": "postorderTraversal2",
"signature": "def postorderTraversal2(self, root: TreeNode) -> List[int]"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorderTraversal1(self, root: TreeNode) -> List[int]: 递归
- def postorderTraversal2(self, root: TreeNode) -> List[int]: 迭代 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorderTraversal1(self, root: TreeNode) -> List[int]: 递归
- def postorderTraversal2(self, root: TreeNode) -> List[int]: 迭代
<|skeleton|>
class Solution:
def postorderTr... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def postorderTraversal1(self, root: TreeNode) -> List[int]:
"""递归"""
<|body_0|>
def postorderTraversal2(self, root: TreeNode) -> List[int]:
"""迭代"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def postorderTraversal1(self, root: TreeNode) -> List[int]:
"""递归"""
if not root:
return []
res = []
if root.left:
res += self.postorderTraversal1(root.left)
if root.right:
res += self.postorderTraversal1(root.right)
... | the_stack_v2_python_sparse | 145_binary-tree-postorder-traversal.py | helloocc/algorithm | train | 1 | |
2f873c90398b72884e171a15b29992a4901d405a | [
"verify_snapshot_list(slo)\nself.snapshot_list = slo\nself.client = slo.client\nself.retry_interval = retry_interval\nself.retry_count = retry_count\nself.repository = slo.repository\nself.loggit = logging.getLogger('curator.actions.delete_snapshots')",
"self.loggit.info('DRY-RUN MODE. No changes will be made.')... | <|body_start_0|>
verify_snapshot_list(slo)
self.snapshot_list = slo
self.client = slo.client
self.retry_interval = retry_interval
self.retry_count = retry_count
self.repository = slo.repository
self.loggit = logging.getLogger('curator.actions.delete_snapshots')
<|... | Delete Snapshots Action Class | DeleteSnapshots | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteSnapshots:
"""Delete Snapshots Action Class"""
def __init__(self, slo, retry_interval=120, retry_count=3):
""":param slo: A SnapshotList object :type slo: :py:class:`~.curator.snapshotlist.SnapshotList` :param retry_interval: Seconds to delay betwen retries. (Default: ``120``) ... | stack_v2_sparse_classes_36k_train_007182 | 21,632 | permissive | [
{
"docstring": ":param slo: A SnapshotList object :type slo: :py:class:`~.curator.snapshotlist.SnapshotList` :param retry_interval: Seconds to delay betwen retries. (Default: ``120``) :type retry_interval: int :param retry_count: Number of attempts to make. (Default: ``3``) :type retry_count: int",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_007150 | Implement the Python class `DeleteSnapshots` described below.
Class description:
Delete Snapshots Action Class
Method signatures and docstrings:
- def __init__(self, slo, retry_interval=120, retry_count=3): :param slo: A SnapshotList object :type slo: :py:class:`~.curator.snapshotlist.SnapshotList` :param retry_inter... | Implement the Python class `DeleteSnapshots` described below.
Class description:
Delete Snapshots Action Class
Method signatures and docstrings:
- def __init__(self, slo, retry_interval=120, retry_count=3): :param slo: A SnapshotList object :type slo: :py:class:`~.curator.snapshotlist.SnapshotList` :param retry_inter... | b41743a061ad790820affe7acee5f71abe819357 | <|skeleton|>
class DeleteSnapshots:
"""Delete Snapshots Action Class"""
def __init__(self, slo, retry_interval=120, retry_count=3):
""":param slo: A SnapshotList object :type slo: :py:class:`~.curator.snapshotlist.SnapshotList` :param retry_interval: Seconds to delay betwen retries. (Default: ``120``) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteSnapshots:
"""Delete Snapshots Action Class"""
def __init__(self, slo, retry_interval=120, retry_count=3):
""":param slo: A SnapshotList object :type slo: :py:class:`~.curator.snapshotlist.SnapshotList` :param retry_interval: Seconds to delay betwen retries. (Default: ``120``) :type retry_i... | the_stack_v2_python_sparse | curator/actions/snapshot.py | volatilemolotov/curator | train | 0 |
7568adfd3092d11983bb1a07fc46df6a80aaed44 | [
"theKeys = HashSet()\nfor game in File('games/test').listFiles():\n if not game.__name__.endsWith('.kif'):\n continue\n theKeys.add(game.__name__.replace('.kif', ''))\nreturn theKeys",
"try:\n return Game.createEphemeralGame(Game.preprocessRulesheet(FileUtils.readFileAsString(File('games/test/' + ... | <|body_start_0|>
theKeys = HashSet()
for game in File('games/test').listFiles():
if not game.__name__.endsWith('.kif'):
continue
theKeys.add(game.__name__.replace('.kif', ''))
return theKeys
<|end_body_0|>
<|body_start_1|>
try:
return ... | generated source for class TestGameRepository | TestGameRepository | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGameRepository:
"""generated source for class TestGameRepository"""
def getUncachedGameKeys(self):
"""generated source for method getUncachedGameKeys"""
<|body_0|>
def getUncachedGame(self, theKey):
"""generated source for method getUncachedGame"""
<|... | stack_v2_sparse_classes_36k_train_007183 | 1,170 | permissive | [
{
"docstring": "generated source for method getUncachedGameKeys",
"name": "getUncachedGameKeys",
"signature": "def getUncachedGameKeys(self)"
},
{
"docstring": "generated source for method getUncachedGame",
"name": "getUncachedGame",
"signature": "def getUncachedGame(self, theKey)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014682 | Implement the Python class `TestGameRepository` described below.
Class description:
generated source for class TestGameRepository
Method signatures and docstrings:
- def getUncachedGameKeys(self): generated source for method getUncachedGameKeys
- def getUncachedGame(self, theKey): generated source for method getUncac... | Implement the Python class `TestGameRepository` described below.
Class description:
generated source for class TestGameRepository
Method signatures and docstrings:
- def getUncachedGameKeys(self): generated source for method getUncachedGameKeys
- def getUncachedGame(self, theKey): generated source for method getUncac... | 4e6e6e876c3a4294cd711647051da2d9c1836b60 | <|skeleton|>
class TestGameRepository:
"""generated source for class TestGameRepository"""
def getUncachedGameKeys(self):
"""generated source for method getUncachedGameKeys"""
<|body_0|>
def getUncachedGame(self, theKey):
"""generated source for method getUncachedGame"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestGameRepository:
"""generated source for class TestGameRepository"""
def getUncachedGameKeys(self):
"""generated source for method getUncachedGameKeys"""
theKeys = HashSet()
for game in File('games/test').listFiles():
if not game.__name__.endsWith('.kif'):
... | the_stack_v2_python_sparse | ggpy/cruft/autocode/TestGameRepository.py | hobson/ggpy | train | 1 |
0e57fd3b6d5613145c0b1d11b7b9b2aa8bf0ece6 | [
"name = name.strip()\nassert name\nself.name = name\nactionInstances = []\nfor action in actions:\n if isinstance(action, (MenuAction, _MenuSeparator)):\n actionInstances.append(action)\n elif isclass(action) and (action is _MenuSeparator or issubclass(action, MenuAction)):\n actionInstances.app... | <|body_start_0|>
name = name.strip()
assert name
self.name = name
actionInstances = []
for action in actions:
if isinstance(action, (MenuAction, _MenuSeparator)):
actionInstances.append(action)
elif isclass(action) and (action is _MenuSepar... | Container class for a menu definition. | MenuBuilder | [
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuBuilder:
"""Container class for a menu definition."""
def __init__(self, name, actions):
"""Parameters ---------- name : str actions : List[Union[MenuAction, Type[MenuAction]]]"""
<|body_0|>
def Build(self, context, contextCallback=None, parent=None):
"""Buil... | stack_v2_sparse_classes_36k_train_007184 | 14,708 | permissive | [
{
"docstring": "Parameters ---------- name : str actions : List[Union[MenuAction, Type[MenuAction]]]",
"name": "__init__",
"signature": "def __init__(self, name, actions)"
},
{
"docstring": "Build and return a new `QMenu` instance using the current list of actions and the given context, and pare... | 2 | stack_v2_sparse_classes_30k_train_006749 | Implement the Python class `MenuBuilder` described below.
Class description:
Container class for a menu definition.
Method signatures and docstrings:
- def __init__(self, name, actions): Parameters ---------- name : str actions : List[Union[MenuAction, Type[MenuAction]]]
- def Build(self, context, contextCallback=Non... | Implement the Python class `MenuBuilder` described below.
Class description:
Container class for a menu definition.
Method signatures and docstrings:
- def __init__(self, name, actions): Parameters ---------- name : str actions : List[Union[MenuAction, Type[MenuAction]]]
- def Build(self, context, contextCallback=Non... | 58dad9ee9dd754c0b22fa986724aace9b3e8b5b9 | <|skeleton|>
class MenuBuilder:
"""Container class for a menu definition."""
def __init__(self, name, actions):
"""Parameters ---------- name : str actions : List[Union[MenuAction, Type[MenuAction]]]"""
<|body_0|>
def Build(self, context, contextCallback=None, parent=None):
"""Buil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MenuBuilder:
"""Container class for a menu definition."""
def __init__(self, name, actions):
"""Parameters ---------- name : str actions : List[Union[MenuAction, Type[MenuAction]]]"""
name = name.strip()
assert name
self.name = name
actionInstances = []
for... | the_stack_v2_python_sparse | pxr/usdQt/qtUtils.py | LumaPictures/usd-qt | train | 151 |
4c070fd6231594ad35bbffc1ec40db8be72e6359 | [
"if g.current_ticket.user != current_user and (not current_user.has_permission(models.Group.HOSTS)):\n response = make_response('Not authorised', 401)\n return response\nopts = g.current_game.game_options(g.current_options)\noptions = Options(**opts)\noptions.checkbox = True\noptions.title = g.current_game.ti... | <|body_start_0|>
if g.current_ticket.user != current_user and (not current_user.has_permission(models.Group.HOSTS)):
response = make_response('Not authorised', 401)
return response
opts = g.current_game.game_options(g.current_options)
options = Options(**opts)
opt... | Allows a Bingo ticket to be downloaded as a PDF file | DownloadTicketView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownloadTicketView:
"""Allows a Bingo ticket to be downloaded as a PDF file"""
def get(self, **kwargs):
"""get a Bingo ticket as a PDF file"""
<|body_0|>
def create_pdf(options: Options, ticket: BingoTicket, tmpdirname: Path) -> Path:
"""Create a PDF file in the ... | stack_v2_sparse_classes_36k_train_007185 | 5,882 | no_license | [
{
"docstring": "get a Bingo ticket as a PDF file",
"name": "get",
"signature": "def get(self, **kwargs)"
},
{
"docstring": "Create a PDF file in the specified temporary directory",
"name": "create_pdf",
"signature": "def create_pdf(options: Options, ticket: BingoTicket, tmpdirname: Path)... | 2 | null | Implement the Python class `DownloadTicketView` described below.
Class description:
Allows a Bingo ticket to be downloaded as a PDF file
Method signatures and docstrings:
- def get(self, **kwargs): get a Bingo ticket as a PDF file
- def create_pdf(options: Options, ticket: BingoTicket, tmpdirname: Path) -> Path: Crea... | Implement the Python class `DownloadTicketView` described below.
Class description:
Allows a Bingo ticket to be downloaded as a PDF file
Method signatures and docstrings:
- def get(self, **kwargs): get a Bingo ticket as a PDF file
- def create_pdf(options: Options, ticket: BingoTicket, tmpdirname: Path) -> Path: Crea... | f49d26900a10593a6f993b82d8d782b2e7367f84 | <|skeleton|>
class DownloadTicketView:
"""Allows a Bingo ticket to be downloaded as a PDF file"""
def get(self, **kwargs):
"""get a Bingo ticket as a PDF file"""
<|body_0|>
def create_pdf(options: Options, ticket: BingoTicket, tmpdirname: Path) -> Path:
"""Create a PDF file in the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DownloadTicketView:
"""Allows a Bingo ticket to be downloaded as a PDF file"""
def get(self, **kwargs):
"""get a Bingo ticket as a PDF file"""
if g.current_ticket.user != current_user and (not current_user.has_permission(models.Group.HOSTS)):
response = make_response('Not auth... | the_stack_v2_python_sparse | musicbingo/server/views.py | asrashley/music-bingo | train | 1 |
59d390bedaea571ff416b52b9fedd3176ddf4b71 | [
"crypto_conf = config.get_module_config('crypto')\nplugin_names = self._get_internal_plugin_names(crypto_conf)\nsuper(_CryptoPluginManager, self).__init__(crypto_conf.crypto.namespace, plugin_names, invoke_on_load=False, invoke_args=invoke_args, invoke_kwds=invoke_kwargs, name_order=True)\nplugin_utils.instantiate_... | <|body_start_0|>
crypto_conf = config.get_module_config('crypto')
plugin_names = self._get_internal_plugin_names(crypto_conf)
super(_CryptoPluginManager, self).__init__(crypto_conf.crypto.namespace, plugin_names, invoke_on_load=False, invoke_args=invoke_args, invoke_kwds=invoke_kwargs, name_orde... | _CryptoPluginManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _CryptoPluginManager:
def __init__(self, conf=CONF, invoke_args=(), invoke_kwargs={}):
"""Crypto Plugin Manager Each time this class is initialized it will load a new instance of each enabled crypto plugin. This is undesirable, so rather than initializing a new instance of this class use... | stack_v2_sparse_classes_36k_train_007186 | 6,147 | permissive | [
{
"docstring": "Crypto Plugin Manager Each time this class is initialized it will load a new instance of each enabled crypto plugin. This is undesirable, so rather than initializing a new instance of this class use the PLUGIN_MANAGER at the module level.",
"name": "__init__",
"signature": "def __init__(... | 4 | null | Implement the Python class `_CryptoPluginManager` described below.
Class description:
Implement the _CryptoPluginManager class.
Method signatures and docstrings:
- def __init__(self, conf=CONF, invoke_args=(), invoke_kwargs={}): Crypto Plugin Manager Each time this class is initialized it will load a new instance of ... | Implement the Python class `_CryptoPluginManager` described below.
Class description:
Implement the _CryptoPluginManager class.
Method signatures and docstrings:
- def __init__(self, conf=CONF, invoke_args=(), invoke_kwargs={}): Crypto Plugin Manager Each time this class is initialized it will load a new instance of ... | c8e3dc14e6225f1d400131434e8afec0aa410ae7 | <|skeleton|>
class _CryptoPluginManager:
def __init__(self, conf=CONF, invoke_args=(), invoke_kwargs={}):
"""Crypto Plugin Manager Each time this class is initialized it will load a new instance of each enabled crypto plugin. This is undesirable, so rather than initializing a new instance of this class use... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _CryptoPluginManager:
def __init__(self, conf=CONF, invoke_args=(), invoke_kwargs={}):
"""Crypto Plugin Manager Each time this class is initialized it will load a new instance of each enabled crypto plugin. This is undesirable, so rather than initializing a new instance of this class use the PLUGIN_MA... | the_stack_v2_python_sparse | barbican/plugin/crypto/manager.py | openstack/barbican | train | 189 | |
1bb9db5eb0f6d75336bbc4809832f4967405ae92 | [
"try:\n release = Release.objects.get(organization_id=project.organization_id, projects=project, version=version)\nexcept Release.DoesNotExist:\n raise ResourceDoesNotExist\nreturn self.get_releasefile(request, release, file_id, check_permission_fn=lambda: has_download_permission(request, project))",
"try:\... | <|body_start_0|>
try:
release = Release.objects.get(organization_id=project.organization_id, projects=project, version=version)
except Release.DoesNotExist:
raise ResourceDoesNotExist
return self.get_releasefile(request, release, file_id, check_permission_fn=lambda: has_d... | ProjectReleaseFileDetailsEndpoint | [
"Apache-2.0",
"BUSL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectReleaseFileDetailsEndpoint:
def get(self, request: Request, project, version, file_id) -> Response:
"""Retrieve a Project Release's File ````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file,... | stack_v2_sparse_classes_36k_train_007187 | 10,538 | permissive | [
{
"docstring": "Retrieve a Project Release's File ````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file, just the associated metadata. :pparam string organization_slug: the slug of the organization the release belongs to. ... | 3 | stack_v2_sparse_classes_30k_train_012391 | Implement the Python class `ProjectReleaseFileDetailsEndpoint` described below.
Class description:
Implement the ProjectReleaseFileDetailsEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, project, version, file_id) -> Response: Retrieve a Project Release's File ``````````````````````... | Implement the Python class `ProjectReleaseFileDetailsEndpoint` described below.
Class description:
Implement the ProjectReleaseFileDetailsEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, project, version, file_id) -> Response: Retrieve a Project Release's File ``````````````````````... | d9dd4f382f96b5c4576b64cbf015db651556c18b | <|skeleton|>
class ProjectReleaseFileDetailsEndpoint:
def get(self, request: Request, project, version, file_id) -> Response:
"""Retrieve a Project Release's File ````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectReleaseFileDetailsEndpoint:
def get(self, request: Request, project, version, file_id) -> Response:
"""Retrieve a Project Release's File ````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file, just the asso... | the_stack_v2_python_sparse | src/sentry/api/endpoints/project_release_file_details.py | nagyist/sentry | train | 0 | |
597af2f7e4854d6bcc87f39f33903b4d05761478 | [
"if len(self._tags) < 1:\n return True\nelse:\n return False",
"self._create_debug_info('Parse tag definitions ...')\nwhile not self._end_reached:\n self._parse_tag_definitions()\n if self._parser.has_errors():\n break\n self._step_to_next_row()",
"container = ExcelMoleculeDesignPoolLayout... | <|body_start_0|>
if len(self._tags) < 1:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
self._create_debug_info('Parse tag definitions ...')
while not self._end_reached:
self._parse_tag_definitions()
if self._parser.has_err... | ParsingContainer subclass performing the single steps of the parsing and storing the intermediate information of an Excel sheet. The data is passed back to the parser as soon it is in a hierarchy that can be used for the creation of a experiment design object. | _ExperimentDesignSheetParsingContainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ExperimentDesignSheetParsingContainer:
"""ParsingContainer subclass performing the single steps of the parsing and storing the intermediate information of an Excel sheet. The data is passed back to the parser as soon it is in a hierarchy that can be used for the creation of a experiment design o... | stack_v2_sparse_classes_36k_train_007188 | 13,192 | permissive | [
{
"docstring": "If there are no tag definitions in the container, it is considered as empty.",
"name": "is_empty",
"signature": "def is_empty(self)"
},
{
"docstring": "Parses tags, values and codes (including associated tags) of a sheet and stores them as TagParsingContainer objects in the tags ... | 6 | stack_v2_sparse_classes_30k_val_001120 | Implement the Python class `_ExperimentDesignSheetParsingContainer` described below.
Class description:
ParsingContainer subclass performing the single steps of the parsing and storing the intermediate information of an Excel sheet. The data is passed back to the parser as soon it is in a hierarchy that can be used fo... | Implement the Python class `_ExperimentDesignSheetParsingContainer` described below.
Class description:
ParsingContainer subclass performing the single steps of the parsing and storing the intermediate information of an Excel sheet. The data is passed back to the parser as soon it is in a hierarchy that can be used fo... | d2dc7a478ee5d24ccf3cc680888e712d482321d0 | <|skeleton|>
class _ExperimentDesignSheetParsingContainer:
"""ParsingContainer subclass performing the single steps of the parsing and storing the intermediate information of an Excel sheet. The data is passed back to the parser as soon it is in a hierarchy that can be used for the creation of a experiment design o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _ExperimentDesignSheetParsingContainer:
"""ParsingContainer subclass performing the single steps of the parsing and storing the intermediate information of an Excel sheet. The data is passed back to the parser as soon it is in a hierarchy that can be used for the creation of a experiment design object."""
... | the_stack_v2_python_sparse | thelma/tools/parsers/experimentdesign.py | papagr/TheLMA | train | 1 |
bb003d516105792ed8a10df40845499e9ef8b639 | [
"io.logger.debug('FarFieldIntensity forward 1')\nwave_shifted = wave.ifftshift((3, 4))\nwave_farfield = wave_shifted.fft2_()\nctx.wave_farfield = wave_farfield\nctx.gradient_mask = gradient_mask\nI_model = th.cuda.FloatTensor(wave.size())\nwave_farfield.expect(out=I_model)\nfor dim in range(1, I_model.ndimension() ... | <|body_start_0|>
io.logger.debug('FarFieldIntensity forward 1')
wave_shifted = wave.ifftshift((3, 4))
wave_farfield = wave_shifted.fft2_()
ctx.wave_farfield = wave_farfield
ctx.gradient_mask = gradient_mask
I_model = th.cuda.FloatTensor(wave.size())
wave_farfield.... | FarFieldIntensityNoSubpixel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FarFieldIntensityNoSubpixel:
def forward(ctx, wave, gradient_mask):
"""Parameters ---------- wave : dimension: K, N_p, N_o, M1, M2 Returns ------- I_model : dimension: K, M1, M2 float tensor diffraction intensities"""
<|body_0|>
def backward(ctx, grad_output):
"""bac... | stack_v2_sparse_classes_36k_train_007189 | 2,707 | permissive | [
{
"docstring": "Parameters ---------- wave : dimension: K, N_p, N_o, M1, M2 Returns ------- I_model : dimension: K, M1, M2 float tensor diffraction intensities",
"name": "forward",
"signature": "def forward(ctx, wave, gradient_mask)"
},
{
"docstring": "backward. Parameters ---------- grad_output... | 2 | stack_v2_sparse_classes_30k_train_011877 | Implement the Python class `FarFieldIntensityNoSubpixel` described below.
Class description:
Implement the FarFieldIntensityNoSubpixel class.
Method signatures and docstrings:
- def forward(ctx, wave, gradient_mask): Parameters ---------- wave : dimension: K, N_p, N_o, M1, M2 Returns ------- I_model : dimension: K, M... | Implement the Python class `FarFieldIntensityNoSubpixel` described below.
Class description:
Implement the FarFieldIntensityNoSubpixel class.
Method signatures and docstrings:
- def forward(ctx, wave, gradient_mask): Parameters ---------- wave : dimension: K, N_p, N_o, M1, M2 Returns ------- I_model : dimension: K, M... | 50833b13160b6afe0a743d63d560bddeee2c18b5 | <|skeleton|>
class FarFieldIntensityNoSubpixel:
def forward(ctx, wave, gradient_mask):
"""Parameters ---------- wave : dimension: K, N_p, N_o, M1, M2 Returns ------- I_model : dimension: K, M1, M2 float tensor diffraction intensities"""
<|body_0|>
def backward(ctx, grad_output):
"""bac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FarFieldIntensityNoSubpixel:
def forward(ctx, wave, gradient_mask):
"""Parameters ---------- wave : dimension: K, N_p, N_o, M1, M2 Returns ------- I_model : dimension: K, M1, M2 float tensor diffraction intensities"""
io.logger.debug('FarFieldIntensity forward 1')
wave_shifted = wave.i... | the_stack_v2_python_sparse | skpr/nn/_functions/FarfieldIntensityNoSubpixel.py | 1034776739/scikit-pr-open | train | 0 | |
2519e1703ef84943371b66707ded39c477ec4a9e | [
"if not isinstance(origin, math3d.VectorN) or not isinstance(direction, math3d.VectorN) or len(origin) != len(direction):\n raise ValueError(\"You must pass two equal-dimension VectorN's for the origin and direction.\")\nself.mOrigin = origin.copy()\nself.mDirection = direction.normalized()",
"if not isinstanc... | <|body_start_0|>
if not isinstance(origin, math3d.VectorN) or not isinstance(direction, math3d.VectorN) or len(origin) != len(direction):
raise ValueError("You must pass two equal-dimension VectorN's for the origin and direction.")
self.mOrigin = origin.copy()
self.mDirection = direc... | An n-dimensional ray [by definition a ray is an origin point and a direction | Ray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ray:
"""An n-dimensional ray [by definition a ray is an origin point and a direction"""
def __init__(self, origin, direction):
""":param origin: the origin POSITION of the ray (a copy of the passed vector is created) :param direction: the DIRECTION of the ray (the vector passed in is... | stack_v2_sparse_classes_36k_train_007190 | 10,671 | no_license | [
{
"docstring": ":param origin: the origin POSITION of the ray (a copy of the passed vector is created) :param direction: the DIRECTION of the ray (the vector passed in is normalized) :return: N/A",
"name": "__init__",
"signature": "def __init__(self, origin, direction)"
},
{
"docstring": ":param... | 4 | stack_v2_sparse_classes_30k_train_012991 | Implement the Python class `Ray` described below.
Class description:
An n-dimensional ray [by definition a ray is an origin point and a direction
Method signatures and docstrings:
- def __init__(self, origin, direction): :param origin: the origin POSITION of the ray (a copy of the passed vector is created) :param dir... | Implement the Python class `Ray` described below.
Class description:
An n-dimensional ray [by definition a ray is an origin point and a direction
Method signatures and docstrings:
- def __init__(self, origin, direction): :param origin: the origin POSITION of the ray (a copy of the passed vector is created) :param dir... | 5916caa83fd57fd1400875d74ffff8e89b7bb0bc | <|skeleton|>
class Ray:
"""An n-dimensional ray [by definition a ray is an origin point and a direction"""
def __init__(self, origin, direction):
""":param origin: the origin POSITION of the ray (a copy of the passed vector is created) :param direction: the DIRECTION of the ray (the vector passed in is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ray:
"""An n-dimensional ray [by definition a ray is an origin point and a direction"""
def __init__(self, origin, direction):
""":param origin: the origin POSITION of the ray (a copy of the passed vector is created) :param direction: the DIRECTION of the ray (the vector passed in is normalized) ... | the_stack_v2_python_sparse | ConceptsOf3DGraphics/Lab05/objects3d.py | kjakar/Portfolio | train | 0 |
41f7236628f72809948a866c358cfebb2f68adf0 | [
"connector_config = ConnectorConfig(**config)\ntry:\n aws_handler = AwsHandler(connector_config, self)\nexcept ClientError as e:\n self.logger.error(f'Could not create session due to exception {repr(e)}')\n raise\nself.logger.debug('AWS session creation OK')\nstreams = {s.stream.name: StreamWriter(name=s.s... | <|body_start_0|>
connector_config = ConnectorConfig(**config)
try:
aws_handler = AwsHandler(connector_config, self)
except ClientError as e:
self.logger.error(f'Could not create session due to exception {repr(e)}')
raise
self.logger.debug('AWS session ... | DestinationAwsDatalake | [
"MIT",
"Elastic-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DestinationAwsDatalake:
def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]:
"""Reads the input stream of messages, config, and catalog to write data to the destination. This method... | stack_v2_sparse_classes_36k_train_007191 | 5,313 | permissive | [
{
"docstring": "Reads the input stream of messages, config, and catalog to write data to the destination. This method returns an iterable (typically a generator of AirbyteMessages via yield) containing state messages received in the input message stream. Outputting a state message means that every AirbyteRecord... | 2 | null | Implement the Python class `DestinationAwsDatalake` described below.
Class description:
Implement the DestinationAwsDatalake class.
Method signatures and docstrings:
- def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[Airbyte... | Implement the Python class `DestinationAwsDatalake` described below.
Class description:
Implement the DestinationAwsDatalake class.
Method signatures and docstrings:
- def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[Airbyte... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class DestinationAwsDatalake:
def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]:
"""Reads the input stream of messages, config, and catalog to write data to the destination. This method... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DestinationAwsDatalake:
def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]:
"""Reads the input stream of messages, config, and catalog to write data to the destination. This method returns an it... | the_stack_v2_python_sparse | dts/airbyte/airbyte-integrations/connectors/destination-aws-datalake/destination_aws_datalake/destination.py | alldatacenter/alldata | train | 774 | |
2f850c47dfd5cfacf69e39833222a8f414afc621 | [
"self.A = A\nself.count_index = 0\nself.num_index = 1",
"if self.count_index >= len(self.A) - 1:\n return -1\nif n == 0:\n return self.A[self.count_index + 1]\nwhile self.count_index < len(self.A) and self.A[self.count_index] < n:\n n -= self.A[self.count_index]\n self.count_index += 2\nif self.count_... | <|body_start_0|>
self.A = A
self.count_index = 0
self.num_index = 1
<|end_body_0|>
<|body_start_1|>
if self.count_index >= len(self.A) - 1:
return -1
if n == 0:
return self.A[self.count_index + 1]
while self.count_index < len(self.A) and self.A[se... | RLEIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.A = A
self.count_index = 0
self.num_index = 1
<|end_body_0|>
... | stack_v2_sparse_classes_36k_train_007192 | 885 | no_license | [
{
"docstring": ":type A: List[int]",
"name": "__init__",
"signature": "def __init__(self, A)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "next",
"signature": "def next(self, n)"
}
] | 2 | null | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int
<|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: Lis... | 696a25f8597e2a5bc5ab788924418d6423160af1 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
self.A = A
self.count_index = 0
self.num_index = 1
def next(self, n):
""":type n: int :rtype: int"""
if self.count_index >= len(self.A) - 1:
return -1
if n == 0:
re... | the_stack_v2_python_sparse | 900_RLE_iterator.py | tooyoungtoosimplesometimesnaive/probable-octo-potato | train | 0 | |
4ff22f8378785c2ee4b591c2e1224fb258fa3c40 | [
"trigger_full_path = trigger.cmd.split(' ')[0]\nif os.path.exists('{}-{}'.format(trigger_full_path, self.extension)):\n trigger.cmd = trigger.cmd.replace(trigger_full_path, '{}-{}'.format(trigger_full_path, self.extension))\n trigger.conf['executable'] = '{}-{}'.format(trigger.conf.get('executable'), self.ext... | <|body_start_0|>
trigger_full_path = trigger.cmd.split(' ')[0]
if os.path.exists('{}-{}'.format(trigger_full_path, self.extension)):
trigger.cmd = trigger.cmd.replace(trigger_full_path, '{}-{}'.format(trigger_full_path, self.extension))
trigger.conf['executable'] = '{}-{}'.format... | The base plugin implementation for triggering failing runs | Fail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fail:
"""The base plugin implementation for triggering failing runs"""
def pre_trigger_run(self, trigger: RawTrigger, *args, **kwargs) -> None:
"""Updates the coredumps information in order to generate some correctly :param trigger: the trigger instance to use :param args: additional... | stack_v2_sparse_classes_36k_train_007193 | 4,395 | no_license | [
{
"docstring": "Updates the coredumps information in order to generate some correctly :param trigger: the trigger instance to use :param args: additional arguments :param kwargs: additional keyword arguments",
"name": "pre_trigger_run",
"signature": "def pre_trigger_run(self, trigger: RawTrigger, *args,... | 3 | stack_v2_sparse_classes_30k_val_000251 | Implement the Python class `Fail` described below.
Class description:
The base plugin implementation for triggering failing runs
Method signatures and docstrings:
- def pre_trigger_run(self, trigger: RawTrigger, *args, **kwargs) -> None: Updates the coredumps information in order to generate some correctly :param tri... | Implement the Python class `Fail` described below.
Class description:
The base plugin implementation for triggering failing runs
Method signatures and docstrings:
- def pre_trigger_run(self, trigger: RawTrigger, *args, **kwargs) -> None: Updates the coredumps information in order to generate some correctly :param tri... | e9f914fb6c4eb1bc97f7dfc665e8dd6c7e7ad068 | <|skeleton|>
class Fail:
"""The base plugin implementation for triggering failing runs"""
def pre_trigger_run(self, trigger: RawTrigger, *args, **kwargs) -> None:
"""Updates the coredumps information in order to generate some correctly :param trigger: the trigger instance to use :param args: additional... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fail:
"""The base plugin implementation for triggering failing runs"""
def pre_trigger_run(self, trigger: RawTrigger, *args, **kwargs) -> None:
"""Updates the coredumps information in order to generate some correctly :param trigger: the trigger instance to use :param args: additional arguments :p... | the_stack_v2_python_sparse | plugins/base/fail.py | holaymzhang/bugbase | train | 0 |
debb8c7fa0fc9beed61de76179ac1bfcbcf14668 | [
"super(PanelFilePath, self).__init__(window_file_panel.tab_widget)\nself.window_file_panel = window_file_panel\nself.setup_file_path_ui()\nself.setup_connections()",
"self.path_layout = QtGui.QHBoxLayout(self)\nself.path_layout.setMargin(0)\nself.path_layout.setSpacing(0)\nself.path_line_edit = PanelDoubleClickPa... | <|body_start_0|>
super(PanelFilePath, self).__init__(window_file_panel.tab_widget)
self.window_file_panel = window_file_panel
self.setup_file_path_ui()
self.setup_connections()
<|end_body_0|>
<|body_start_1|>
self.path_layout = QtGui.QHBoxLayout(self)
self.path_layout.se... | PanelFilePath | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PanelFilePath:
def __init__(self, window_file_panel):
"""constructor initializes a widget with a edit line and button to be put on WindowFilePanel. Keyword arguments: :param window_file_panel: an initialized instance (parent widget) of WindowFilePanel class"""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_007194 | 2,909 | no_license | [
{
"docstring": "constructor initializes a widget with a edit line and button to be put on WindowFilePanel. Keyword arguments: :param window_file_panel: an initialized instance (parent widget) of WindowFilePanel class",
"name": "__init__",
"signature": "def __init__(self, window_file_panel)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_018447 | Implement the Python class `PanelFilePath` described below.
Class description:
Implement the PanelFilePath class.
Method signatures and docstrings:
- def __init__(self, window_file_panel): constructor initializes a widget with a edit line and button to be put on WindowFilePanel. Keyword arguments: :param window_file_... | Implement the Python class `PanelFilePath` described below.
Class description:
Implement the PanelFilePath class.
Method signatures and docstrings:
- def __init__(self, window_file_panel): constructor initializes a widget with a edit line and button to be put on WindowFilePanel. Keyword arguments: :param window_file_... | 5f7ab5b39c1dc7d8d2182048c5d8eaff04de3d06 | <|skeleton|>
class PanelFilePath:
def __init__(self, window_file_panel):
"""constructor initializes a widget with a edit line and button to be put on WindowFilePanel. Keyword arguments: :param window_file_panel: an initialized instance (parent widget) of WindowFilePanel class"""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PanelFilePath:
def __init__(self, window_file_panel):
"""constructor initializes a widget with a edit line and button to be put on WindowFilePanel. Keyword arguments: :param window_file_panel: an initialized instance (parent widget) of WindowFilePanel class"""
super(PanelFilePath, self).__init... | the_stack_v2_python_sparse | views/window/filepanel/panel_file_path.py | jafi666/pyCommander | train | 0 | |
03cafb17dbb9b39a099cd039729c65c3cd88c158 | [
"shutil.copy2(PREVIEW_APP_PATH_ANDROID.strip(), SUT_FOLDER)\nshutil.copy2(PREVIEW_APP_PATH_IOS.strip(), SUT_FOLDER)\nshutil.copy2(PLAYGROUND_APP_PATH_IOS.strip(), SUT_FOLDER)\n'Unpack the .tgz file to get the nsplaydev.app'\nFile.unpack_tar(os.path.join(SUT_FOLDER, 'nsplaydev.tgz'), SUT_FOLDER)\nFile.unpack_tar(os.... | <|body_start_0|>
shutil.copy2(PREVIEW_APP_PATH_ANDROID.strip(), SUT_FOLDER)
shutil.copy2(PREVIEW_APP_PATH_IOS.strip(), SUT_FOLDER)
shutil.copy2(PLAYGROUND_APP_PATH_IOS.strip(), SUT_FOLDER)
'Unpack the .tgz file to get the nsplaydev.app'
File.unpack_tar(os.path.join(SUT_FOLDER, 'n... | Preview | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preview:
def get_app_packages():
"""Copy Preview App packages from Shares to local folder"""
<|body_0|>
def install_preview_app(device_id, platform=Platform.BOTH):
"""Installs Preview App on emulator and simulator"""
<|body_1|>
def install_playground_app... | stack_v2_sparse_classes_36k_train_007195 | 3,684 | no_license | [
{
"docstring": "Copy Preview App packages from Shares to local folder",
"name": "get_app_packages",
"signature": "def get_app_packages()"
},
{
"docstring": "Installs Preview App on emulator and simulator",
"name": "install_preview_app",
"signature": "def install_preview_app(device_id, pl... | 6 | stack_v2_sparse_classes_30k_train_018604 | Implement the Python class `Preview` described below.
Class description:
Implement the Preview class.
Method signatures and docstrings:
- def get_app_packages(): Copy Preview App packages from Shares to local folder
- def install_preview_app(device_id, platform=Platform.BOTH): Installs Preview App on emulator and sim... | Implement the Python class `Preview` described below.
Class description:
Implement the Preview class.
Method signatures and docstrings:
- def get_app_packages(): Copy Preview App packages from Shares to local folder
- def install_preview_app(device_id, platform=Platform.BOTH): Installs Preview App on emulator and sim... | b173dc78de9f45a383bf74c2175f24e7fbae02c9 | <|skeleton|>
class Preview:
def get_app_packages():
"""Copy Preview App packages from Shares to local folder"""
<|body_0|>
def install_preview_app(device_id, platform=Platform.BOTH):
"""Installs Preview App on emulator and simulator"""
<|body_1|>
def install_playground_app... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Preview:
def get_app_packages():
"""Copy Preview App packages from Shares to local folder"""
shutil.copy2(PREVIEW_APP_PATH_ANDROID.strip(), SUT_FOLDER)
shutil.copy2(PREVIEW_APP_PATH_IOS.strip(), SUT_FOLDER)
shutil.copy2(PLAYGROUND_APP_PATH_IOS.strip(), SUT_FOLDER)
'Unpa... | the_stack_v2_python_sparse | core/preview_app/preview.py | niravgohil/nativescript-cli-tests | train | 0 | |
52199d5344bb74983cb53ee0493b9ae79490b3d4 | [
"username = request.user.get_username()\nserializer = CardSerializer(username, repo_base, request)\ncards = serializer.list_cards(repo_name)\nreturn Response(cards, status=status.HTTP_200_OK)",
"username = request.user.get_username()\nserializer = CardSerializer(username, repo_base, request)\ncard_name = request.... | <|body_start_0|>
username = request.user.get_username()
serializer = CardSerializer(username, repo_base, request)
cards = serializer.list_cards(repo_name)
return Response(cards, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
username = request.user.get_username()
... | Cards | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cards:
def get(self, request, repo_base, repo_name, format=None):
"""Cards in a repo"""
<|body_0|>
def post(self, request, repo_base, repo_name, format=None):
"""Create a card in a repo --- omit_serializer: true parameters: - name: card_name in: body type: string des... | stack_v2_sparse_classes_36k_train_007196 | 31,465 | permissive | [
{
"docstring": "Cards in a repo",
"name": "get",
"signature": "def get(self, request, repo_base, repo_name, format=None)"
},
{
"docstring": "Create a card in a repo --- omit_serializer: true parameters: - name: card_name in: body type: string description: name of the card to be created required:... | 2 | stack_v2_sparse_classes_30k_train_017579 | Implement the Python class `Cards` described below.
Class description:
Implement the Cards class.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, format=None): Cards in a repo
- def post(self, request, repo_base, repo_name, format=None): Create a card in a repo --- omit_serializer: tr... | Implement the Python class `Cards` described below.
Class description:
Implement the Cards class.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, format=None): Cards in a repo
- def post(self, request, repo_base, repo_name, format=None): Create a card in a repo --- omit_serializer: tr... | f066b472c2b66cc3b868bbe433aed2d4557aea32 | <|skeleton|>
class Cards:
def get(self, request, repo_base, repo_name, format=None):
"""Cards in a repo"""
<|body_0|>
def post(self, request, repo_base, repo_name, format=None):
"""Create a card in a repo --- omit_serializer: true parameters: - name: card_name in: body type: string des... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cards:
def get(self, request, repo_base, repo_name, format=None):
"""Cards in a repo"""
username = request.user.get_username()
serializer = CardSerializer(username, repo_base, request)
cards = serializer.list_cards(repo_name)
return Response(cards, status=status.HTTP_20... | the_stack_v2_python_sparse | src/api/views.py | datahuborg/datahub | train | 199 | |
fcdc1824d29de4166e2c9401cc42c818d46784f7 | [
"try:\n proxy_content = self.redisclient.srandmember('pycrawler_proxies:dly')\n if isinstance(proxy_content, bytes):\n proxy_content = proxy_content.decode()\n proxy = 'http://databurning:2tQJl*t8@{}'.format(proxy_content.strip())\n spider.logger.info(proxy)\n print('=======代理是===={}==========... | <|body_start_0|>
try:
proxy_content = self.redisclient.srandmember('pycrawler_proxies:dly')
if isinstance(proxy_content, bytes):
proxy_content = proxy_content.decode()
proxy = 'http://databurning:2tQJl*t8@{}'.format(proxy_content.strip())
spider.lo... | RedisProxyMiddleware | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisProxyMiddleware:
def process_request(self, request, spider):
"""将request设置为使用代理"""
<|body_0|>
def process_exception(self, request, exception, spider):
"""处理由于使用代理导致的连接异常 则重新换个代理继续请求"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_007197 | 13,351 | no_license | [
{
"docstring": "将request设置为使用代理",
"name": "process_request",
"signature": "def process_request(self, request, spider)"
},
{
"docstring": "处理由于使用代理导致的连接异常 则重新换个代理继续请求",
"name": "process_exception",
"signature": "def process_exception(self, request, exception, spider)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017936 | Implement the Python class `RedisProxyMiddleware` described below.
Class description:
Implement the RedisProxyMiddleware class.
Method signatures and docstrings:
- def process_request(self, request, spider): 将request设置为使用代理
- def process_exception(self, request, exception, spider): 处理由于使用代理导致的连接异常 则重新换个代理继续请求 | Implement the Python class `RedisProxyMiddleware` described below.
Class description:
Implement the RedisProxyMiddleware class.
Method signatures and docstrings:
- def process_request(self, request, spider): 将request设置为使用代理
- def process_exception(self, request, exception, spider): 处理由于使用代理导致的连接异常 则重新换个代理继续请求
<|skel... | e84350733bbb9f214757276d3a7c41d20cca9512 | <|skeleton|>
class RedisProxyMiddleware:
def process_request(self, request, spider):
"""将request设置为使用代理"""
<|body_0|>
def process_exception(self, request, exception, spider):
"""处理由于使用代理导致的连接异常 则重新换个代理继续请求"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RedisProxyMiddleware:
def process_request(self, request, spider):
"""将request设置为使用代理"""
try:
proxy_content = self.redisclient.srandmember('pycrawler_proxies:dly')
if isinstance(proxy_content, bytes):
proxy_content = proxy_content.decode()
pro... | the_stack_v2_python_sparse | amazon_us_07_17/amazon_us/middlewares.py | ShiJianYingxiang/origin | train | 2 | |
19489dc7818e7cd86c07d1bd1bd7eca7d6df53f0 | [
"profile = self.user.get_profile()\nsiteconfig = SiteConfiguration.objects.get_current()\ndiffviewer_syntax_highlighting = siteconfig.get('diffviewer_syntax_highlighting')\nself.set_initial({'open_an_issue': profile.open_an_issue, 'syntax_highlighting': profile.syntax_highlighting and diffviewer_syntax_highlighting... | <|body_start_0|>
profile = self.user.get_profile()
siteconfig = SiteConfiguration.objects.get_current()
diffviewer_syntax_highlighting = siteconfig.get('diffviewer_syntax_highlighting')
self.set_initial({'open_an_issue': profile.open_an_issue, 'syntax_highlighting': profile.syntax_highli... | Form for the Settings page for an account. | AccountSettingsForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountSettingsForm:
"""Form for the Settings page for an account."""
def load(self):
"""Load data for the form."""
<|body_0|>
def save(self):
"""Save the form."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
profile = self.user.get_profile()
... | stack_v2_sparse_classes_36k_train_007198 | 23,770 | permissive | [
{
"docstring": "Load data for the form.",
"name": "load",
"signature": "def load(self)"
},
{
"docstring": "Save the form.",
"name": "save",
"signature": "def save(self)"
}
] | 2 | null | Implement the Python class `AccountSettingsForm` described below.
Class description:
Form for the Settings page for an account.
Method signatures and docstrings:
- def load(self): Load data for the form.
- def save(self): Save the form. | Implement the Python class `AccountSettingsForm` described below.
Class description:
Form for the Settings page for an account.
Method signatures and docstrings:
- def load(self): Load data for the form.
- def save(self): Save the form.
<|skeleton|>
class AccountSettingsForm:
"""Form for the Settings page for an... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class AccountSettingsForm:
"""Form for the Settings page for an account."""
def load(self):
"""Load data for the form."""
<|body_0|>
def save(self):
"""Save the form."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountSettingsForm:
"""Form for the Settings page for an account."""
def load(self):
"""Load data for the form."""
profile = self.user.get_profile()
siteconfig = SiteConfiguration.objects.get_current()
diffviewer_syntax_highlighting = siteconfig.get('diffviewer_syntax_hig... | the_stack_v2_python_sparse | reviewboard/accounts/forms/pages.py | reviewboard/reviewboard | train | 1,141 |
176fbe5c2ac4efe16a54306dfde836c552a0cdf2 | [
"person = model.Person.get(self.repo, self.params.id)\nif not person:\n return self.error(400, _('No person with ID: %(id_str)s.') % {'id_str': self.params.id})\nself.render('disable_notes.html', person=person, view_url=self.get_url('/view', id=self.params.id), captcha_html=self.get_captcha_html())",
"person =... | <|body_start_0|>
person = model.Person.get(self.repo, self.params.id)
if not person:
return self.error(400, _('No person with ID: %(id_str)s.') % {'id_str': self.params.id})
self.render('disable_notes.html', person=person, view_url=self.get_url('/view', id=self.params.id), captcha_ht... | Handles an author request to disable notes to a person record. | Handler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Handler:
"""Handles an author request to disable notes to a person record."""
def get(self):
"""Prompts the user with a CAPTCHA before proceeding the request."""
<|body_0|>
def post(self):
"""If the user passed the CAPTCHA, send the confirmation email."""
... | stack_v2_sparse_classes_36k_train_007199 | 3,511 | permissive | [
{
"docstring": "Prompts the user with a CAPTCHA before proceeding the request.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "If the user passed the CAPTCHA, send the confirmation email.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `Handler` described below.
Class description:
Handles an author request to disable notes to a person record.
Method signatures and docstrings:
- def get(self): Prompts the user with a CAPTCHA before proceeding the request.
- def post(self): If the user passed the CAPTCHA, send the confirmat... | Implement the Python class `Handler` described below.
Class description:
Handles an author request to disable notes to a person record.
Method signatures and docstrings:
- def get(self): Prompts the user with a CAPTCHA before proceeding the request.
- def post(self): If the user passed the CAPTCHA, send the confirmat... | 7e40f2783ac89b91efd1d8497f1acc5b006361fa | <|skeleton|>
class Handler:
"""Handles an author request to disable notes to a person record."""
def get(self):
"""Prompts the user with a CAPTCHA before proceeding the request."""
<|body_0|>
def post(self):
"""If the user passed the CAPTCHA, send the confirmation email."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Handler:
"""Handles an author request to disable notes to a person record."""
def get(self):
"""Prompts the user with a CAPTCHA before proceeding the request."""
person = model.Person.get(self.repo, self.params.id)
if not person:
return self.error(400, _('No person wit... | the_stack_v2_python_sparse | app/disable_notes.py | ZhengC1/personfinder | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.