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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
605d737393abfb1f7c4ccbb6e50d4de28d422788 | [
"result = dict()\ncodec = dahuffman.HuffmanCodec.from_data(''.join(str_list))\nfor i in str_list:\n result.update({i: base64.b64encode(codec.encode(i)).decode('utf-8')})\ncode_table = codec.get_code_table()\ndata = {'code_table': code_table}\ndata = base64.b64encode(pickle.dumps(data)).decode('utf-8')\nresult.up... | <|body_start_0|>
result = dict()
codec = dahuffman.HuffmanCodec.from_data(''.join(str_list))
for i in str_list:
result.update({i: base64.b64encode(codec.encode(i)).decode('utf-8')})
code_table = codec.get_code_table()
data = {'code_table': code_table}
data = b... | The HuffmanCoding class forms the base of the dependency provider for the Huffman Coding algorithm. It uses dahuffman.HuffmanCodec to perform the majority of the work. Data is base64 encoded for transfer over the network | HuffmanCoding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HuffmanCoding:
"""The HuffmanCoding class forms the base of the dependency provider for the Huffman Coding algorithm. It uses dahuffman.HuffmanCodec to perform the majority of the work. Data is base64 encoded for transfer over the network"""
def encode(str_list):
"""The main function... | stack_v2_sparse_classes_36k_train_017100 | 2,753 | no_license | [
{
"docstring": "The main function to produce a dictionary of original and encoded strings. A code table is added to the result for calibrating a new Huffman codec for decode. The code table is pickled first, and then base64 encoded to deal with custom _EOF marker included in dahuffman :param str_list: The list ... | 2 | stack_v2_sparse_classes_30k_train_013200 | Implement the Python class `HuffmanCoding` described below.
Class description:
The HuffmanCoding class forms the base of the dependency provider for the Huffman Coding algorithm. It uses dahuffman.HuffmanCodec to perform the majority of the work. Data is base64 encoded for transfer over the network
Method signatures ... | Implement the Python class `HuffmanCoding` described below.
Class description:
The HuffmanCoding class forms the base of the dependency provider for the Huffman Coding algorithm. It uses dahuffman.HuffmanCodec to perform the majority of the work. Data is base64 encoded for transfer over the network
Method signatures ... | 60caf3dbedc4512cd8d47c6fac4da7c4d13038d3 | <|skeleton|>
class HuffmanCoding:
"""The HuffmanCoding class forms the base of the dependency provider for the Huffman Coding algorithm. It uses dahuffman.HuffmanCodec to perform the majority of the work. Data is base64 encoded for transfer over the network"""
def encode(str_list):
"""The main function... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HuffmanCoding:
"""The HuffmanCoding class forms the base of the dependency provider for the Huffman Coding algorithm. It uses dahuffman.HuffmanCodec to perform the majority of the work. Data is base64 encoded for transfer over the network"""
def encode(str_list):
"""The main function to produce a... | the_stack_v2_python_sparse | Development/V03/app/dependencies/huffman.py | 8563a236e65cede7b14220e65c70ad5718144a3/microservices-interview-answers | train | 0 |
0cffb42cef42e5fa2eb8f37ab515e19c6218c25d | [
"if l2 and l1 and (l2.val < l1.val) or l1 is None:\n head = l2\n if l2:\n l2 = l2.next\nelse:\n head = l1\n if l1:\n l1 = l1.next\nnow = head\nwhile l1 and l2:\n if l1.val <= l2.val:\n now.next = l1\n now = l1\n l1 = l1.next\n else:\n now.next = l2\n ... | <|body_start_0|>
if l2 and l1 and (l2.val < l1.val) or l1 is None:
head = l2
if l2:
l2 = l2.next
else:
head = l1
if l1:
l1 = l1.next
now = head
while l1 and l2:
if l1.val <= l2.val:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if l2 an... | stack_v2_sparse_classes_36k_train_017101 | 993 | permissive | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
},
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
<|skeleton|>... | 97e84daa2926a9cd2036e0dee36dfe5773114b15 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
if l2 and l1 and (l2.val < l1.val) or l1 is None:
head = l2
if l2:
l2 = l2.next
else:
head = l1
if l1:
... | the_stack_v2_python_sparse | 23. Merge k Sorted Lists.py | ten2net/Leetcode-solution | train | 0 | |
1163b186507be134c84d30355dfbd38a57dd7f95 | [
"super().__init__(decision_variables=decision_variables, constraints=constraints, encoding_rule=encoding_rule)\nself._name = 'Travel Salesman Problem'\nself._objective = ProblemObjective.Minimization\nself._distances = []\nif 'Distances' in decision_variables:\n self._distances = decision_variables['Distances']\... | <|body_start_0|>
super().__init__(decision_variables=decision_variables, constraints=constraints, encoding_rule=encoding_rule)
self._name = 'Travel Salesman Problem'
self._objective = ProblemObjective.Minimization
self._distances = []
if 'Distances' in decision_variables:
... | Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city? | TravelSalesmanProblem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TravelSalesmanProblem:
"""Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city?"""
def __init__(self, decision_variables, constraints={}, encoding_rule={}):
"""Trave... | stack_v2_sparse_classes_36k_train_017102 | 8,155 | no_license | [
{
"docstring": "Travel Salesman Problem CONSTRUCTOR Parameters: @decision_variables Expected Decision Variables, so the dictionary must have the following keys and values of them must be lists: e.g: decision_variables_example = { \"Distances\" : data, #<< Matrix, Mandatory - the matrix containing the distances ... | 4 | stack_v2_sparse_classes_30k_train_008363 | Implement the Python class `TravelSalesmanProblem` described below.
Class description:
Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city?
Method signatures and docstrings:
- def __init__(self, dec... | Implement the Python class `TravelSalesmanProblem` described below.
Class description:
Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city?
Method signatures and docstrings:
- def __init__(self, dec... | 497945e2f017aa34f79af1f448a21807a8220cc1 | <|skeleton|>
class TravelSalesmanProblem:
"""Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city?"""
def __init__(self, decision_variables, constraints={}, encoding_rule={}):
"""Trave... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TravelSalesmanProblem:
"""Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city?"""
def __init__(self, decision_variables, constraints={}, encoding_rule={}):
"""Travel Salesman Pr... | the_stack_v2_python_sparse | cifo_project_v2/cifo_project/cifo/custom_problem/travel_salesman_problem.py | CatPalha/CIFO-Project | train | 1 |
b34cd735cd2b4c1ff9ab0091f79aa1f659cb044e | [
"super().__init__()\nself.status_bar = self.statusBar()\nmain_frame = MainFrame(self.status_bar, smbedit)\nself.setCentralWidget(main_frame)\nself.menu_bar = MenuBar(self, main_frame, smbedit)\nself.setGeometry(150, 150, 550, 500)\nself.status_bar.showMessage('Ready')",
"percent = ('{0:.' + str(decimals) + 'f}').... | <|body_start_0|>
super().__init__()
self.status_bar = self.statusBar()
main_frame = MainFrame(self.status_bar, smbedit)
self.setCentralWidget(main_frame)
self.menu_bar = MenuBar(self, main_frame, smbedit)
self.setGeometry(150, 150, 550, 500)
self.status_bar.showMe... | Window | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Window:
def __init__(self, smbedit):
"""@type smbedit: SMBEditGUI"""
<|body_0|>
def print_progress_bar(self, iteration, total, prefix='', suffix='', decimals=1, length=20, fill='X'):
"""Original: https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-co... | stack_v2_sparse_classes_36k_train_017103 | 1,829 | no_license | [
{
"docstring": "@type smbedit: SMBEditGUI",
"name": "__init__",
"signature": "def __init__(self, smbedit)"
},
{
"docstring": "Original: https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console Call in a loop to create terminal progress bar @params: iteration - Required : curr... | 2 | null | Implement the Python class `Window` described below.
Class description:
Implement the Window class.
Method signatures and docstrings:
- def __init__(self, smbedit): @type smbedit: SMBEditGUI
- def print_progress_bar(self, iteration, total, prefix='', suffix='', decimals=1, length=20, fill='X'): Original: https://stac... | Implement the Python class `Window` described below.
Class description:
Implement the Window class.
Method signatures and docstrings:
- def __init__(self, smbedit): @type smbedit: SMBEditGUI
- def print_progress_bar(self, iteration, total, prefix='', suffix='', decimals=1, length=20, fill='X'): Original: https://stac... | 12fe1b39513cf0d1ca8edd9adb6c11269c58fbb5 | <|skeleton|>
class Window:
def __init__(self, smbedit):
"""@type smbedit: SMBEditGUI"""
<|body_0|>
def print_progress_bar(self, iteration, total, prefix='', suffix='', decimals=1, length=20, fill='X'):
"""Original: https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Window:
def __init__(self, smbedit):
"""@type smbedit: SMBEditGUI"""
super().__init__()
self.status_bar = self.statusBar()
main_frame = MainFrame(self.status_bar, smbedit)
self.setCentralWidget(main_frame)
self.menu_bar = MenuBar(self, main_frame, smbedit)
... | the_stack_v2_python_sparse | smlib/gui/window.py | p-hofmann/SMBEdit | train | 6 | |
302ee6f6bef265faefda4ea9c8f4852cf9aa4022 | [
"self.context_mock = MagicMock()\nself.context_mock.peer.return_value = CLIENT_CID\nself.client_messages = [CLIENT_MESSAGE for _ in range(5)]\nself.res_wrappers = [ResWrapper(client_message=msg) for msg in self.client_messages]\nself.client_messages_iterator = iter(self.client_messages)\nself.ins_wrappers = [InsWra... | <|body_start_0|>
self.context_mock = MagicMock()
self.context_mock.peer.return_value = CLIENT_CID
self.client_messages = [CLIENT_MESSAGE for _ in range(5)]
self.res_wrappers = [ResWrapper(client_message=msg) for msg in self.client_messages]
self.client_messages_iterator = iter(se... | Test suite for class FlowerServiceServicer and helper functions. | FlowerServiceServicerTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlowerServiceServicerTestCase:
"""Test suite for class FlowerServiceServicer and helper functions."""
def setUp(self) -> None:
"""Create mocks for tests."""
<|body_0|>
def test_register_client_proxy(self) -> None:
"""Test register_client_proxy function."""
... | stack_v2_sparse_classes_36k_train_017104 | 5,195 | permissive | [
{
"docstring": "Create mocks for tests.",
"name": "setUp",
"signature": "def setUp(self) -> None"
},
{
"docstring": "Test register_client_proxy function.",
"name": "test_register_client_proxy",
"signature": "def test_register_client_proxy(self) -> None"
},
{
"docstring": "Test Jo... | 3 | stack_v2_sparse_classes_30k_train_000516 | Implement the Python class `FlowerServiceServicerTestCase` described below.
Class description:
Test suite for class FlowerServiceServicer and helper functions.
Method signatures and docstrings:
- def setUp(self) -> None: Create mocks for tests.
- def test_register_client_proxy(self) -> None: Test register_client_prox... | Implement the Python class `FlowerServiceServicerTestCase` described below.
Class description:
Test suite for class FlowerServiceServicer and helper functions.
Method signatures and docstrings:
- def setUp(self) -> None: Create mocks for tests.
- def test_register_client_proxy(self) -> None: Test register_client_prox... | 55be690535e5f3feb33c888c3e4a586b7bdbf489 | <|skeleton|>
class FlowerServiceServicerTestCase:
"""Test suite for class FlowerServiceServicer and helper functions."""
def setUp(self) -> None:
"""Create mocks for tests."""
<|body_0|>
def test_register_client_proxy(self) -> None:
"""Test register_client_proxy function."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlowerServiceServicerTestCase:
"""Test suite for class FlowerServiceServicer and helper functions."""
def setUp(self) -> None:
"""Create mocks for tests."""
self.context_mock = MagicMock()
self.context_mock.peer.return_value = CLIENT_CID
self.client_messages = [CLIENT_MESS... | the_stack_v2_python_sparse | src/py/flwr/server/fleet/grpc_bidi/flower_service_servicer_test.py | adap/flower | train | 2,999 |
a2cccdbd08faa977d51083ea531c59e180ee6305 | [
"examples = []\nfor i, line in enumerate(lines):\n if len(line) != 2:\n print('data format error: %s' % '\\t'.join(line))\n print('data row contains two parts: label \\t conversation_content')\n continue\n guid = '%s-%d' % (set_type, i)\n text_a = line[1]\n text_a = tokenization.con... | <|body_start_0|>
examples = []
for i, line in enumerate(lines):
if len(line) != 2:
print('data format error: %s' % '\t'.join(line))
print('data row contains two parts: label \t conversation_content')
continue
guid = '%s-%d' % (set_t... | Processor for the ATIS intent data set. | ATISIntentProcessor | [
"Apache-2.0",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ATISIntentProcessor:
"""Processor for the ATIS intent data set."""
def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
<|body_0|>
def get_train_examples(self, data_dir):
"""See base class."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_017105 | 30,538 | permissive | [
{
"docstring": "Creates examples for the training and dev sets.",
"name": "_create_examples",
"signature": "def _create_examples(self, lines, set_type)"
},
{
"docstring": "See base class.",
"name": "get_train_examples",
"signature": "def get_train_examples(self, data_dir)"
},
{
"... | 5 | null | Implement the Python class `ATISIntentProcessor` described below.
Class description:
Processor for the ATIS intent data set.
Method signatures and docstrings:
- def _create_examples(self, lines, set_type): Creates examples for the training and dev sets.
- def get_train_examples(self, data_dir): See base class.
- def ... | Implement the Python class `ATISIntentProcessor` described below.
Class description:
Processor for the ATIS intent data set.
Method signatures and docstrings:
- def _create_examples(self, lines, set_type): Creates examples for the training and dev sets.
- def get_train_examples(self, data_dir): See base class.
- def ... | a60babdf382aba71fe447b3259441b4bed947414 | <|skeleton|>
class ATISIntentProcessor:
"""Processor for the ATIS intent data set."""
def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
<|body_0|>
def get_train_examples(self, data_dir):
"""See base class."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ATISIntentProcessor:
"""Processor for the ATIS intent data set."""
def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for i, line in enumerate(lines):
if len(line) != 2:
print('data format er... | the_stack_v2_python_sparse | PaddleNLP/dialogue_system/dialogue_general_understanding/dgu/reader.py | littletomatodonkey/models | train | 5 |
d5e98791c212c21b48657bdc6ea9aa0fb76eacbc | [
"if serializer is None:\n serializer = DefaultSerializer()\nif output_type is None:\n output_type = 'ask_sdk_model.response.Response'\nself.serializer = serializer\nself.output_type = output_type",
"try:\n encoding = template_content.encoding\n template = Template(template_content.content_data.decode(... | <|body_start_0|>
if serializer is None:
serializer = DefaultSerializer()
if output_type is None:
output_type = 'ask_sdk_model.response.Response'
self.serializer = serializer
self.output_type = output_type
<|end_body_0|>
<|body_start_1|>
try:
e... | Implementation to render a Jinja Template, and deserialize to skill response output. JinjaTemplateRenderer can be initialised with a custom serializer to deserialize the template content to corresponding response type. If no serializer is specified, default serializer from :py:class:`ask_sdk_core.serialize.DefaultSeria... | JinjaTemplateRenderer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JinjaTemplateRenderer:
"""Implementation to render a Jinja Template, and deserialize to skill response output. JinjaTemplateRenderer can be initialised with a custom serializer to deserialize the template content to corresponding response type. If no serializer is specified, default serializer fr... | stack_v2_sparse_classes_36k_train_017106 | 4,516 | permissive | [
{
"docstring": "Initializing the default serializer to deserialize rendered content to skill response output. If no serializer is specified, default serializer from :py:class:`ask_sdk_core.serialize.DefaultSerializer` is set also if the output type is not specified default value of :py:class:`ask_sdk_model.resp... | 2 | null | Implement the Python class `JinjaTemplateRenderer` described below.
Class description:
Implementation to render a Jinja Template, and deserialize to skill response output. JinjaTemplateRenderer can be initialised with a custom serializer to deserialize the template content to corresponding response type. If no seriali... | Implement the Python class `JinjaTemplateRenderer` described below.
Class description:
Implementation to render a Jinja Template, and deserialize to skill response output. JinjaTemplateRenderer can be initialised with a custom serializer to deserialize the template content to corresponding response type. If no seriali... | 7e13ca69b240985584dff6ec633a27598a154ca1 | <|skeleton|>
class JinjaTemplateRenderer:
"""Implementation to render a Jinja Template, and deserialize to skill response output. JinjaTemplateRenderer can be initialised with a custom serializer to deserialize the template content to corresponding response type. If no serializer is specified, default serializer fr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JinjaTemplateRenderer:
"""Implementation to render a Jinja Template, and deserialize to skill response output. JinjaTemplateRenderer can be initialised with a custom serializer to deserialize the template content to corresponding response type. If no serializer is specified, default serializer from :py:class:... | the_stack_v2_python_sparse | ask-sdk-jinja-renderer/ask_sdk_jinja_renderer/jinja_template_renderer.py | alexa/alexa-skills-kit-sdk-for-python | train | 560 |
c378b0e152cd9995673a349ef91d7235e750e441 | [
"key = sha256(elem.serialize()).digest()\ncandidates = self.conn.scan(self.table, Range(srow=key, erow=key))\ntry:\n first = next(candidates)\nexcept StopIteration:\n return None\nreturn EmbeddedNode(self, key)",
"sl = cls(None, lbound, rbound, coin)\nif conn_info is not None:\n host, port, user, passwor... | <|body_start_0|>
key = sha256(elem.serialize()).digest()
candidates = self.conn.scan(self.table, Range(srow=key, erow=key))
try:
first = next(candidates)
except StopIteration:
return None
return EmbeddedNode(self, key)
<|end_body_0|>
<|body_start_1|>
... | A class for an authenticated skip list embedded in an Accumulo instance. Most of the work on the actual embedding is in the node class, found in embeddednode.py | EmbeddedSkipList | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmbeddedSkipList:
"""A class for an authenticated skip list embedded in an Accumulo instance. Most of the work on the actual embedding is in the node class, found in embeddednode.py"""
def from_elem(self, elem):
"""Check if an element is in the database. If so, return an embedded nod... | stack_v2_sparse_classes_36k_train_017107 | 6,748 | permissive | [
{
"docstring": "Check if an element is in the database. If so, return an embedded node pointing to that element's leaf node in the skiplist. If not, return None.",
"name": "from_elem",
"signature": "def from_elem(self, elem)"
},
{
"docstring": "Create a new skiplist that stores all of its data i... | 3 | null | Implement the Python class `EmbeddedSkipList` described below.
Class description:
A class for an authenticated skip list embedded in an Accumulo instance. Most of the work on the actual embedding is in the node class, found in embeddednode.py
Method signatures and docstrings:
- def from_elem(self, elem): Check if an ... | Implement the Python class `EmbeddedSkipList` described below.
Class description:
A class for an authenticated skip list embedded in an Accumulo instance. Most of the work on the actual embedding is in the node class, found in embeddednode.py
Method signatures and docstrings:
- def from_elem(self, elem): Check if an ... | eb61250886e51647bd1edb6d8f4fa7f83eb0bc81 | <|skeleton|>
class EmbeddedSkipList:
"""A class for an authenticated skip list embedded in an Accumulo instance. Most of the work on the actual embedding is in the node class, found in embeddednode.py"""
def from_elem(self, elem):
"""Check if an element is in the database. If so, return an embedded nod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmbeddedSkipList:
"""A class for an authenticated skip list embedded in an Accumulo instance. Most of the work on the actual embedding is in the node class, found in embeddednode.py"""
def from_elem(self, elem):
"""Check if an element is in the database. If so, return an embedded node pointing to... | the_stack_v2_python_sparse | pace/ads/skiplist/accumulo/embeddedskiplist.py | Global-localhost/PACE-python | train | 0 |
da9c15c98e48592ce33e686931d10fe18c2bd657 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UnifiedRoleManagementPolicyEnablementRule()",
"from .unified_role_management_policy_rule import UnifiedRoleManagementPolicyRule\nfrom .unified_role_management_policy_rule import UnifiedRoleManagementPolicyRule\nfields: Dict[str, Callab... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UnifiedRoleManagementPolicyEnablementRule()
<|end_body_0|>
<|body_start_1|>
from .unified_role_management_policy_rule import UnifiedRoleManagementPolicyRule
from .unified_role_management... | UnifiedRoleManagementPolicyEnablementRule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnifiedRoleManagementPolicyEnablementRule:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleManagementPolicyEnablementRule:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to re... | stack_v2_sparse_classes_36k_train_017108 | 2,533 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UnifiedRoleManagementPolicyEnablementRule",
"name": "create_from_discriminator_value",
"signature": "def cre... | 3 | stack_v2_sparse_classes_30k_train_002124 | Implement the Python class `UnifiedRoleManagementPolicyEnablementRule` described below.
Class description:
Implement the UnifiedRoleManagementPolicyEnablementRule class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleManagementPolicyEnableme... | Implement the Python class `UnifiedRoleManagementPolicyEnablementRule` described below.
Class description:
Implement the UnifiedRoleManagementPolicyEnablementRule class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleManagementPolicyEnableme... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UnifiedRoleManagementPolicyEnablementRule:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleManagementPolicyEnablementRule:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnifiedRoleManagementPolicyEnablementRule:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleManagementPolicyEnablementRule:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discrim... | the_stack_v2_python_sparse | msgraph/generated/models/unified_role_management_policy_enablement_rule.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
f5a0fd43b0d104e3a05d49c794231261362352e3 | [
"review: Review = self.get_object()\nreview.helpful.add(request.user)\nserializer: ReviewSerializer = self.get_serializer(review)\nreturn Response(data=serializer.data, status=status.HTTP_200_OK)",
"review: Review = self.get_object()\nreview.helpful.remove(request.user)\nserializer: ReviewSerializer = self.get_se... | <|body_start_0|>
review: Review = self.get_object()
review.helpful.add(request.user)
serializer: ReviewSerializer = self.get_serializer(review)
return Response(data=serializer.data, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
review: Review = self.get_object()
... | Review helpful view. | ReviewHelpful | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewHelpful:
"""Review helpful view."""
def post(self, request: Request, *args: tuple, **kwargs: dict) -> Response:
"""Set the review as helpful. :param request: Request :return: Review"""
<|body_0|>
def delete(self, request: Request, *args: tuple, **kwargs: dict) -> R... | stack_v2_sparse_classes_36k_train_017109 | 5,590 | no_license | [
{
"docstring": "Set the review as helpful. :param request: Request :return: Review",
"name": "post",
"signature": "def post(self, request: Request, *args: tuple, **kwargs: dict) -> Response"
},
{
"docstring": "Unset the review as helpful. :param request: Request :return: Review",
"name": "de... | 2 | null | Implement the Python class `ReviewHelpful` described below.
Class description:
Review helpful view.
Method signatures and docstrings:
- def post(self, request: Request, *args: tuple, **kwargs: dict) -> Response: Set the review as helpful. :param request: Request :return: Review
- def delete(self, request: Request, *a... | Implement the Python class `ReviewHelpful` described below.
Class description:
Review helpful view.
Method signatures and docstrings:
- def post(self, request: Request, *args: tuple, **kwargs: dict) -> Response: Set the review as helpful. :param request: Request :return: Review
- def delete(self, request: Request, *a... | 713b9d84ac70d964d46f189ab1f9c7b944b9684b | <|skeleton|>
class ReviewHelpful:
"""Review helpful view."""
def post(self, request: Request, *args: tuple, **kwargs: dict) -> Response:
"""Set the review as helpful. :param request: Request :return: Review"""
<|body_0|>
def delete(self, request: Request, *args: tuple, **kwargs: dict) -> R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReviewHelpful:
"""Review helpful view."""
def post(self, request: Request, *args: tuple, **kwargs: dict) -> Response:
"""Set the review as helpful. :param request: Request :return: Review"""
review: Review = self.get_object()
review.helpful.add(request.user)
serializer: Re... | the_stack_v2_python_sparse | jobadvisor/reviews/views/review.py | ewgen19892/jobadvisor | train | 0 |
fb59509acbeed91f80436a9b734ecd145ffd4861 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Win32LobAppMsiInformation()",
"from .win32_lob_app_msi_package_type import Win32LobAppMsiPackageType\nfrom .win32_lob_app_msi_package_type import Win32LobAppMsiPackageType\nfields: Dict[str, Callable[[Any], None]] = {'@odata.type': lam... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Win32LobAppMsiInformation()
<|end_body_0|>
<|body_start_1|>
from .win32_lob_app_msi_package_type import Win32LobAppMsiPackageType
from .win32_lob_app_msi_package_type import Win32LobAppM... | Contains MSI app properties for a Win32 App. | Win32LobAppMsiInformation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Win32LobAppMsiInformation:
"""Contains MSI app properties for a Win32 App."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppMsiInformation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The ... | stack_v2_sparse_classes_36k_train_017110 | 4,285 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Win32LobAppMsiInformation",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrim... | 3 | null | Implement the Python class `Win32LobAppMsiInformation` described below.
Class description:
Contains MSI app properties for a Win32 App.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppMsiInformation: Creates a new instance of the appropriate ... | Implement the Python class `Win32LobAppMsiInformation` described below.
Class description:
Contains MSI app properties for a Win32 App.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppMsiInformation: Creates a new instance of the appropriate ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Win32LobAppMsiInformation:
"""Contains MSI app properties for a Win32 App."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppMsiInformation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Win32LobAppMsiInformation:
"""Contains MSI app properties for a Win32 App."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppMsiInformation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to... | the_stack_v2_python_sparse | msgraph/generated/models/win32_lob_app_msi_information.py | microsoftgraph/msgraph-sdk-python | train | 135 |
c6f0bf1a6a2437b2972e7a6092b793e5fee53601 | [
"files = os.listdir(fpath)\nfiles.sort(key=lambda s: os.path.getmtime(os.path.join(fpath, s)))\nfrom_files = [self.from_chl(fpath + abf) for abf in files]\nmulti_data = pd.concat(from_files, axis=1)\nself.to_pc(header, fpath + '/all.atf', multi_data)",
"print('parsing file: {}'.format(infile))\nreader = neo.io.Ax... | <|body_start_0|>
files = os.listdir(fpath)
files.sort(key=lambda s: os.path.getmtime(os.path.join(fpath, s)))
from_files = [self.from_chl(fpath + abf) for abf in files]
multi_data = pd.concat(from_files, axis=1)
self.to_pc(header, fpath + '/all.atf', multi_data)
<|end_body_0|>
<... | Lab2Clamp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lab2Clamp:
def __init__(self, header, fpath):
"""reads all ChannelLab abf files at path and saves in one atf file :param header: path to header template :param path: path to directory"""
<|body_0|>
def from_chl(self, infile):
"""reads single abf file :param infile: a... | stack_v2_sparse_classes_36k_train_017111 | 2,747 | no_license | [
{
"docstring": "reads all ChannelLab abf files at path and saves in one atf file :param header: path to header template :param path: path to directory",
"name": "__init__",
"signature": "def __init__(self, header, fpath)"
},
{
"docstring": "reads single abf file :param infile: abf file path :ret... | 3 | null | Implement the Python class `Lab2Clamp` described below.
Class description:
Implement the Lab2Clamp class.
Method signatures and docstrings:
- def __init__(self, header, fpath): reads all ChannelLab abf files at path and saves in one atf file :param header: path to header template :param path: path to directory
- def ... | Implement the Python class `Lab2Clamp` described below.
Class description:
Implement the Lab2Clamp class.
Method signatures and docstrings:
- def __init__(self, header, fpath): reads all ChannelLab abf files at path and saves in one atf file :param header: path to header template :param path: path to directory
- def ... | fdb8a1a14bcf0b372ebaf152f2bbb1f5d804172e | <|skeleton|>
class Lab2Clamp:
def __init__(self, header, fpath):
"""reads all ChannelLab abf files at path and saves in one atf file :param header: path to header template :param path: path to directory"""
<|body_0|>
def from_chl(self, infile):
"""reads single abf file :param infile: a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lab2Clamp:
def __init__(self, header, fpath):
"""reads all ChannelLab abf files at path and saves in one atf file :param header: path to header template :param path: path to directory"""
files = os.listdir(fpath)
files.sort(key=lambda s: os.path.getmtime(os.path.join(fpath, s)))
... | the_stack_v2_python_sparse | multi_channel/lab2clamp.py | michal2am/bioscripts | train | 3 | |
28f8990ed2f9d24cb7f5eb1c467b4844917f9bbd | [
"curr = head\nprev = None\nwhile curr is not None:\n nextnode = curr.next\n curr.next = prev\n prev = curr\n curr = nextnode\nreturn prev",
"if head is None or head.next is None:\n return head\nrst = self.reverseList_recursive(head.next)\nhead.next.next = head\nhead = None\nreturn rst"
] | <|body_start_0|>
curr = head
prev = None
while curr is not None:
nextnode = curr.next
curr.next = prev
prev = curr
curr = nextnode
return prev
<|end_body_0|>
<|body_start_1|>
if head is None or head.next is None:
return... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList_iterative(self, head):
""":type head: ListNode :rtype: ListNode :Algorithm: - Interate through the list - maintain a pointer indicating the next node - maintain a previous node, starting from None - make current node point to previous node - make previous node g... | stack_v2_sparse_classes_36k_train_017112 | 1,439 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode :Algorithm: - Interate through the list - maintain a pointer indicating the next node - maintain a previous node, starting from None - make current node point to previous node - make previous node goes to current node - make current node point to next node",... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList_iterative(self, head): :type head: ListNode :rtype: ListNode :Algorithm: - Interate through the list - maintain a pointer indicating the next node - maintain a pr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList_iterative(self, head): :type head: ListNode :rtype: ListNode :Algorithm: - Interate through the list - maintain a pointer indicating the next node - maintain a pr... | 41365b549f1e6b04aac9f1632a66e71c1e05b322 | <|skeleton|>
class Solution:
def reverseList_iterative(self, head):
""":type head: ListNode :rtype: ListNode :Algorithm: - Interate through the list - maintain a pointer indicating the next node - maintain a previous node, starting from None - make current node point to previous node - make previous node g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList_iterative(self, head):
""":type head: ListNode :rtype: ListNode :Algorithm: - Interate through the list - maintain a pointer indicating the next node - maintain a previous node, starting from None - make current node point to previous node - make previous node goes to current... | the_stack_v2_python_sparse | python practice/LinkedList/e_reverseList.py | SuzyWu2014/coding-practice | train | 1 | |
c6be058507f7c1fe3ca07fafe628f8362d2d5303 | [
"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 that implements Google Cloud Text-to-Speech API. | TextToSpeechServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextToSpeechServicer:
"""Service that implements Google Cloud Text-to-Speech API."""
def ListVoices(self, request, context):
"""Returns a list of Voice supported for synthesis."""
<|body_0|>
def SynthesizeSpeech(self, request, context):
"""Synthesizes speech sync... | stack_v2_sparse_classes_36k_train_017113 | 3,037 | permissive | [
{
"docstring": "Returns a list of Voice supported for synthesis.",
"name": "ListVoices",
"signature": "def ListVoices(self, request, context)"
},
{
"docstring": "Synthesizes speech synchronously: receive results after all text input has been processed.",
"name": "SynthesizeSpeech",
"sign... | 2 | null | Implement the Python class `TextToSpeechServicer` described below.
Class description:
Service that implements Google Cloud Text-to-Speech API.
Method signatures and docstrings:
- def ListVoices(self, request, context): Returns a list of Voice supported for synthesis.
- def SynthesizeSpeech(self, request, context): Sy... | Implement the Python class `TextToSpeechServicer` described below.
Class description:
Service that implements Google Cloud Text-to-Speech API.
Method signatures and docstrings:
- def ListVoices(self, request, context): Returns a list of Voice supported for synthesis.
- def SynthesizeSpeech(self, request, context): Sy... | d897d56bce03d1fda98b79afb08264e51d46c421 | <|skeleton|>
class TextToSpeechServicer:
"""Service that implements Google Cloud Text-to-Speech API."""
def ListVoices(self, request, context):
"""Returns a list of Voice supported for synthesis."""
<|body_0|>
def SynthesizeSpeech(self, request, context):
"""Synthesizes speech sync... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextToSpeechServicer:
"""Service that implements Google Cloud Text-to-Speech API."""
def ListVoices(self, request, context):
"""Returns a list of Voice supported for synthesis."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | texttospeech/google/cloud/texttospeech_v1/proto/cloud_tts_pb2_grpc.py | tswast/google-cloud-python | train | 1 |
579516258348d647606b131e9eb94318f9a306cf | [
"if not nums:\n return 0\nnums_set = set(nums)\nlongestConsecutiveLen = 0\ncount = 0\nfor num in nums_set:\n if num - 1 not in nums_set:\n current_num = num\n count = 1\n while current_num + 1 in nums_set:\n count += 1\n current_num += 1\n longestConsecutiveLe... | <|body_start_0|>
if not nums:
return 0
nums_set = set(nums)
longestConsecutiveLen = 0
count = 0
for num in nums_set:
if num - 1 not in nums_set:
current_num = num
count = 1
while current_num + 1 in nums_set:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestConsecutiveV0(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
retu... | stack_v2_sparse_classes_36k_train_017114 | 1,208 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutive",
"signature": "def longestConsecutive(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutiveV0",
"signature": "def longestConsecutiveV0(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012142 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int
- def longestConsecutiveV0(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int
- def longestConsecutiveV0(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 76fdcec59b48c69120ebcf13a5374e6fc480c257 | <|skeleton|>
class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestConsecutiveV0(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
nums_set = set(nums)
longestConsecutiveLen = 0
count = 0
for num in nums_set:
if num - 1 not in nums_set:
current_... | the_stack_v2_python_sparse | lulu/longestConsecutiveSequence.py | luluxing3/LeetCode | train | 1 | |
91bc824fbc850b3a8d04607956fc21673b175379 | [
"self.sensor = sensor\nself.pin = getattr(board, pin)\nself.data = {}\nself.name = name",
"dht = self.sensor(self.pin)\ntry:\n temperature = dht.temperature\n humidity = dht.humidity\nexcept RuntimeError:\n _LOGGER.debug('Unexpected value from DHT sensor: %s', self.name)\nexcept Exception:\n _LOGGER.e... | <|body_start_0|>
self.sensor = sensor
self.pin = getattr(board, pin)
self.data = {}
self.name = name
<|end_body_0|>
<|body_start_1|>
dht = self.sensor(self.pin)
try:
temperature = dht.temperature
humidity = dht.humidity
except RuntimeError... | Get the latest data from the DHT sensor. | DHTClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DHTClient:
"""Get the latest data from the DHT sensor."""
def __init__(self, sensor, pin, name):
"""Initialize the sensor."""
<|body_0|>
def update(self):
"""Get the latest data the DHT sensor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sel... | stack_v2_sparse_classes_36k_train_017115 | 5,733 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, sensor, pin, name)"
},
{
"docstring": "Get the latest data the DHT sensor.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003357 | Implement the Python class `DHTClient` described below.
Class description:
Get the latest data from the DHT sensor.
Method signatures and docstrings:
- def __init__(self, sensor, pin, name): Initialize the sensor.
- def update(self): Get the latest data the DHT sensor. | Implement the Python class `DHTClient` described below.
Class description:
Get the latest data from the DHT sensor.
Method signatures and docstrings:
- def __init__(self, sensor, pin, name): Initialize the sensor.
- def update(self): Get the latest data the DHT sensor.
<|skeleton|>
class DHTClient:
"""Get the la... | 8de7966104911bca6f855a1755a6d71a07afb9de | <|skeleton|>
class DHTClient:
"""Get the latest data from the DHT sensor."""
def __init__(self, sensor, pin, name):
"""Initialize the sensor."""
<|body_0|>
def update(self):
"""Get the latest data the DHT sensor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DHTClient:
"""Get the latest data from the DHT sensor."""
def __init__(self, sensor, pin, name):
"""Initialize the sensor."""
self.sensor = sensor
self.pin = getattr(board, pin)
self.data = {}
self.name = name
def update(self):
"""Get the latest data t... | the_stack_v2_python_sparse | homeassistant/components/dht/sensor.py | AlexxIT/home-assistant | train | 9 |
fc172eb3354166984cc3c6c08ee8c531dfccc707 | [
"task = kwargs.pop('task', None)\nsuper(self.__class__, self).__init__(*args, **kwargs)\nself.fields['sub_tasks'].queryset = Task.objects.filter(parent=task) if task else Task.objects.none()",
"sub_tasks = self.cleaned_data['sub_tasks']\nfor sub_task in sub_tasks:\n if task.parent == sub_task:\n continu... | <|body_start_0|>
task = kwargs.pop('task', None)
super(self.__class__, self).__init__(*args, **kwargs)
self.fields['sub_tasks'].queryset = Task.objects.filter(parent=task) if task else Task.objects.none()
<|end_body_0|>
<|body_start_1|>
sub_tasks = self.cleaned_data['sub_tasks']
... | Form representing sub task | SubTaskForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubTaskForm:
"""Form representing sub task"""
def __init__(self, *args, **kwargs):
"""choice field values willl be filled during form load"""
<|body_0|>
def save(self, task):
"""save the sub task for a task"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_017116 | 5,361 | no_license | [
{
"docstring": "choice field values willl be filled during form load",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "save the sub task for a task",
"name": "save",
"signature": "def save(self, task)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001749 | Implement the Python class `SubTaskForm` described below.
Class description:
Form representing sub task
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): choice field values willl be filled during form load
- def save(self, task): save the sub task for a task | Implement the Python class `SubTaskForm` described below.
Class description:
Form representing sub task
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): choice field values willl be filled during form load
- def save(self, task): save the sub task for a task
<|skeleton|>
class SubTaskForm:
... | 7a337e0e3a20180b9564de68ab22620dc9aa1a36 | <|skeleton|>
class SubTaskForm:
"""Form representing sub task"""
def __init__(self, *args, **kwargs):
"""choice field values willl be filled during form load"""
<|body_0|>
def save(self, task):
"""save the sub task for a task"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubTaskForm:
"""Form representing sub task"""
def __init__(self, *args, **kwargs):
"""choice field values willl be filled during form load"""
task = kwargs.pop('task', None)
super(self.__class__, self).__init__(*args, **kwargs)
self.fields['sub_tasks'].queryset = Task.obje... | the_stack_v2_python_sparse | project_management/tasks/forms.py | raveena17/ILASM | train | 0 |
050db89f160115666822de13fc3fc9649184dc8c | [
"ent_home = self.get_enterprise_home_(config_file)\nif ent_home != None:\n from google3.enterprise.legacy.adminrunner import entconfig\n return entconfig.EntConfig(ent_home)\nraise Exception('%s is not a valid enterprise config file!' % config_file)\ndie = 5 / 0\nsys.exit(1)",
"if type(config_file) != type(... | <|body_start_0|>
ent_home = self.get_enterprise_home_(config_file)
if ent_home != None:
from google3.enterprise.legacy.adminrunner import entconfig
return entconfig.EntConfig(ent_home)
raise Exception('%s is not a valid enterprise config file!' % config_file)
die ... | ConfigFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFactory:
def CreateConfig(self, config_file, config_dir=None):
"""Given a config file name this returns a Config or an EntConfig object"""
<|body_0|>
def get_enterprise_home_(self, config_file):
"""Given a config file name we check if it looks like and enterpri... | stack_v2_sparse_classes_36k_train_017117 | 1,646 | no_license | [
{
"docstring": "Given a config file name this returns a Config or an EntConfig object",
"name": "CreateConfig",
"signature": "def CreateConfig(self, config_file, config_dir=None)"
},
{
"docstring": "Given a config file name we check if it looks like and enterprise config file and if it does, it ... | 2 | null | Implement the Python class `ConfigFactory` described below.
Class description:
Implement the ConfigFactory class.
Method signatures and docstrings:
- def CreateConfig(self, config_file, config_dir=None): Given a config file name this returns a Config or an EntConfig object
- def get_enterprise_home_(self, config_file... | Implement the Python class `ConfigFactory` described below.
Class description:
Implement the ConfigFactory class.
Method signatures and docstrings:
- def CreateConfig(self, config_file, config_dir=None): Given a config file name this returns a Config or an EntConfig object
- def get_enterprise_home_(self, config_file... | 18ecee580e284705b642b88c8e9594535993fead | <|skeleton|>
class ConfigFactory:
def CreateConfig(self, config_file, config_dir=None):
"""Given a config file name this returns a Config or an EntConfig object"""
<|body_0|>
def get_enterprise_home_(self, config_file):
"""Given a config file name we check if it looks like and enterpri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigFactory:
def CreateConfig(self, config_file, config_dir=None):
"""Given a config file name this returns a Config or an EntConfig object"""
ent_home = self.get_enterprise_home_(config_file)
if ent_home != None:
from google3.enterprise.legacy.adminrunner import entconfi... | the_stack_v2_python_sparse | enterprise/legacy/production/babysitter/config_factory.py | cash2one/BHWGoogleProject | train | 0 | |
364f5f76da9b3717726fc999e7a9d2a954a3afa8 | [
"self.global_word_count_vector_collection = None\nself.user_word_count_vector_collection = None\nself.global_word_frequency_vector_collection = None\nself.user_word_frequency_vector_collection = None\nself.relative_user_word_frequency_vector_collection = None",
"existing_global_wc_vector = self.global_word_count_... | <|body_start_0|>
self.global_word_count_vector_collection = None
self.user_word_count_vector_collection = None
self.global_word_frequency_vector_collection = None
self.user_word_frequency_vector_collection = None
self.relative_user_word_frequency_vector_collection = None
<|end_bo... | A class that stores data collection into MongoDB. @private global_word_count_vector_collection: global word count to be stored into MongoBD user_word_count_vector_collection: user word count to be stored into MongoDB global_word_frequency_vector_collection: global word frequency to be stored into MongoDB user_word_freq... | WordFrequencyMongoSetDAO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordFrequencyMongoSetDAO:
"""A class that stores data collection into MongoDB. @private global_word_count_vector_collection: global word count to be stored into MongoBD user_word_count_vector_collection: user word count to be stored into MongoDB global_word_frequency_vector_collection: global wor... | stack_v2_sparse_classes_36k_train_017118 | 6,565 | no_license | [
{
"docstring": "Initilize a new WordFrequencyMongoSetDAO class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Store global word count vector in descending order. @param global_wc_vector: global word vector to be stored",
"name": "store_global_word_count_vector",
... | 6 | stack_v2_sparse_classes_30k_train_021557 | Implement the Python class `WordFrequencyMongoSetDAO` described below.
Class description:
A class that stores data collection into MongoDB. @private global_word_count_vector_collection: global word count to be stored into MongoBD user_word_count_vector_collection: user word count to be stored into MongoDB global_word_... | Implement the Python class `WordFrequencyMongoSetDAO` described below.
Class description:
A class that stores data collection into MongoDB. @private global_word_count_vector_collection: global word count to be stored into MongoBD user_word_count_vector_collection: user word count to be stored into MongoDB global_word_... | 33a3fa38ad4dcdd54ff583da15dcd67c99ad9701 | <|skeleton|>
class WordFrequencyMongoSetDAO:
"""A class that stores data collection into MongoDB. @private global_word_count_vector_collection: global word count to be stored into MongoBD user_word_count_vector_collection: user word count to be stored into MongoDB global_word_frequency_vector_collection: global wor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordFrequencyMongoSetDAO:
"""A class that stores data collection into MongoDB. @private global_word_count_vector_collection: global word count to be stored into MongoBD user_word_count_vector_collection: user word count to be stored into MongoDB global_word_frequency_vector_collection: global word frequency t... | the_stack_v2_python_sparse | src/data_infrastructure/datastore/mongo/word_frequency/wf_mongo_set.py | ReinaKousaka/core | train | 0 |
82e382a8b0beb2e8801daa5804b527436e52b683 | [
"picking_id = super(mrp_production, self).action_confirm(cr, uid, ids)\nproduct_uom_obj = self.pool.get('product.uom')\nfor production in self.browse(cr, uid, ids):\n source = production.product_id.property_stock_production.id\n if not production.bom_id:\n continue\n for sub_product in production.bo... | <|body_start_0|>
picking_id = super(mrp_production, self).action_confirm(cr, uid, ids)
product_uom_obj = self.pool.get('product.uom')
for production in self.browse(cr, uid, ids):
source = production.product_id.property_stock_production.id
if not production.bom_id:
... | mrp_production | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mrp_production:
def action_confirm(self, cr, uid, ids):
"""Confirms production order and calculates quantity based on subproduct_type. @return: Newly generated picking Id."""
<|body_0|>
def _get_subproduct_factor(self, cr, uid, production_id, move_id=None, context=None):
... | stack_v2_sparse_classes_36k_train_017119 | 8,765 | no_license | [
{
"docstring": "Confirms production order and calculates quantity based on subproduct_type. @return: Newly generated picking Id.",
"name": "action_confirm",
"signature": "def action_confirm(self, cr, uid, ids)"
},
{
"docstring": "Compute the factor to compute the qty of procucts to produce for t... | 2 | null | Implement the Python class `mrp_production` described below.
Class description:
Implement the mrp_production class.
Method signatures and docstrings:
- def action_confirm(self, cr, uid, ids): Confirms production order and calculates quantity based on subproduct_type. @return: Newly generated picking Id.
- def _get_su... | Implement the Python class `mrp_production` described below.
Class description:
Implement the mrp_production class.
Method signatures and docstrings:
- def action_confirm(self, cr, uid, ids): Confirms production order and calculates quantity based on subproduct_type. @return: Newly generated picking Id.
- def _get_su... | e6b06ea17fa44e35e3c99a83c6f3ec433c33c894 | <|skeleton|>
class mrp_production:
def action_confirm(self, cr, uid, ids):
"""Confirms production order and calculates quantity based on subproduct_type. @return: Newly generated picking Id."""
<|body_0|>
def _get_subproduct_factor(self, cr, uid, production_id, move_id=None, context=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mrp_production:
def action_confirm(self, cr, uid, ids):
"""Confirms production order and calculates quantity based on subproduct_type. @return: Newly generated picking Id."""
picking_id = super(mrp_production, self).action_confirm(cr, uid, ids)
product_uom_obj = self.pool.get('product.... | the_stack_v2_python_sparse | mrp_byproduct/mrp_byproduct.py | rvalyi/openerp-addons | train | 2 | |
d7de809cb6ec6c52b1835df62a2df121ee02c79e | [
"author = g.user\nnotes = NoteModel.get_all_notes(author, archive='all')\nif not notes:\n abort(404, error=f'You have no notes yet')\nreturn (notes, 200)",
"author = g.user\nnote = NoteModel(author_id=author.id, **kwargs)\nnote.save()\nreturn (note, 201)"
] | <|body_start_0|>
author = g.user
notes = NoteModel.get_all_notes(author, archive='all')
if not notes:
abort(404, error=f'You have no notes yet')
return (notes, 200)
<|end_body_0|>
<|body_start_1|>
author = g.user
note = NoteModel(author_id=author.id, **kwargs... | NoteListResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoteListResource:
def get(self):
"""Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки"""
<|body_0|>
def post(self, **kwargs):
"""Создает заметку пользователя. Требуется аутентификация. :param kwargs: па... | stack_v2_sparse_classes_36k_train_017120 | 11,305 | no_license | [
{
"docstring": "Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Создает заметку пользователя. Требуется аутентификация. :param kwargs: параметры для создания заметк... | 2 | stack_v2_sparse_classes_30k_train_006945 | Implement the Python class `NoteListResource` described below.
Class description:
Implement the NoteListResource class.
Method signatures and docstrings:
- def get(self): Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки
- def post(self, **kwargs): Созд... | Implement the Python class `NoteListResource` described below.
Class description:
Implement the NoteListResource class.
Method signatures and docstrings:
- def get(self): Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки
- def post(self, **kwargs): Созд... | adb9a3f4524ab76e8ba656344e2ed452e87b577c | <|skeleton|>
class NoteListResource:
def get(self):
"""Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки"""
<|body_0|>
def post(self, **kwargs):
"""Создает заметку пользователя. Требуется аутентификация. :param kwargs: па... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoteListResource:
def get(self):
"""Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки"""
author = g.user
notes = NoteModel.get_all_notes(author, archive='all')
if not notes:
abort(404, error=f'You have... | the_stack_v2_python_sparse | api/resources/note.py | UshakovAleksandr/Blog | train | 1 | |
cfbc94c800993689be4e37a2200eb575104ef2fa | [
"self.precip_cube = set_up_precip_probability_cube()\nself.coord_name = find_threshold_coordinate(self.precip_cube).name()\nself.precip_cube.coord(self.coord_name).convert_units('mm h-1')\nself.expected_data = self.precip_cube[:2].data",
"values = [0.03, 0.1]\nresult = create_sorted_lambda_constraint(self.coord_n... | <|body_start_0|>
self.precip_cube = set_up_precip_probability_cube()
self.coord_name = find_threshold_coordinate(self.precip_cube).name()
self.precip_cube.coord(self.coord_name).convert_units('mm h-1')
self.expected_data = self.precip_cube[:2].data
<|end_body_0|>
<|body_start_1|>
... | Test that a lambda constraint is created. | Test_create_sorted_lambda_constraint | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_create_sorted_lambda_constraint:
"""Test that a lambda constraint is created."""
def setUp(self):
"""Set up cube with testing lambda constraint."""
<|body_0|>
def test_basic_ascending(self):
"""Test that a constraint is created, if the input coordinates are ... | stack_v2_sparse_classes_36k_train_017121 | 4,264 | permissive | [
{
"docstring": "Set up cube with testing lambda constraint.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that a constraint is created, if the input coordinates are ascending.",
"name": "test_basic_ascending",
"signature": "def test_basic_ascending(self)"
},... | 4 | null | Implement the Python class `Test_create_sorted_lambda_constraint` described below.
Class description:
Test that a lambda constraint is created.
Method signatures and docstrings:
- def setUp(self): Set up cube with testing lambda constraint.
- def test_basic_ascending(self): Test that a constraint is created, if the i... | Implement the Python class `Test_create_sorted_lambda_constraint` described below.
Class description:
Test that a lambda constraint is created.
Method signatures and docstrings:
- def setUp(self): Set up cube with testing lambda constraint.
- def test_basic_ascending(self): Test that a constraint is created, if the i... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_create_sorted_lambda_constraint:
"""Test that a lambda constraint is created."""
def setUp(self):
"""Set up cube with testing lambda constraint."""
<|body_0|>
def test_basic_ascending(self):
"""Test that a constraint is created, if the input coordinates are ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_create_sorted_lambda_constraint:
"""Test that a lambda constraint is created."""
def setUp(self):
"""Set up cube with testing lambda constraint."""
self.precip_cube = set_up_precip_probability_cube()
self.coord_name = find_threshold_coordinate(self.precip_cube).name()
... | the_stack_v2_python_sparse | improver_tests/utilities/test_cube_constraints.py | metoppv/improver | train | 101 |
40756d7cee79e84ad3a929ec359951f2543e759e | [
"result = self.init_parameter()\nquestion_id = self.get_argument('question_id')\nres = self.question_model.get(question_id).get('_source')\nresult['data'] = res\nreturn result",
"question = self.get_argument('question')\nsimilar_question = self.get_argument('similar_question', '')\nanswer_id = self.get_argument('... | <|body_start_0|>
result = self.init_parameter()
question_id = self.get_argument('question_id')
res = self.question_model.get(question_id).get('_source')
result['data'] = res
return result
<|end_body_0|>
<|body_start_1|>
question = self.get_argument('question')
si... | QuestionInfoDetailHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionInfoDetailHandler:
def get(self, *args, **kwargs):
"""获取问题详细信息 :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, *args, **kwargs):
"""新建问题信息 :param args: :param kwargs: :return:"""
<|body_1|>
def put(self, *args, **kwargs):
... | stack_v2_sparse_classes_36k_train_017122 | 2,671 | no_license | [
{
"docstring": "获取问题详细信息 :param args: :param kwargs: :return:",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "新建问题信息 :param args: :param kwargs: :return:",
"name": "post",
"signature": "def post(self, *args, **kwargs)"
},
{
"docstring": "修改问题信息 :... | 3 | stack_v2_sparse_classes_30k_train_013351 | Implement the Python class `QuestionInfoDetailHandler` described below.
Class description:
Implement the QuestionInfoDetailHandler class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): 获取问题详细信息 :param args: :param kwargs: :return:
- def post(self, *args, **kwargs): 新建问题信息 :param args: :param kwar... | Implement the Python class `QuestionInfoDetailHandler` described below.
Class description:
Implement the QuestionInfoDetailHandler class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): 获取问题详细信息 :param args: :param kwargs: :return:
- def post(self, *args, **kwargs): 新建问题信息 :param args: :param kwar... | 9781b183cf168832b3c962d420e7f0a63287c4db | <|skeleton|>
class QuestionInfoDetailHandler:
def get(self, *args, **kwargs):
"""获取问题详细信息 :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, *args, **kwargs):
"""新建问题信息 :param args: :param kwargs: :return:"""
<|body_1|>
def put(self, *args, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionInfoDetailHandler:
def get(self, *args, **kwargs):
"""获取问题详细信息 :param args: :param kwargs: :return:"""
result = self.init_parameter()
question_id = self.get_argument('question_id')
res = self.question_model.get(question_id).get('_source')
result['data'] = res
... | the_stack_v2_python_sparse | chat_bot/handlers/bot_manage/question_info.py | jiaojianglong/MyBot | train | 0 | |
4908dd54aeb1bc2aed9b9f53f6a0ae5e7664d401 | [
"self.min_heap = []\nself.max_heap = []\nself.first = 0\nself.second = 0\nself.count = 0",
"self.count += 1\nif self.count == 1:\n self.first = num\n return\nif self.count == 2:\n self.second = num\n return\nif self.count == 3:\n min_num = min(self.first, self.second)\n max_num = max(self.first,... | <|body_start_0|>
self.min_heap = []
self.max_heap = []
self.first = 0
self.second = 0
self.count = 0
<|end_body_0|>
<|body_start_1|>
self.count += 1
if self.count == 1:
self.first = num
return
if self.count == 2:
self.s... | 372ms | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
"""372ms"""
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_017123 | 4,302 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | null | Implement the Python class `MedianFinder` described below.
Class description:
372ms
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: void
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
372ms
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: void
- def findMedian(self): :rtype: float
<|skeleton|>
class MedianFinder:
"""372ms"""
... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class MedianFinder:
"""372ms"""
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedianFinder:
"""372ms"""
def __init__(self):
"""initialize your data structure here."""
self.min_heap = []
self.max_heap = []
self.first = 0
self.second = 0
self.count = 0
def addNum(self, num):
""":type num: int :rtype: void"""
self.c... | the_stack_v2_python_sparse | FindMedianFromDataStream_HARD_295.py | 953250587/leetcode-python | train | 2 |
f61e1501b64bb58aac7b0f10a83e2a74a025aee2 | [
"self.passengers_with_carry_on = MyStack()\nself.passengers_without_carry_on = MyStack()\nself.max_passengers_limit = max_passengers_limit",
"if self.passengers_with_carry_on.size() + self.passengers_without_carry_on.size() >= self.max_passengers_limit:\n return False\nif passenger.has_carry_on:\n self.pass... | <|body_start_0|>
self.passengers_with_carry_on = MyStack()
self.passengers_without_carry_on = MyStack()
self.max_passengers_limit = max_passengers_limit
<|end_body_0|>
<|body_start_1|>
if self.passengers_with_carry_on.size() + self.passengers_without_carry_on.size() >= self.max_passenge... | Aircraft | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Aircraft:
def __init__(self, max_passengers_limit):
"""Constructor aircraft class :param max_passengers_limit: maximum passengers limit"""
<|body_0|>
def board_passenger(self, passenger: Passenger):
"""Board passenger into aircraft :param passenger: passenger :return... | stack_v2_sparse_classes_36k_train_017124 | 2,965 | no_license | [
{
"docstring": "Constructor aircraft class :param max_passengers_limit: maximum passengers limit",
"name": "__init__",
"signature": "def __init__(self, max_passengers_limit)"
},
{
"docstring": "Board passenger into aircraft :param passenger: passenger :return: boolean",
"name": "board_passen... | 4 | stack_v2_sparse_classes_30k_train_019760 | Implement the Python class `Aircraft` described below.
Class description:
Implement the Aircraft class.
Method signatures and docstrings:
- def __init__(self, max_passengers_limit): Constructor aircraft class :param max_passengers_limit: maximum passengers limit
- def board_passenger(self, passenger: Passenger): Boar... | Implement the Python class `Aircraft` described below.
Class description:
Implement the Aircraft class.
Method signatures and docstrings:
- def __init__(self, max_passengers_limit): Constructor aircraft class :param max_passengers_limit: maximum passengers limit
- def board_passenger(self, passenger: Passenger): Boar... | 7a52bf5bdf95ca758808112ad0b57a6af1a60dc4 | <|skeleton|>
class Aircraft:
def __init__(self, max_passengers_limit):
"""Constructor aircraft class :param max_passengers_limit: maximum passengers limit"""
<|body_0|>
def board_passenger(self, passenger: Passenger):
"""Board passenger into aircraft :param passenger: passenger :return... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Aircraft:
def __init__(self, max_passengers_limit):
"""Constructor aircraft class :param max_passengers_limit: maximum passengers limit"""
self.passengers_with_carry_on = MyStack()
self.passengers_without_carry_on = MyStack()
self.max_passengers_limit = max_passengers_limit
... | the_stack_v2_python_sparse | AiRit/Aircraft.py | beetisushruth/Python-projects | train | 0 | |
444190b445f222725ff943ea38399cb9a30d435e | [
"if copy:\n self.data = data.copy()\nelse:\n self.data = data",
"if exclude_pi:\n pxx = pxx[:-1]\npxx_length = len(pxx)\ntest_statistic = np.max(pxx) / sum(pxx)\nupper = np.floor(1 / test_statistic).astype('int')\nif pxx_length > 700:\n p_value = 1 - (1 - np.exp(-pxx_length * test_statistic)) ** pxx_l... | <|body_start_0|>
if copy:
self.data = data.copy()
else:
self.data = data
<|end_body_0|>
<|body_start_1|>
if exclude_pi:
pxx = pxx[:-1]
pxx_length = len(pxx)
test_statistic = np.max(pxx) / sum(pxx)
upper = np.floor(1 / test_statistic).a... | Polling detector using the Periodogram to detect strong frequencies. Attributes ---------- data: DataFrame Dataframe containing the data to be analysed. Must contain a column of edges and a column of timestamps Methods ------- detect_polling(timestamps, process_start, process_end, interval) Detect strong periodic frequ... | PeriodogramPollingDetector | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"EPL-1.0",
"GPL-1.0-or-later",
"LGPL-2.1-only",
"MPL-2.0",
"Python-2.0",
"PSF-2.0",
"LicenseRef-scancode-python-cwi",
"GPL-2.0-or-later",
"LGPL-2.1-or-later... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeriodogramPollingDetector:
"""Polling detector using the Periodogram to detect strong frequencies. Attributes ---------- data: DataFrame Dataframe containing the data to be analysed. Must contain a column of edges and a column of timestamps Methods ------- detect_polling(timestamps, process_star... | stack_v2_sparse_classes_36k_train_017125 | 7,747 | permissive | [
{
"docstring": "Create periodogram polling detector. Parameters ---------- data: DataFrame Dataframe containing the data to be analysed. Must contain a column of edges and a column of timestamps copy: bool A bool to indicate whether to copy the dataframe supplied to data",
"name": "__init__",
"signature... | 4 | null | Implement the Python class `PeriodogramPollingDetector` described below.
Class description:
Polling detector using the Periodogram to detect strong frequencies. Attributes ---------- data: DataFrame Dataframe containing the data to be analysed. Must contain a column of edges and a column of timestamps Methods ------- ... | Implement the Python class `PeriodogramPollingDetector` described below.
Class description:
Polling detector using the Periodogram to detect strong frequencies. Attributes ---------- data: DataFrame Dataframe containing the data to be analysed. Must contain a column of edges and a column of timestamps Methods ------- ... | 55c6c1aebb8505a220046705b7c74194f83d62f3 | <|skeleton|>
class PeriodogramPollingDetector:
"""Polling detector using the Periodogram to detect strong frequencies. Attributes ---------- data: DataFrame Dataframe containing the data to be analysed. Must contain a column of edges and a column of timestamps Methods ------- detect_polling(timestamps, process_star... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PeriodogramPollingDetector:
"""Polling detector using the Periodogram to detect strong frequencies. Attributes ---------- data: DataFrame Dataframe containing the data to be analysed. Must contain a column of edges and a column of timestamps Methods ------- detect_polling(timestamps, process_start, process_en... | the_stack_v2_python_sparse | msticpy/analysis/polling_detection.py | rhaug77/msticpy | train | 0 |
20deb9b033922f28158bbe6025d0e67d8ae19838 | [
"self.input_path = input_path\npath = Path(input_path)\nself.gen_path = path.parent\njsonfile = 'organized.json'\nobj_props = lab2mat.load(os.path.join(self.gen_path, jsonfile))\nself.rawdata_path = os.path.join(self.gen_path, 'filt_data')\nverpred_path = 'verified_predictions'\nobj_props.update({'verpred_path': ve... | <|body_start_0|>
self.input_path = input_path
path = Path(input_path)
self.gen_path = path.parent
jsonfile = 'organized.json'
obj_props = lab2mat.load(os.path.join(self.gen_path, jsonfile))
self.rawdata_path = os.path.join(self.gen_path, 'filt_data')
verpred_path ... | Class for User verification of detected seizures | UserVerify | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserVerify:
"""Class for User verification of detected seizures"""
def __init__(self, input_path):
"""lab2mat(main_path) Parameters ---------- input_path : Str, Path to raw data."""
<|body_0|>
def get_feature_pred(self, file_id):
"""get_feature_pred(self, file_id... | stack_v2_sparse_classes_36k_train_017126 | 10,529 | permissive | [
{
"docstring": "lab2mat(main_path) Parameters ---------- input_path : Str, Path to raw data.",
"name": "__init__",
"signature": "def __init__(self, input_path)"
},
{
"docstring": "get_feature_pred(self, file_id) Parameters ---------- file_id : Str Returns ------- data : 3d Numpy Array (1D = segm... | 5 | stack_v2_sparse_classes_30k_train_020631 | Implement the Python class `UserVerify` described below.
Class description:
Class for User verification of detected seizures
Method signatures and docstrings:
- def __init__(self, input_path): lab2mat(main_path) Parameters ---------- input_path : Str, Path to raw data.
- def get_feature_pred(self, file_id): get_featu... | Implement the Python class `UserVerify` described below.
Class description:
Class for User verification of detected seizures
Method signatures and docstrings:
- def __init__(self, input_path): lab2mat(main_path) Parameters ---------- input_path : Str, Path to raw data.
- def get_feature_pred(self, file_id): get_featu... | fd238749a8b80af1bd0902f737bc9017c4e29756 | <|skeleton|>
class UserVerify:
"""Class for User verification of detected seizures"""
def __init__(self, input_path):
"""lab2mat(main_path) Parameters ---------- input_path : Str, Path to raw data."""
<|body_0|>
def get_feature_pred(self, file_id):
"""get_feature_pred(self, file_id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserVerify:
"""Class for User verification of detected seizures"""
def __init__(self, input_path):
"""lab2mat(main_path) Parameters ---------- input_path : Str, Path to raw data."""
self.input_path = input_path
path = Path(input_path)
self.gen_path = path.parent
js... | the_stack_v2_python_sparse | user_gui/UserVerify_instant.py | bhargavaganti/logic_seizedetect | train | 0 |
7ba6afe873e5fe4feb1bed2c8f9a3f5525b8046e | [
"template_path = os.path.join(os.path.dirname(__file__), '..', 'html_templates', 'acl.html')\ntemplate_args = {'users': model.AuthenticatedUser.all()}\nself.response.out.write(template.render(template_path, template_args))",
"user = users.User(self.request.get('email'))\naction = self.request.get('action')\nif ac... | <|body_start_0|>
template_path = os.path.join(os.path.dirname(__file__), '..', 'html_templates', 'acl.html')
template_args = {'users': model.AuthenticatedUser.all()}
self.response.out.write(template.render(template_path, template_args))
<|end_body_0|>
<|body_start_1|>
user = users.User(... | A form to edit global application permissions. | ACLHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ACLHandler:
"""A form to edit global application permissions."""
def get(self):
"""Displays a list of authenticated users and a from to edit them."""
<|body_0|>
def post(self):
"""Adds or deletes an authenticated user then displays the ACL form."""
<|body... | stack_v2_sparse_classes_36k_train_017127 | 1,779 | permissive | [
{
"docstring": "Displays a list of authenticated users and a from to edit them.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Adds or deletes an authenticated user then displays the ACL form.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011226 | Implement the Python class `ACLHandler` described below.
Class description:
A form to edit global application permissions.
Method signatures and docstrings:
- def get(self): Displays a list of authenticated users and a from to edit them.
- def post(self): Adds or deletes an authenticated user then displays the ACL fo... | Implement the Python class `ACLHandler` described below.
Class description:
A form to edit global application permissions.
Method signatures and docstrings:
- def get(self): Displays a list of authenticated users and a from to edit them.
- def post(self): Adds or deletes an authenticated user then displays the ACL fo... | d675139606cfa362ca0239c19995efabecb8edf2 | <|skeleton|>
class ACLHandler:
"""A form to edit global application permissions."""
def get(self):
"""Displays a list of authenticated users and a from to edit them."""
<|body_0|>
def post(self):
"""Adds or deletes an authenticated user then displays the ACL form."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ACLHandler:
"""A form to edit global application permissions."""
def get(self):
"""Displays a list of authenticated users and a from to edit them."""
template_path = os.path.join(os.path.dirname(__file__), '..', 'html_templates', 'acl.html')
template_args = {'users': model.Authent... | the_stack_v2_python_sparse | layermanager/handlers/acl.py | deleted/kml-layer-manager | train | 0 |
fa09705729613b29b27d4a87f6337ebe4334c9b5 | [
"nums.sort()\nfor i in range(1, len(nums)):\n if nums[i] == nums[i - 1]:\n return True\nreturn False",
"o = set(nums)\nif len(nums) != len(s):\n return True\nreturn False",
"m = defaultdict(int)\nfor num in nums:\n if m[num]:\n return True\n m[num] += 1\nreturn False"
] | <|body_start_0|>
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return True
return False
<|end_body_0|>
<|body_start_1|>
o = set(nums)
if len(nums) != len(s):
return True
return False
<|end_body_1|>
<|body_st... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def contains_duplicate1(self, nums: List[int]) -> bool:
"""n(log(n)) Using sort with one loop :param nums: :return:"""
<|body_0|>
def contains_duplicate2(self, nums: List[int]) -> bool:
"""O(n), space = O(n) Using sort with one loop :param nums: :return:"""... | stack_v2_sparse_classes_36k_train_017128 | 1,740 | permissive | [
{
"docstring": "n(log(n)) Using sort with one loop :param nums: :return:",
"name": "contains_duplicate1",
"signature": "def contains_duplicate1(self, nums: List[int]) -> bool"
},
{
"docstring": "O(n), space = O(n) Using sort with one loop :param nums: :return:",
"name": "contains_duplicate2"... | 3 | stack_v2_sparse_classes_30k_train_006359 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def contains_duplicate1(self, nums: List[int]) -> bool: n(log(n)) Using sort with one loop :param nums: :return:
- def contains_duplicate2(self, nums: List[int]) -> bool: O(n), s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def contains_duplicate1(self, nums: List[int]) -> bool: n(log(n)) Using sort with one loop :param nums: :return:
- def contains_duplicate2(self, nums: List[int]) -> bool: O(n), s... | 47c406bda760c4fb3256150e0eacd2db80c2477e | <|skeleton|>
class Solution:
def contains_duplicate1(self, nums: List[int]) -> bool:
"""n(log(n)) Using sort with one loop :param nums: :return:"""
<|body_0|>
def contains_duplicate2(self, nums: List[int]) -> bool:
"""O(n), space = O(n) Using sort with one loop :param nums: :return:"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def contains_duplicate1(self, nums: List[int]) -> bool:
"""n(log(n)) Using sort with one loop :param nums: :return:"""
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return True
return False
def contains_duplicate... | the_stack_v2_python_sparse | udemy_leetcode/Hash Map Facebook Interview Questions solutions/contain_duplicate.py | dipsuji/coding_pyhton | train | 0 | |
942141b19900eda88e50fa78cdad2de0a173b99c | [
"self.user = user\nself.host = host\nself.port = port\nself.clients[user] = client\nself._ensure_client_for(user)\nself.logger = QChatLogger('QChatClientRPCServer-{}'.format(user))\nself.logger.debug('Starting server for {} at {}:{}'.format(user, host, port))",
"self._ensure_client_for(user)\ntry:\n self.clien... | <|body_start_0|>
self.user = user
self.host = host
self.port = port
self.clients[user] = client
self._ensure_client_for(user)
self.logger = QChatLogger('QChatClientRPCServer-{}'.format(user))
self.logger.debug('Starting server for {} at {}:{}'.format(user, host, p... | An RPC Server that connects to a QChatServer | QChatRPCServer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QChatRPCServer:
"""An RPC Server that connects to a QChatServer"""
def __init__(self, user, host, port, client):
"""Initializes the RPC server :param user: str The name of the QChatServer :param host: str The host to receive RPC commands at :param port: int The port to receive RPC co... | stack_v2_sparse_classes_36k_train_017129 | 5,230 | permissive | [
{
"docstring": "Initializes the RPC server :param user: str The name of the QChatServer :param host: str The host to receive RPC commands at :param port: int The port to receive RPC commands at :param client: `~qchat.client.QChatClient` The QChatClient to interact with",
"name": "__init__",
"signature":... | 4 | stack_v2_sparse_classes_30k_train_014661 | Implement the Python class `QChatRPCServer` described below.
Class description:
An RPC Server that connects to a QChatServer
Method signatures and docstrings:
- def __init__(self, user, host, port, client): Initializes the RPC server :param user: str The name of the QChatServer :param host: str The host to receive RP... | Implement the Python class `QChatRPCServer` described below.
Class description:
An RPC Server that connects to a QChatServer
Method signatures and docstrings:
- def __init__(self, user, host, port, client): Initializes the RPC server :param user: str The name of the QChatServer :param host: str The host to receive RP... | a393d530b9d289ba2a75682cd1d4a07d40776785 | <|skeleton|>
class QChatRPCServer:
"""An RPC Server that connects to a QChatServer"""
def __init__(self, user, host, port, client):
"""Initializes the RPC server :param user: str The name of the QChatServer :param host: str The host to receive RPC commands at :param port: int The port to receive RPC co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QChatRPCServer:
"""An RPC Server that connects to a QChatServer"""
def __init__(self, user, host, port, client):
"""Initializes the RPC server :param user: str The name of the QChatServer :param host: str The host to receive RPC commands at :param port: int The port to receive RPC commands at :pa... | the_stack_v2_python_sparse | qchat/rpc.py | mdskrzypczyk/QChat | train | 4 |
dec79f5df710d51e895e49587faf92ef4db943b8 | [
"self.smtpserver = smtpserver\nself.sender = sender\nself.password = password",
"msg = MIMEMultipart()\nmsg.attach(MIMEText(content, 'plain', 'utf-8'))\nmsg['Subject'] = Header(subject, 'utf-8')\nmsg['From'] = username + '<' + self.sender + '>'\nmsg['To'] = ','.join(receiver)\natt1 = MIMEApplication(open(filename... | <|body_start_0|>
self.smtpserver = smtpserver
self.sender = sender
self.password = password
<|end_body_0|>
<|body_start_1|>
msg = MIMEMultipart()
msg.attach(MIMEText(content, 'plain', 'utf-8'))
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = username + '<... | SendEmail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendEmail:
def __init__(self, smtpserver, sender, password):
"""定义发送邮件需要的参数 :param smtpserver: smtp服务器 :param sender: 发送者的邮箱 :param password: 登录smtp服务器的密码"""
<|body_0|>
def generate_msg(self, subject, content, username, receiver, filename):
"""生成邮件正文 :param subject: ... | stack_v2_sparse_classes_36k_train_017130 | 2,023 | no_license | [
{
"docstring": "定义发送邮件需要的参数 :param smtpserver: smtp服务器 :param sender: 发送者的邮箱 :param password: 登录smtp服务器的密码",
"name": "__init__",
"signature": "def __init__(self, smtpserver, sender, password)"
},
{
"docstring": "生成邮件正文 :param subject: 邮件标题 :param content: 邮件内容 :return:",
"name": "generate_ms... | 3 | stack_v2_sparse_classes_30k_train_021117 | Implement the Python class `SendEmail` described below.
Class description:
Implement the SendEmail class.
Method signatures and docstrings:
- def __init__(self, smtpserver, sender, password): 定义发送邮件需要的参数 :param smtpserver: smtp服务器 :param sender: 发送者的邮箱 :param password: 登录smtp服务器的密码
- def generate_msg(self, subject, c... | Implement the Python class `SendEmail` described below.
Class description:
Implement the SendEmail class.
Method signatures and docstrings:
- def __init__(self, smtpserver, sender, password): 定义发送邮件需要的参数 :param smtpserver: smtp服务器 :param sender: 发送者的邮箱 :param password: 登录smtp服务器的密码
- def generate_msg(self, subject, c... | 6837a07ff200b610e7ba799a52543493848b6026 | <|skeleton|>
class SendEmail:
def __init__(self, smtpserver, sender, password):
"""定义发送邮件需要的参数 :param smtpserver: smtp服务器 :param sender: 发送者的邮箱 :param password: 登录smtp服务器的密码"""
<|body_0|>
def generate_msg(self, subject, content, username, receiver, filename):
"""生成邮件正文 :param subject: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SendEmail:
def __init__(self, smtpserver, sender, password):
"""定义发送邮件需要的参数 :param smtpserver: smtp服务器 :param sender: 发送者的邮箱 :param password: 登录smtp服务器的密码"""
self.smtpserver = smtpserver
self.sender = sender
self.password = password
def generate_msg(self, subject, content,... | the_stack_v2_python_sparse | lib/send_email.py | liwei123a/APITestFrame | train | 0 | |
0fd4ddef4d8107b5aab58de7df9b6bd41797d1be | [
"if numbering is None:\n numbering = covid.load_aligned_parent_seq()\nif aaindex_features is None:\n aaindex_features = helper.read_csv(AAINDEX_FILENAME)\nself._numbering = numbering\nself._indices = numbering.loc[numbering['pos'].isin(positions), 'index'].values\nself._token_to_aaindex = {token: features.val... | <|body_start_0|>
if numbering is None:
numbering = covid.load_aligned_parent_seq()
if aaindex_features is None:
aaindex_features = helper.read_csv(AAINDEX_FILENAME)
self._numbering = numbering
self._indices = numbering.loc[numbering['pos'].isin(positions), 'index'... | Encodes (featurizes) an amino acid sequence for making predictions. Onehot- and AAIndex encodes each sequence, and concatenates the resulting encodings. | SequenceEncoder | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceEncoder:
"""Encodes (featurizes) an amino acid sequence for making predictions. Onehot- and AAIndex encodes each sequence, and concatenates the resulting encodings."""
def __init__(self, numbering=None, aaindex_features=None, num_aaindex_features=10, positions=covid.ALLOWED_POS):
... | stack_v2_sparse_classes_36k_train_017131 | 9,504 | permissive | [
{
"docstring": "Creates an instance of this class. Args: numbering: IMGT numbering table. Will be read from disk if `None`. aaindex_features: AAIndex matrix. Will be read from disk if `None`. num_aaindex_features: The number of AAIndex features to be used for encoding. positions: The IMGT positions that were us... | 4 | stack_v2_sparse_classes_30k_train_009961 | Implement the Python class `SequenceEncoder` described below.
Class description:
Encodes (featurizes) an amino acid sequence for making predictions. Onehot- and AAIndex encodes each sequence, and concatenates the resulting encodings.
Method signatures and docstrings:
- def __init__(self, numbering=None, aaindex_featu... | Implement the Python class `SequenceEncoder` described below.
Class description:
Encodes (featurizes) an amino acid sequence for making predictions. Onehot- and AAIndex encodes each sequence, and concatenates the resulting encodings.
Method signatures and docstrings:
- def __init__(self, numbering=None, aaindex_featu... | 1b4e7db5f90bcb4f80803383a81d8613ebfdfeec | <|skeleton|>
class SequenceEncoder:
"""Encodes (featurizes) an amino acid sequence for making predictions. Onehot- and AAIndex encodes each sequence, and concatenates the resulting encodings."""
def __init__(self, numbering=None, aaindex_features=None, num_aaindex_features=10, positions=covid.ALLOWED_POS):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceEncoder:
"""Encodes (featurizes) an amino acid sequence for making predictions. Onehot- and AAIndex encodes each sequence, and concatenates the resulting encodings."""
def __init__(self, numbering=None, aaindex_features=None, num_aaindex_features=10, positions=covid.ALLOWED_POS):
"""Creat... | the_stack_v2_python_sparse | covid_vhh_design/models.py | antonpolishko/google-research | train | 0 |
589857bd6234392e36f0991be93fe854536c96f9 | [
"self.sys = platform.system()\nself.name = netName or settings.ADSL_NAME\nself.url = url or settings.IP138_URL\nself.token = token or settings.IP138_TOKEN\nself.user = user or settings.ADSL_USER\nself.password = password or settings.ADSL_PASSWORD\nself.ip = self.refreshIP()\nself.status = False\nif self.sys == 'Win... | <|body_start_0|>
self.sys = platform.system()
self.name = netName or settings.ADSL_NAME
self.url = url or settings.IP138_URL
self.token = token or settings.IP138_TOKEN
self.user = user or settings.ADSL_USER
self.password = password or settings.ADSL_PASSWORD
self.i... | ADSL_Tool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ADSL_Tool:
def __init__(self, netName='adslproxy', user=None, password=None, url=None, token=None):
"""user: windows使用者的adsl用户账号 password: windows使用者的adsl密码 url: ip138的ip查询临时url token: ip138提供的ip查询接口 当同时使用了url与token参数,默认会调用token返回ip地址"""
<|body_0|>
def cmd(self, commands):
... | stack_v2_sparse_classes_36k_train_017132 | 3,858 | no_license | [
{
"docstring": "user: windows使用者的adsl用户账号 password: windows使用者的adsl密码 url: ip138的ip查询临时url token: ip138提供的ip查询接口 当同时使用了url与token参数,默认会调用token返回ip地址",
"name": "__init__",
"signature": "def __init__(self, netName='adslproxy', user=None, password=None, url=None, token=None)"
},
{
"docstring": "comm... | 6 | null | Implement the Python class `ADSL_Tool` described below.
Class description:
Implement the ADSL_Tool class.
Method signatures and docstrings:
- def __init__(self, netName='adslproxy', user=None, password=None, url=None, token=None): user: windows使用者的adsl用户账号 password: windows使用者的adsl密码 url: ip138的ip查询临时url token: ip138... | Implement the Python class `ADSL_Tool` described below.
Class description:
Implement the ADSL_Tool class.
Method signatures and docstrings:
- def __init__(self, netName='adslproxy', user=None, password=None, url=None, token=None): user: windows使用者的adsl用户账号 password: windows使用者的adsl密码 url: ip138的ip查询临时url token: ip138... | 54bf8cc8fba72a1177ce3279a3e0f7a7a8fc754e | <|skeleton|>
class ADSL_Tool:
def __init__(self, netName='adslproxy', user=None, password=None, url=None, token=None):
"""user: windows使用者的adsl用户账号 password: windows使用者的adsl密码 url: ip138的ip查询临时url token: ip138提供的ip查询接口 当同时使用了url与token参数,默认会调用token返回ip地址"""
<|body_0|>
def cmd(self, commands):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ADSL_Tool:
def __init__(self, netName='adslproxy', user=None, password=None, url=None, token=None):
"""user: windows使用者的adsl用户账号 password: windows使用者的adsl密码 url: ip138的ip查询临时url token: ip138提供的ip查询接口 当同时使用了url与token参数,默认会调用token返回ip地址"""
self.sys = platform.system()
self.name = netName... | the_stack_v2_python_sparse | adsl_py/adsl.py | crystalxiao/myspider | train | 0 | |
7f21dcf95b011292844fa197982adee16c80fead | [
"super().__init__()\nsqueeze_channels = round(in_channels * squeeze_ratio)\nif squeeze_channels < 2:\n squeeze_channels = 2\nself.conv_squeeze = Conv(conv, in_channels=in_channels, out_channels=squeeze_channels, kernel_size=1, bias=True, padding=0)\nself.act = Activation(activation)\nself.conv_excite = Conv(conv... | <|body_start_0|>
super().__init__()
squeeze_channels = round(in_channels * squeeze_ratio)
if squeeze_channels < 2:
squeeze_channels = 2
self.conv_squeeze = Conv(conv, in_channels=in_channels, out_channels=squeeze_channels, kernel_size=1, bias=True, padding=0)
self.act... | SqueezeAndExcite | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SqueezeAndExcite:
def __init__(self, in_channels: int, squeeze_ratio: float=0.25, conv: str='conv', activation: str='relu', gate_activation: str='sigmoid', **kwargs) -> None:
"""Squeeze-and-Excitation block. https://arxiv.org/abs/1709.01507 Parameters ---------- in_channels : int Number ... | stack_v2_sparse_classes_36k_train_017133 | 11,576 | permissive | [
{
"docstring": "Squeeze-and-Excitation block. https://arxiv.org/abs/1709.01507 Parameters ---------- in_channels : int Number of input channels. squeeze_ratio : float, default=0.25 Ratio of squeeze. conv : str, default=\"conv\" Convolution layer type. activation : str, default=\"relu\" Activation layer after sq... | 2 | null | Implement the Python class `SqueezeAndExcite` described below.
Class description:
Implement the SqueezeAndExcite class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, squeeze_ratio: float=0.25, conv: str='conv', activation: str='relu', gate_activation: str='sigmoid', **kwargs) -> None: Squee... | Implement the Python class `SqueezeAndExcite` described below.
Class description:
Implement the SqueezeAndExcite class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, squeeze_ratio: float=0.25, conv: str='conv', activation: str='relu', gate_activation: str='sigmoid', **kwargs) -> None: Squee... | 7f79405012eb934b419bbdba8de23f35e840ca85 | <|skeleton|>
class SqueezeAndExcite:
def __init__(self, in_channels: int, squeeze_ratio: float=0.25, conv: str='conv', activation: str='relu', gate_activation: str='sigmoid', **kwargs) -> None:
"""Squeeze-and-Excitation block. https://arxiv.org/abs/1709.01507 Parameters ---------- in_channels : int Number ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SqueezeAndExcite:
def __init__(self, in_channels: int, squeeze_ratio: float=0.25, conv: str='conv', activation: str='relu', gate_activation: str='sigmoid', **kwargs) -> None:
"""Squeeze-and-Excitation block. https://arxiv.org/abs/1709.01507 Parameters ---------- in_channels : int Number of input chann... | the_stack_v2_python_sparse | cellseg_models_pytorch/modules/attention_modules.py | okunator/cellseg_models.pytorch | train | 43 | |
1f2acfcf090ff9f2b71282c325ec1f827e6b572a | [
"email = field.data.lower()\nif User.query.filter(func.lower(User.email) == email).first():\n raise ValidationError('Email already in use.')\nif current_app.config['MAIL_DOMAIN'] not in email:\n raise ValidationError('Not an allowed email domain')",
"username = field.data.lower()\nif User.query.filter(func.... | <|body_start_0|>
email = field.data.lower()
if User.query.filter(func.lower(User.email) == email).first():
raise ValidationError('Email already in use.')
if current_app.config['MAIL_DOMAIN'] not in email:
raise ValidationError('Not an allowed email domain')
<|end_body_0|>... | Registers a new user Attributes: email: takes the user's email from the StringField from wtforms username: takes the user's username from the StringField from wtforms password: takes the user's password from the PasswordField from wtforms password2: takes the user's password from the PasswordField from wtforms a second... | RegistrationForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""Registers a new user Attributes: email: takes the user's email from the StringField from wtforms username: takes the user's username from the StringField from wtforms password: takes the user's password from the PasswordField from wtforms password2: takes the user's password ... | stack_v2_sparse_classes_36k_train_017134 | 8,064 | permissive | [
{
"docstring": "Check that the email isn't already registered, and is the right email domain as per config Args: self: is a class argument field: is the email Returns: ValidationError, only if the email is already registered, or is not a company email",
"name": "validate_email",
"signature": "def valida... | 2 | stack_v2_sparse_classes_30k_train_001321 | Implement the Python class `RegistrationForm` described below.
Class description:
Registers a new user Attributes: email: takes the user's email from the StringField from wtforms username: takes the user's username from the StringField from wtforms password: takes the user's password from the PasswordField from wtform... | Implement the Python class `RegistrationForm` described below.
Class description:
Registers a new user Attributes: email: takes the user's email from the StringField from wtforms username: takes the user's username from the StringField from wtforms password: takes the user's password from the PasswordField from wtform... | 99d07b3220a5877ead8811a0b002527b55bba7cf | <|skeleton|>
class RegistrationForm:
"""Registers a new user Attributes: email: takes the user's email from the StringField from wtforms username: takes the user's username from the StringField from wtforms password: takes the user's password from the PasswordField from wtforms password2: takes the user's password ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationForm:
"""Registers a new user Attributes: email: takes the user's email from the StringField from wtforms username: takes the user's username from the StringField from wtforms password: takes the user's password from the PasswordField from wtforms password2: takes the user's password from the Pass... | the_stack_v2_python_sparse | web/app/auth/forms.py | innocorps/pyIoT | train | 2 |
f472aca41daaca12a1715494045c148614208d7f | [
"snap = super(AbstractButton, self).snapshot()\nsnap['text'] = self.text\nsnap['checkable'] = self.checkable\nsnap['checked'] = self.checked\nsnap['icon_size'] = tuple(self.icon_size)\nsnap['icon_source'] = self.icon_source\nreturn snap",
"super(AbstractButton, self).bind()\nattrs = ('text', 'checkable', 'checked... | <|body_start_0|>
snap = super(AbstractButton, self).snapshot()
snap['text'] = self.text
snap['checkable'] = self.checkable
snap['checked'] = self.checked
snap['icon_size'] = tuple(self.icon_size)
snap['icon_source'] = self.icon_source
return snap
<|end_body_0|>
<... | A base class which provides functionality common for several button-like widgets. | AbstractButton | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractButton:
"""A base class which provides functionality common for several button-like widgets."""
def snapshot(self):
"""Returns the snapshot for an abstract button."""
<|body_0|>
def bind(self):
"""Bind the change handlers for an abstract button."""
... | stack_v2_sparse_classes_36k_train_017135 | 3,025 | permissive | [
{
"docstring": "Returns the snapshot for an abstract button.",
"name": "snapshot",
"signature": "def snapshot(self)"
},
{
"docstring": "Bind the change handlers for an abstract button.",
"name": "bind",
"signature": "def bind(self)"
},
{
"docstring": "Handle the 'clicked' action ... | 4 | stack_v2_sparse_classes_30k_train_009515 | Implement the Python class `AbstractButton` described below.
Class description:
A base class which provides functionality common for several button-like widgets.
Method signatures and docstrings:
- def snapshot(self): Returns the snapshot for an abstract button.
- def bind(self): Bind the change handlers for an abstr... | Implement the Python class `AbstractButton` described below.
Class description:
A base class which provides functionality common for several button-like widgets.
Method signatures and docstrings:
- def snapshot(self): Returns the snapshot for an abstract button.
- def bind(self): Bind the change handlers for an abstr... | 424bba29219de58fe9e47196de6763de8b2009f2 | <|skeleton|>
class AbstractButton:
"""A base class which provides functionality common for several button-like widgets."""
def snapshot(self):
"""Returns the snapshot for an abstract button."""
<|body_0|>
def bind(self):
"""Bind the change handlers for an abstract button."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractButton:
"""A base class which provides functionality common for several button-like widgets."""
def snapshot(self):
"""Returns the snapshot for an abstract button."""
snap = super(AbstractButton, self).snapshot()
snap['text'] = self.text
snap['checkable'] = self.ch... | the_stack_v2_python_sparse | enaml/widgets/abstract_button.py | enthought/enaml | train | 17 |
5bcc1f933c809062f02d79567fde618594f5c5f3 | [
"data = []\nfor i, m in enumerate(result.get('availableMachineType', [])):\n key = ''\n if i == 0:\n key = 'machine types'\n data.append((key, self._presenter.PresentElement(m)))\nfor window in result.get('maintenanceWindows', []):\n maintenance_info = []\n maintenance_info.append(('name', win... | <|body_start_0|>
data = []
for i, m in enumerate(result.get('availableMachineType', [])):
key = ''
if i == 0:
key = 'machine types'
data.append((key, self._presenter.PresentElement(m)))
for window in result.get('maintenanceWindows', []):
... | Get a zone. | GetZone | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetZone:
"""Get a zone."""
def GetDetailRow(self, result):
"""Returns an associative list of items for display in a detail table. Args: result: A dict returned by the server. Returns: A list."""
<|body_0|>
def Handle(self, zone_name):
"""Get the specified zone. A... | stack_v2_sparse_classes_36k_train_017136 | 4,211 | permissive | [
{
"docstring": "Returns an associative list of items for display in a detail table. Args: result: A dict returned by the server. Returns: A list.",
"name": "GetDetailRow",
"signature": "def GetDetailRow(self, result)"
},
{
"docstring": "Get the specified zone. Args: zone_name: Path of the zone t... | 2 | stack_v2_sparse_classes_30k_train_008643 | Implement the Python class `GetZone` described below.
Class description:
Get a zone.
Method signatures and docstrings:
- def GetDetailRow(self, result): Returns an associative list of items for display in a detail table. Args: result: A dict returned by the server. Returns: A list.
- def Handle(self, zone_name): Get ... | Implement the Python class `GetZone` described below.
Class description:
Get a zone.
Method signatures and docstrings:
- def GetDetailRow(self, result): Returns an associative list of items for display in a detail table. Args: result: A dict returned by the server. Returns: A list.
- def Handle(self, zone_name): Get ... | d379afa2db3582d5c3be652165f0e9e2e0c154c6 | <|skeleton|>
class GetZone:
"""Get a zone."""
def GetDetailRow(self, result):
"""Returns an associative list of items for display in a detail table. Args: result: A dict returned by the server. Returns: A list."""
<|body_0|>
def Handle(self, zone_name):
"""Get the specified zone. A... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetZone:
"""Get a zone."""
def GetDetailRow(self, result):
"""Returns an associative list of items for display in a detail table. Args: result: A dict returned by the server. Returns: A list."""
data = []
for i, m in enumerate(result.get('availableMachineType', [])):
k... | the_stack_v2_python_sparse | y/google-cloud-sdk/platform/gcutil/lib/google_compute_engine/gcutil_lib/zone_cmds.py | ychen820/microblog | train | 0 |
188c6141a615dc5b75b822e02884276508e800c3 | [
"try:\n obj = cls.objects.get(type=4, agent_id=agent_id)\n return model_to_dict(obj, fields=['api', 'user', 'password'])\nexcept:\n return dict()",
"try:\n obj = cls.objects.get(type=1, agent_id=agent_id)\n return model_to_dict(obj)\nexcept:\n return dict()",
"try:\n obj = cls.objects.get(t... | <|body_start_0|>
try:
obj = cls.objects.get(type=4, agent_id=agent_id)
return model_to_dict(obj, fields=['api', 'user', 'password'])
except:
return dict()
<|end_body_0|>
<|body_start_1|>
try:
obj = cls.objects.get(type=1, agent_id=agent_id)
... | 代理商消息的设置,包括邮件、短信等 | Message | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Message:
"""代理商消息的设置,包括邮件、短信等"""
def get_cloud_info(cls, agent_id):
"""获取cloud 发邮件的需要数据 :return:"""
<|body_0|>
def get_smtp_info(cls, agent_id):
"""获取smtp服务信息 :param msg: :return:"""
<|body_1|>
def get_msg_info(cls, agent_id):
"""获取发短信信息 :par... | stack_v2_sparse_classes_36k_train_017137 | 13,020 | no_license | [
{
"docstring": "获取cloud 发邮件的需要数据 :return:",
"name": "get_cloud_info",
"signature": "def get_cloud_info(cls, agent_id)"
},
{
"docstring": "获取smtp服务信息 :param msg: :return:",
"name": "get_smtp_info",
"signature": "def get_smtp_info(cls, agent_id)"
},
{
"docstring": "获取发短信信息 :param a... | 3 | null | Implement the Python class `Message` described below.
Class description:
代理商消息的设置,包括邮件、短信等
Method signatures and docstrings:
- def get_cloud_info(cls, agent_id): 获取cloud 发邮件的需要数据 :return:
- def get_smtp_info(cls, agent_id): 获取smtp服务信息 :param msg: :return:
- def get_msg_info(cls, agent_id): 获取发短信信息 :param agent_id: :r... | Implement the Python class `Message` described below.
Class description:
代理商消息的设置,包括邮件、短信等
Method signatures and docstrings:
- def get_cloud_info(cls, agent_id): 获取cloud 发邮件的需要数据 :return:
- def get_smtp_info(cls, agent_id): 获取smtp服务信息 :param msg: :return:
- def get_msg_info(cls, agent_id): 获取发短信信息 :param agent_id: :r... | d6e025d7e9d9e3aecfd399c77f376130edd8a2df | <|skeleton|>
class Message:
"""代理商消息的设置,包括邮件、短信等"""
def get_cloud_info(cls, agent_id):
"""获取cloud 发邮件的需要数据 :return:"""
<|body_0|>
def get_smtp_info(cls, agent_id):
"""获取smtp服务信息 :param msg: :return:"""
<|body_1|>
def get_msg_info(cls, agent_id):
"""获取发短信信息 :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Message:
"""代理商消息的设置,包括邮件、短信等"""
def get_cloud_info(cls, agent_id):
"""获取cloud 发邮件的需要数据 :return:"""
try:
obj = cls.objects.get(type=4, agent_id=agent_id)
return model_to_dict(obj, fields=['api', 'user', 'password'])
except:
return dict()
de... | the_stack_v2_python_sparse | soc_system/models.py | sundw2015/841 | train | 4 |
60351c5539a2c0347c18b9f37b9002f77e5524b1 | [
"self.selector = selector\nself.K = ParallelMean(1)\nself.R = ParallelMean(1)\nself.count = 0",
"data = _DataWrapper(data, '')\nsel = self.selector(data, *args, **kwargs)\nw = data['weight']\nK = data['m']\nR = 1.0 - data['sigma_e'] ** 2\nn = w[sel].size\nself.count += n\nw = w[sel]\nself.R.add_data(0, R[sel], w)... | <|body_start_0|>
self.selector = selector
self.K = ParallelMean(1)
self.R = ParallelMean(1)
self.count = 0
<|end_body_0|>
<|body_start_1|>
data = _DataWrapper(data, '')
sel = self.selector(data, *args, **kwargs)
w = data['weight']
K = data['m']
R ... | This class builds up the total response calibration factors for HSC-convention shear-calibration from each chunk of data it is given. At the end an MPI communicator can be supplied to collect together the results from the different processes. | HSCCalculator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HSCCalculator:
"""This class builds up the total response calibration factors for HSC-convention shear-calibration from each chunk of data it is given. At the end an MPI communicator can be supplied to collect together the results from the different processes."""
def __init__(self, selector)... | stack_v2_sparse_classes_36k_train_017138 | 27,539 | permissive | [
{
"docstring": "Initialize the Calibrator using the function you will use to select objects. That function should take at least one argument, the chunk of data to select on. The selector can take further *args and **kwargs, passed in when adding data. Parameters ---------- selector: function Function that selec... | 3 | null | Implement the Python class `HSCCalculator` described below.
Class description:
This class builds up the total response calibration factors for HSC-convention shear-calibration from each chunk of data it is given. At the end an MPI communicator can be supplied to collect together the results from the different processe... | Implement the Python class `HSCCalculator` described below.
Class description:
This class builds up the total response calibration factors for HSC-convention shear-calibration from each chunk of data it is given. At the end an MPI communicator can be supplied to collect together the results from the different processe... | addbfbe6c4dc0df208ce4f7ba4cb0a7588a932e3 | <|skeleton|>
class HSCCalculator:
"""This class builds up the total response calibration factors for HSC-convention shear-calibration from each chunk of data it is given. At the end an MPI communicator can be supplied to collect together the results from the different processes."""
def __init__(self, selector)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HSCCalculator:
"""This class builds up the total response calibration factors for HSC-convention shear-calibration from each chunk of data it is given. At the end an MPI communicator can be supplied to collect together the results from the different processes."""
def __init__(self, selector):
"""... | the_stack_v2_python_sparse | txpipe/utils/calibration_tools.py | LSSTDESC/TXPipe | train | 17 |
cb411fdfa95aa0d109b2d9fb8dff8e84e9fa03d5 | [
"super(QNetworkVision, self).__init__()\nself.take_additional_forward_arguments = False\nself.sequence_length = sequence_length\nself.repeat_size = repeat_size\nmx.random.seed(seed)\nself.net = gluon.nn.HybridSequential()\nwith self.net.name_scope():\n for i in range(number_of_conv_layers):\n self.net.add... | <|body_start_0|>
super(QNetworkVision, self).__init__()
self.take_additional_forward_arguments = False
self.sequence_length = sequence_length
self.repeat_size = repeat_size
mx.random.seed(seed)
self.net = gluon.nn.HybridSequential()
with self.net.name_scope():
... | QNetworkVision | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QNetworkVision:
def __init__(self, state_shape, action_size, starting_channels, number_of_conv_layers, number_of_dense_layers, number_of_hidden_states, kernel_size, repeat_size, activation_type, sequence_length, seed):
"""Initialize parameters and build model. Params ====== state_shape (... | stack_v2_sparse_classes_36k_train_017139 | 14,417 | permissive | [
{
"docstring": "Initialize parameters and build model. Params ====== state_shape (int, int, int): Dimension of each state action_size (int): Dimension of each action starting_channels (int): number_of_conv_layers (int) number_of_dense_layers (int) number_of_hidden_states (int) repeat_size (int) activation_type ... | 2 | stack_v2_sparse_classes_30k_train_013909 | Implement the Python class `QNetworkVision` described below.
Class description:
Implement the QNetworkVision class.
Method signatures and docstrings:
- def __init__(self, state_shape, action_size, starting_channels, number_of_conv_layers, number_of_dense_layers, number_of_hidden_states, kernel_size, repeat_size, acti... | Implement the Python class `QNetworkVision` described below.
Class description:
Implement the QNetworkVision class.
Method signatures and docstrings:
- def __init__(self, state_shape, action_size, starting_channels, number_of_conv_layers, number_of_dense_layers, number_of_hidden_states, kernel_size, repeat_size, acti... | 5baa886c17fa2cf53dd0146493281de717771d81 | <|skeleton|>
class QNetworkVision:
def __init__(self, state_shape, action_size, starting_channels, number_of_conv_layers, number_of_dense_layers, number_of_hidden_states, kernel_size, repeat_size, activation_type, sequence_length, seed):
"""Initialize parameters and build model. Params ====== state_shape (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QNetworkVision:
def __init__(self, state_shape, action_size, starting_channels, number_of_conv_layers, number_of_dense_layers, number_of_hidden_states, kernel_size, repeat_size, activation_type, sequence_length, seed):
"""Initialize parameters and build model. Params ====== state_shape (int, int, int)... | the_stack_v2_python_sparse | source/MXNetEnv/training/training_src/networks/qnetworks.py | awslabs/sagemaker-battlesnake-ai | train | 91 | |
b95da1d90ea2e1f57aecf7e28c7c28ea49f71d9c | [
"satSolverName = satSolverName.lower()\nif satSolverName == 'lingeling' or satSolverName == '':\n return SatSolver.LINGELING\nelif satSolverName == 'minisat':\n return SatSolver.MINISAT\nelif satSolverName == 'picosat':\n return SatSolver.PICOSAT\nelse:\n errMsg = 'Unknown backend SAT solver for Boolect... | <|body_start_0|>
satSolverName = satSolverName.lower()
if satSolverName == 'lingeling' or satSolverName == '':
return SatSolver.LINGELING
elif satSolverName == 'minisat':
return SatSolver.MINISAT
elif satSolverName == 'picosat':
return SatSolver.PICOSA... | This class represents the SAT solver used by Boolector. | SatSolver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SatSolver:
"""This class represents the SAT solver used by Boolector."""
def getSatSolver(satSolverName):
"""Returns the SatSolver representation of the SAT solver whose name is provided. @param satSolverName Name of a SAT solver. @retval SatSolver representation of the SAT solver wh... | stack_v2_sparse_classes_36k_train_017140 | 5,145 | no_license | [
{
"docstring": "Returns the SatSolver representation of the SAT solver whose name is provided. @param satSolverName Name of a SAT solver. @retval SatSolver representation of the SAT solver whose name is provided.",
"name": "getSatSolver",
"signature": "def getSatSolver(satSolverName)"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_015901 | Implement the Python class `SatSolver` described below.
Class description:
This class represents the SAT solver used by Boolector.
Method signatures and docstrings:
- def getSatSolver(satSolverName): Returns the SatSolver representation of the SAT solver whose name is provided. @param satSolverName Name of a SAT solv... | Implement the Python class `SatSolver` described below.
Class description:
This class represents the SAT solver used by Boolector.
Method signatures and docstrings:
- def getSatSolver(satSolverName): Returns the SatSolver representation of the SAT solver whose name is provided. @param satSolverName Name of a SAT solv... | 43fbd6ae7f83c9ebf55dbedb4f98ce064c04514c | <|skeleton|>
class SatSolver:
"""This class represents the SAT solver used by Boolector."""
def getSatSolver(satSolverName):
"""Returns the SatSolver representation of the SAT solver whose name is provided. @param satSolverName Name of a SAT solver. @retval SatSolver representation of the SAT solver wh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SatSolver:
"""This class represents the SAT solver used by Boolector."""
def getSatSolver(satSolverName):
"""Returns the SatSolver representation of the SAT solver whose name is provided. @param satSolverName Name of a SAT solver. @retval SatSolver representation of the SAT solver whose name is p... | the_stack_v2_python_sparse | build/lib.linux-x86_64-2.7/gametime/smt/solvers/boolectorSolver.py | jerryduan07/gametime | train | 0 |
86be358a131d2812190cba4164c5c17578c62d90 | [
"offmol = Molecule.from_smiles('CCO')\noffmol.generate_conformers(n_conformers=1)\ncomp = offmol_to_compound(offmol)\nassert comp.n_particles == offmol.n_atoms\nassert comp.n_bonds == offmol.n_bonds\nnp.testing.assert_equal(offmol.conformers[0].m_as(unit.nanometer), comp.xyz)",
"offmol = Molecule.from_smiles('CCO... | <|body_start_0|>
offmol = Molecule.from_smiles('CCO')
offmol.generate_conformers(n_conformers=1)
comp = offmol_to_compound(offmol)
assert comp.n_particles == offmol.n_atoms
assert comp.n_bonds == offmol.n_bonds
np.testing.assert_equal(offmol.conformers[0].m_as(unit.nanome... | TestMBuildConversions | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMBuildConversions:
def test_basic_mol_to_compound(self):
"""Test basic behavior of conversion to mBuild Compound"""
<|body_0|>
def test_mbuild_conversion_generate_conformers(self):
"""Test that a single conformer is automatically generated"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_017141 | 3,195 | permissive | [
{
"docstring": "Test basic behavior of conversion to mBuild Compound",
"name": "test_basic_mol_to_compound",
"signature": "def test_basic_mol_to_compound(self)"
},
{
"docstring": "Test that a single conformer is automatically generated",
"name": "test_mbuild_conversion_generate_conformers",
... | 5 | null | Implement the Python class `TestMBuildConversions` described below.
Class description:
Implement the TestMBuildConversions class.
Method signatures and docstrings:
- def test_basic_mol_to_compound(self): Test basic behavior of conversion to mBuild Compound
- def test_mbuild_conversion_generate_conformers(self): Test ... | Implement the Python class `TestMBuildConversions` described below.
Class description:
Implement the TestMBuildConversions class.
Method signatures and docstrings:
- def test_basic_mol_to_compound(self): Test basic behavior of conversion to mBuild Compound
- def test_mbuild_conversion_generate_conformers(self): Test ... | 4616f2cff477c18e2c6ca70ac4c74c28b283a4be | <|skeleton|>
class TestMBuildConversions:
def test_basic_mol_to_compound(self):
"""Test basic behavior of conversion to mBuild Compound"""
<|body_0|>
def test_mbuild_conversion_generate_conformers(self):
"""Test that a single conformer is automatically generated"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestMBuildConversions:
def test_basic_mol_to_compound(self):
"""Test basic behavior of conversion to mBuild Compound"""
offmol = Molecule.from_smiles('CCO')
offmol.generate_conformers(n_conformers=1)
comp = offmol_to_compound(offmol)
assert comp.n_particles == offmol.n_... | the_stack_v2_python_sparse | openff/interchange/_tests/unit_tests/components/test_mbuild.py | openforcefield/openff-interchange | train | 39 | |
87541002d19889aa760c03e842f0d0db5db1e8af | [
"uri = '/api/v1/merchantsStatistics/merchantsContractStatics'\nallure.attach(sx_zs_api + uri, '地址', allure.attachment_type.TEXT)\nheaders = SX_PC_IM_headers\nallure.attach(json.dumps(headers, ensure_ascii=False, indent=4), '请求头', allure.attachment_type.TEXT)\ncommon = Common()\ndata = {'isCumulative': isCumulative,... | <|body_start_0|>
uri = '/api/v1/merchantsStatistics/merchantsContractStatics'
allure.attach(sx_zs_api + uri, '地址', allure.attachment_type.TEXT)
headers = SX_PC_IM_headers
allure.attach(json.dumps(headers, ensure_ascii=False, indent=4), '请求头', allure.attachment_type.TEXT)
common =... | Test_case | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_case:
def mk_merchantsStatistics_merchantsContractStatics(self, isCumulative, signBrandCode, unit, case):
"""招商数据概括接口 :return:"""
<|body_0|>
def mk_merchantsStatistics_merchantsEfficiency(self, unit, case):
"""招商人数 :return:"""
<|body_1|>
def mk_merc... | stack_v2_sparse_classes_36k_train_017142 | 5,477 | no_license | [
{
"docstring": "招商数据概括接口 :return:",
"name": "mk_merchantsStatistics_merchantsContractStatics",
"signature": "def mk_merchantsStatistics_merchantsContractStatics(self, isCumulative, signBrandCode, unit, case)"
},
{
"docstring": "招商人数 :return:",
"name": "mk_merchantsStatistics_merchantsEfficie... | 3 | null | Implement the Python class `Test_case` described below.
Class description:
Implement the Test_case class.
Method signatures and docstrings:
- def mk_merchantsStatistics_merchantsContractStatics(self, isCumulative, signBrandCode, unit, case): 招商数据概括接口 :return:
- def mk_merchantsStatistics_merchantsEfficiency(self, uni... | Implement the Python class `Test_case` described below.
Class description:
Implement the Test_case class.
Method signatures and docstrings:
- def mk_merchantsStatistics_merchantsContractStatics(self, isCumulative, signBrandCode, unit, case): 招商数据概括接口 :return:
- def mk_merchantsStatistics_merchantsEfficiency(self, uni... | a184161fdbf4b35dbca8e9b050ad049c05b003ff | <|skeleton|>
class Test_case:
def mk_merchantsStatistics_merchantsContractStatics(self, isCumulative, signBrandCode, unit, case):
"""招商数据概括接口 :return:"""
<|body_0|>
def mk_merchantsStatistics_merchantsEfficiency(self, unit, case):
"""招商人数 :return:"""
<|body_1|>
def mk_merc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_case:
def mk_merchantsStatistics_merchantsContractStatics(self, isCumulative, signBrandCode, unit, case):
"""招商数据概括接口 :return:"""
uri = '/api/v1/merchantsStatistics/merchantsContractStatics'
allure.attach(sx_zs_api + uri, '地址', allure.attachment_type.TEXT)
headers = SX_PC_... | the_stack_v2_python_sparse | TestSuite/zs_mk/zsmk.py | liuchengxu11/IM | train | 0 | |
04164599d53bdbebca30700f26d746cfa9a95deb | [
"list.__init__(self)\nself.name = name\nself.elements = []",
"stream.write(pack_bgn('BGNSTR'))\nstream.write(pack_data('STRNAME', self.name))\nfor element in self.elements:\n element.export(stream)\nstream.write(pack_no_data('ENDSTR'))",
"elem = Boundary(layer, dataType, points)\nself.elements.append(elem)\n... | <|body_start_0|>
list.__init__(self)
self.name = name
self.elements = []
<|end_body_0|>
<|body_start_1|>
stream.write(pack_bgn('BGNSTR'))
stream.write(pack_data('STRNAME', self.name))
for element in self.elements:
element.export(stream)
stream.write(p... | Structure | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Structure:
def __init__(self, name):
"""initialize Structure object Parameters ---------- name : str structure name"""
<|body_0|>
def export(self, stream):
"""Export to stream Parameters ---------- stream : stream file stream to be written"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_017143 | 18,791 | permissive | [
{
"docstring": "initialize Structure object Parameters ---------- name : str structure name",
"name": "__init__",
"signature": "def __init__(self, name)"
},
{
"docstring": "Export to stream Parameters ---------- stream : stream file stream to be written",
"name": "export",
"signature": "... | 6 | null | Implement the Python class `Structure` described below.
Class description:
Implement the Structure class.
Method signatures and docstrings:
- def __init__(self, name): initialize Structure object Parameters ---------- name : str structure name
- def export(self, stream): Export to stream Parameters ---------- stream ... | Implement the Python class `Structure` described below.
Class description:
Implement the Structure class.
Method signatures and docstrings:
- def __init__(self, name): initialize Structure object Parameters ---------- name : str structure name
- def export(self, stream): Export to stream Parameters ---------- stream ... | 8f62ec1971480cb27cb592421fd97f590379cff9 | <|skeleton|>
class Structure:
def __init__(self, name):
"""initialize Structure object Parameters ---------- name : str structure name"""
<|body_0|>
def export(self, stream):
"""Export to stream Parameters ---------- stream : stream file stream to be written"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Structure:
def __init__(self, name):
"""initialize Structure object Parameters ---------- name : str structure name"""
list.__init__(self)
self.name = name
self.elements = []
def export(self, stream):
"""Export to stream Parameters ---------- stream : stream file s... | the_stack_v2_python_sparse | GDSIO.py | ucb-art/laygo | train | 24 | |
e4b5ef3c4903ca97fe28d17a88421d5176f48c14 | [
"self.dhcp_lease_time = dhcp_lease_time\nself.dns_nameservers = dns_nameservers\nself.dns_custom_nameservers = dns_custom_nameservers",
"if dictionary is None:\n return None\ndhcp_lease_time = dictionary.get('dhcpLeaseTime')\ndns_nameservers = dictionary.get('dnsNameservers')\ndns_custom_nameservers = dictiona... | <|body_start_0|>
self.dhcp_lease_time = dhcp_lease_time
self.dns_nameservers = dns_nameservers
self.dns_custom_nameservers = dns_custom_nameservers
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
dhcp_lease_time = dictionary.get('dhcpLeaseTime')
... | Implementation of the 'updateNetworkCellularGatewaySettingsDhcp' model. TODO: type model description here. Attributes: dhcp_lease_time (string): DHCP Lease time for all MG of the network. It can be '30 minutes', '1 hour', '4 hours', '12 hours', '1 day' or '1 week'. dns_nameservers (string): DNS name servers mode for al... | UpdateNetworkCellularGatewaySettingsDhcpModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNetworkCellularGatewaySettingsDhcpModel:
"""Implementation of the 'updateNetworkCellularGatewaySettingsDhcp' model. TODO: type model description here. Attributes: dhcp_lease_time (string): DHCP Lease time for all MG of the network. It can be '30 minutes', '1 hour', '4 hours', '12 hours', '1... | stack_v2_sparse_classes_36k_train_017144 | 2,535 | permissive | [
{
"docstring": "Constructor for the UpdateNetworkCellularGatewaySettingsDhcpModel class",
"name": "__init__",
"signature": "def __init__(self, dhcp_lease_time=None, dns_nameservers=None, dns_custom_nameservers=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: di... | 2 | stack_v2_sparse_classes_30k_train_006009 | Implement the Python class `UpdateNetworkCellularGatewaySettingsDhcpModel` described below.
Class description:
Implementation of the 'updateNetworkCellularGatewaySettingsDhcp' model. TODO: type model description here. Attributes: dhcp_lease_time (string): DHCP Lease time for all MG of the network. It can be '30 minute... | Implement the Python class `UpdateNetworkCellularGatewaySettingsDhcpModel` described below.
Class description:
Implementation of the 'updateNetworkCellularGatewaySettingsDhcp' model. TODO: type model description here. Attributes: dhcp_lease_time (string): DHCP Lease time for all MG of the network. It can be '30 minute... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateNetworkCellularGatewaySettingsDhcpModel:
"""Implementation of the 'updateNetworkCellularGatewaySettingsDhcp' model. TODO: type model description here. Attributes: dhcp_lease_time (string): DHCP Lease time for all MG of the network. It can be '30 minutes', '1 hour', '4 hours', '12 hours', '1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateNetworkCellularGatewaySettingsDhcpModel:
"""Implementation of the 'updateNetworkCellularGatewaySettingsDhcp' model. TODO: type model description here. Attributes: dhcp_lease_time (string): DHCP Lease time for all MG of the network. It can be '30 minutes', '1 hour', '4 hours', '12 hours', '1 day' or '1 w... | the_stack_v2_python_sparse | meraki_sdk/models/update_network_cellular_gateway_settings_dhcp_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
b1aacd63fb3af49f521efcd7c137eb25c38703fd | [
"self.type_ = 'FILL'\nself.timeindex = timeindex\nself.symbol = symbol\nself.exchange = exchange\nself.quantity = quantity\nself.direction = direction\nself.fill_cost = fill_cost\nif commission is None:\n self.commission = self.calculate_ib_commission()\nelse:\n self.commission = commission\nself.dict_ = {str... | <|body_start_0|>
self.type_ = 'FILL'
self.timeindex = timeindex
self.symbol = symbol
self.exchange = exchange
self.quantity = quantity
self.direction = direction
self.fill_cost = fill_cost
if commission is None:
self.commission = self.calculate... | Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage. TODO: Currently does not support filling positions at different prices. This will be simulated by averaging... | EventFill | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventFill:
"""Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage. TODO: Currently does not support filling positions at different prices... | stack_v2_sparse_classes_36k_train_017145 | 6,487 | permissive | [
{
"docstring": "Initialises the FillEvent object. Sets the symbol, exchange, quantity, direction, cost of fill and an optional commission. If commission is not provided, the Fill object will calculate it based on the trade size and Interactive Brokers fees. Parameters: timeindex - The bar-resolution when the or... | 2 | stack_v2_sparse_classes_30k_train_016681 | Implement the Python class `EventFill` described below.
Class description:
Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage. TODO: Currently does not suppor... | Implement the Python class `EventFill` described below.
Class description:
Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage. TODO: Currently does not suppor... | ce74a9bf8db91e3545ccc3e7af81f80796a536fa | <|skeleton|>
class EventFill:
"""Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage. TODO: Currently does not support filling positions at different prices... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventFill:
"""Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage. TODO: Currently does not support filling positions at different prices. This will b... | the_stack_v2_python_sparse | DQIC/backtesting/event.py | xiaosixugithub/DeepQuantInChina | train | 0 |
8190383fb5b7143e5f0564a1239dcd4bac970422 | [
"if len(val) != 8:\n abort(400, 'Bad TAC format')\ntry:\n int(val)\nexcept ValueError:\n abort(400, 'Bad Tac format')",
"self._validate_tac(tac)\nwith get_db_connection() as db_conn, db_conn.cursor() as cursor:\n cursor.execute('SELECT tac, manufacturer, bands, allocation_date, model_name, device_type... | <|body_start_0|>
if len(val) != 8:
abort(400, 'Bad TAC format')
try:
int(val)
except ValueError:
abort(400, 'Bad Tac format')
<|end_body_0|>
<|body_start_1|>
self._validate_tac(tac)
with get_db_connection() as db_conn, db_conn.cursor() as curs... | TAC API version 2 methods. | TacApi | [
"BSD-3-Clause-Clear"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TacApi:
"""TAC API version 2 methods."""
def _validate_tac(val):
"""Validate TAC input argument format."""
<|body_0|>
def get(self, tac):
"""TAC GET API endpoint (version 2)."""
<|body_1|>
def post(self, **kwargs):
"""TAC POST API endpoint (v... | stack_v2_sparse_classes_36k_train_017146 | 7,407 | permissive | [
{
"docstring": "Validate TAC input argument format.",
"name": "_validate_tac",
"signature": "def _validate_tac(val)"
},
{
"docstring": "TAC GET API endpoint (version 2).",
"name": "get",
"signature": "def get(self, tac)"
},
{
"docstring": "TAC POST API endpoint (version 2).",
... | 3 | stack_v2_sparse_classes_30k_train_018665 | Implement the Python class `TacApi` described below.
Class description:
TAC API version 2 methods.
Method signatures and docstrings:
- def _validate_tac(val): Validate TAC input argument format.
- def get(self, tac): TAC GET API endpoint (version 2).
- def post(self, **kwargs): TAC POST API endpoint (version 2). | Implement the Python class `TacApi` described below.
Class description:
TAC API version 2 methods.
Method signatures and docstrings:
- def _validate_tac(val): Validate TAC input argument format.
- def get(self, tac): TAC GET API endpoint (version 2).
- def post(self, **kwargs): TAC POST API endpoint (version 2).
<|s... | 6b48457715338cce4eb6b3948940297ebd789189 | <|skeleton|>
class TacApi:
"""TAC API version 2 methods."""
def _validate_tac(val):
"""Validate TAC input argument format."""
<|body_0|>
def get(self, tac):
"""TAC GET API endpoint (version 2)."""
<|body_1|>
def post(self, **kwargs):
"""TAC POST API endpoint (v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TacApi:
"""TAC API version 2 methods."""
def _validate_tac(val):
"""Validate TAC input argument format."""
if len(val) != 8:
abort(400, 'Bad TAC format')
try:
int(val)
except ValueError:
abort(400, 'Bad Tac format')
def get(self, ta... | the_stack_v2_python_sparse | src/dirbs/api/common/tac.py | bryang-qti-qualcomm/DIRBS-Core | train | 0 |
2f13956b82c378a84c282f0ce8e0131ec2357bd4 | [
"if not root:\n return 0\nreturn max(self.maxDepth_1(root.left), self.maxDepth_1(root.right)) + 1",
"if not root:\n return 0\nqueue, res = ([root], 0)\nwhile queue:\n tmp = []\n for node in queue:\n if node.left:\n tmp.append(node.left)\n if node.right:\n tmp.append... | <|body_start_0|>
if not root:
return 0
return max(self.maxDepth_1(root.left), self.maxDepth_1(root.right)) + 1
<|end_body_0|>
<|body_start_1|>
if not root:
return 0
queue, res = ([root], 0)
while queue:
tmp = []
for node in queue:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth_1(self, root: TreeNode) -> int:
"""深度优先搜索后序遍历二叉树的各个节点(DFS)来计算二叉树的深度 时间复杂度 O(N) : N 为树的节点数量,计算树的深度需要遍历所有节点。 空间复杂度 O(N) : 最差情况下(当树退化为链表时),递归深度可达到 N 。 :param root: :return:"""
<|body_0|>
def maxDepth_2(self, root: TreeNode) -> int:
"""广度优先搜索层次遍历二叉... | stack_v2_sparse_classes_36k_train_017147 | 2,119 | no_license | [
{
"docstring": "深度优先搜索后序遍历二叉树的各个节点(DFS)来计算二叉树的深度 时间复杂度 O(N) : N 为树的节点数量,计算树的深度需要遍历所有节点。 空间复杂度 O(N) : 最差情况下(当树退化为链表时),递归深度可达到 N 。 :param root: :return:",
"name": "maxDepth_1",
"signature": "def maxDepth_1(self, root: TreeNode) -> int"
},
{
"docstring": "广度优先搜索层次遍历二叉树的各个节点(BFS)来计算二叉树的深度 时间复杂度 O(N)... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth_1(self, root: TreeNode) -> int: 深度优先搜索后序遍历二叉树的各个节点(DFS)来计算二叉树的深度 时间复杂度 O(N) : N 为树的节点数量,计算树的深度需要遍历所有节点。 空间复杂度 O(N) : 最差情况下(当树退化为链表时),递归深度可达到 N 。 :param root: :return... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth_1(self, root: TreeNode) -> int: 深度优先搜索后序遍历二叉树的各个节点(DFS)来计算二叉树的深度 时间复杂度 O(N) : N 为树的节点数量,计算树的深度需要遍历所有节点。 空间复杂度 O(N) : 最差情况下(当树退化为链表时),递归深度可达到 N 。 :param root: :return... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def maxDepth_1(self, root: TreeNode) -> int:
"""深度优先搜索后序遍历二叉树的各个节点(DFS)来计算二叉树的深度 时间复杂度 O(N) : N 为树的节点数量,计算树的深度需要遍历所有节点。 空间复杂度 O(N) : 最差情况下(当树退化为链表时),递归深度可达到 N 。 :param root: :return:"""
<|body_0|>
def maxDepth_2(self, root: TreeNode) -> int:
"""广度优先搜索层次遍历二叉... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth_1(self, root: TreeNode) -> int:
"""深度优先搜索后序遍历二叉树的各个节点(DFS)来计算二叉树的深度 时间复杂度 O(N) : N 为树的节点数量,计算树的深度需要遍历所有节点。 空间复杂度 O(N) : 最差情况下(当树退化为链表时),递归深度可达到 N 。 :param root: :return:"""
if not root:
return 0
return max(self.maxDepth_1(root.left), self.maxDepth_1(r... | the_stack_v2_python_sparse | 剑指 Offer(第 2 版)/maxDepth.py | MaoningGuan/LeetCode | train | 3 | |
dc8b17d6eddc0cf03a64c017651eba809f1e1bda | [
"user_id = request.user.id\nredis_conn = get_redis_connection('history')\nsku_ids = redis_conn.lrange('history_' + str(user_id), 0, -1)\nsku_list = list()\nfor sku in sku_ids:\n sku = SKU.objects.get(id=sku)\n sku_list.append({'id': sku.id, 'name': sku.name, 'default_image_url': sku.default_image_url, 'price'... | <|body_start_0|>
user_id = request.user.id
redis_conn = get_redis_connection('history')
sku_ids = redis_conn.lrange('history_' + str(user_id), 0, -1)
sku_list = list()
for sku in sku_ids:
sku = SKU.objects.get(id=sku)
sku_list.append({'id': sku.id, 'name':... | 用户浏览sku记录 | UserBrowseHistory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserBrowseHistory:
"""用户浏览sku记录"""
def get(self, request):
"""获取浏览记录 :param request: :return:"""
<|body_0|>
def post(self, request):
"""保存用户浏览记录 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user_id = request.user.id
... | stack_v2_sparse_classes_36k_train_017148 | 23,231 | permissive | [
{
"docstring": "获取浏览记录 :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "保存用户浏览记录 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011658 | Implement the Python class `UserBrowseHistory` described below.
Class description:
用户浏览sku记录
Method signatures and docstrings:
- def get(self, request): 获取浏览记录 :param request: :return:
- def post(self, request): 保存用户浏览记录 :param request: :return: | Implement the Python class `UserBrowseHistory` described below.
Class description:
用户浏览sku记录
Method signatures and docstrings:
- def get(self, request): 获取浏览记录 :param request: :return:
- def post(self, request): 保存用户浏览记录 :param request: :return:
<|skeleton|>
class UserBrowseHistory:
"""用户浏览sku记录"""
def get(... | fecdf074ddb6844f33d6fadf05d40b0e562b46fb | <|skeleton|>
class UserBrowseHistory:
"""用户浏览sku记录"""
def get(self, request):
"""获取浏览记录 :param request: :return:"""
<|body_0|>
def post(self, request):
"""保存用户浏览记录 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserBrowseHistory:
"""用户浏览sku记录"""
def get(self, request):
"""获取浏览记录 :param request: :return:"""
user_id = request.user.id
redis_conn = get_redis_connection('history')
sku_ids = redis_conn.lrange('history_' + str(user_id), 0, -1)
sku_list = list()
for sku i... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/users/views.py | qls7/dianshang | train | 0 |
2a9ce8288b57e3f43422437ac239f06963ec74e2 | [
"super(LoadFactOperator, self).__init__(*args, **kwargs)\nself.redshift_conn_id = redshift_conn_id\nself.table = table\nself.sql_stmt = sql_stmt\nself.insert_stmt = insert_stmt\nself.create_table_stmt = create_table_stmt",
"redshift = PostgresHook(self.redshift_conn_id)\nif self.create_table_stmt:\n self.log.i... | <|body_start_0|>
super(LoadFactOperator, self).__init__(*args, **kwargs)
self.redshift_conn_id = redshift_conn_id
self.table = table
self.sql_stmt = sql_stmt
self.insert_stmt = insert_stmt
self.create_table_stmt = create_table_stmt
<|end_body_0|>
<|body_start_1|>
... | An airflow custom operator which loads the fact table from the staged tables. | LoadFactOperator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadFactOperator:
"""An airflow custom operator which loads the fact table from the staged tables."""
def __init__(self, redshift_conn_id, table, sql_stmt, insert_stmt=None, create_table_stmt=None, *args, **kwargs):
"""LoadFactOperator Constructor to inialize the object. Parameters -... | stack_v2_sparse_classes_36k_train_017149 | 2,303 | no_license | [
{
"docstring": "LoadFactOperator Constructor to inialize the object. Parameters ---------- redshift_conn_id : str redshift connection id used by the Postgresql hook table : str The fact table sql_stmt : str SQL statement which specifies how to load fact table from the staged tables create_table_stmt : str, opti... | 2 | stack_v2_sparse_classes_30k_train_011158 | Implement the Python class `LoadFactOperator` described below.
Class description:
An airflow custom operator which loads the fact table from the staged tables.
Method signatures and docstrings:
- def __init__(self, redshift_conn_id, table, sql_stmt, insert_stmt=None, create_table_stmt=None, *args, **kwargs): LoadFact... | Implement the Python class `LoadFactOperator` described below.
Class description:
An airflow custom operator which loads the fact table from the staged tables.
Method signatures and docstrings:
- def __init__(self, redshift_conn_id, table, sql_stmt, insert_stmt=None, create_table_stmt=None, *args, **kwargs): LoadFact... | c061dbede550e18111de346e58dfb5f258e4c63f | <|skeleton|>
class LoadFactOperator:
"""An airflow custom operator which loads the fact table from the staged tables."""
def __init__(self, redshift_conn_id, table, sql_stmt, insert_stmt=None, create_table_stmt=None, *args, **kwargs):
"""LoadFactOperator Constructor to inialize the object. Parameters -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadFactOperator:
"""An airflow custom operator which loads the fact table from the staged tables."""
def __init__(self, redshift_conn_id, table, sql_stmt, insert_stmt=None, create_table_stmt=None, *args, **kwargs):
"""LoadFactOperator Constructor to inialize the object. Parameters ---------- red... | the_stack_v2_python_sparse | capstone-project/plugins/operators/load_fact.py | MyDataDevOps/DataEngineeringNanoDegree | train | 0 |
964108a024c9f534d58c8b027b971aaefeb440bd | [
"self.head = head\nself.count = 0\nwhile head:\n self.count += 1\n head = head.next",
"randnode = random.randint(0, self.count - 1)\nnode = self.head\nfor _ in range(randnode):\n node = node.next\nreturn node.val"
] | <|body_start_0|>
self.head = head
self.count = 0
while head:
self.count += 1
head = head.next
<|end_body_0|>
<|body_start_1|>
randnode = random.randint(0, self.count - 1)
node = self.head
for _ in range(randnode):
node = node.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
<|body_0|>
def getRandom(self):
"""Returns a random node's value. :rtype: int"""
... | stack_v2_sparse_classes_36k_train_017150 | 1,294 | no_license | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode",
"name": "__init__",
"signature": "def __init__(self, head)"
},
{
"docstring": "Returns a random node's value. :rtype: int",
"name": "g... | 2 | stack_v2_sparse_classes_30k_train_008323 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode
- def getRan... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode
- def getRan... | 05e0beff0047f0ad399d0b46d625bb8d3459814e | <|skeleton|>
class Solution:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
<|body_0|>
def getRandom(self):
"""Returns a random node's value. :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
self.head = head
self.count = 0
while head:
self.count += 1
head = head.... | the_stack_v2_python_sparse | python_1_to_1000/382_Linked_List_Random_Node.py | jakehoare/leetcode | train | 58 | |
8ea4329aef7334952137eabc59a05d633ff0c0b5 | [
"LDC_Info.__init__(self)\nself.setTitle(self.name)\nif info_res:\n self.status = compat_res[0]\n self.ui.setupUi(self.frame)\n self.__fill_frame(info_res, compat_res, diag_res)\nelse:\n self.status = False\n self.__labelError(compat_res)",
"vendor = self._check_invalid_values(info_res.vendor[1])\nm... | <|body_start_0|>
LDC_Info.__init__(self)
self.setTitle(self.name)
if info_res:
self.status = compat_res[0]
self.ui.setupUi(self.frame)
self.__fill_frame(info_res, compat_res, diag_res)
else:
self.status = False
self.__labelError... | Estende a classe 'LDC_Info'. Classe que define a interface gráfica de exibição dos resultados de teclado | GUIKeyboard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GUIKeyboard:
"""Estende a classe 'LDC_Info'. Classe que define a interface gráfica de exibição dos resultados de teclado"""
def __init__(self, info_res, compat_res, diag_res):
"""Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResKeyboard') comp... | stack_v2_sparse_classes_36k_train_017151 | 3,044 | no_license | [
{
"docstring": "Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResKeyboard') compat_res -- Lista com as tuples de resultado de compatibilidade [(True, msg)] diag_res -- Lista com os resultados do diagnóstico (nesse caso não existe teste de diagnóstico, recebe-se uma lista... | 3 | null | Implement the Python class `GUIKeyboard` described below.
Class description:
Estende a classe 'LDC_Info'. Classe que define a interface gráfica de exibição dos resultados de teclado
Method signatures and docstrings:
- def __init__(self, info_res, compat_res, diag_res): Construtor Parâmetros: info_res -- lista com os ... | Implement the Python class `GUIKeyboard` described below.
Class description:
Estende a classe 'LDC_Info'. Classe que define a interface gráfica de exibição dos resultados de teclado
Method signatures and docstrings:
- def __init__(self, info_res, compat_res, diag_res): Construtor Parâmetros: info_res -- lista com os ... | bda0c2c8977dd1246339f1f0f4718d29e8795f21 | <|skeleton|>
class GUIKeyboard:
"""Estende a classe 'LDC_Info'. Classe que define a interface gráfica de exibição dos resultados de teclado"""
def __init__(self, info_res, compat_res, diag_res):
"""Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResKeyboard') comp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GUIKeyboard:
"""Estende a classe 'LDC_Info'. Classe que define a interface gráfica de exibição dos resultados de teclado"""
def __init__(self, info_res, compat_res, diag_res):
"""Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResKeyboard') compat_res -- Lis... | the_stack_v2_python_sparse | src/libs/keyboard/gui_keyboard.py | adrianomelo/ldc-desktop | train | 1 |
f217506aef774eb17f292ac77057ca875c681d30 | [
"def search(node, sum):\n if not node:\n return 0\n count = 0\n if node.val == sum:\n count += 1\n count += search(node.left, sum - node.val)\n count += search(node.right, sum - node.val)\n return count\nif not root:\n return 0\nreturn search(root, sum) + self.pathSum(root.left, s... | <|body_start_0|>
def search(node, sum):
if not node:
return 0
count = 0
if node.val == sum:
count += 1
count += search(node.left, sum - node.val)
count += search(node.right, sum - node.val)
return count
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
<|body_0|>
def pathSum_hashtable(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
<|body_1|>
def pathSum_failed(self, root, sum):
... | stack_v2_sparse_classes_36k_train_017152 | 3,840 | no_license | [
{
"docstring": ":type root: TreeNode :type sum: int :rtype: int",
"name": "pathSum",
"signature": "def pathSum(self, root, sum)"
},
{
"docstring": ":type root: TreeNode :type sum: int :rtype: int",
"name": "pathSum_hashtable",
"signature": "def pathSum_hashtable(self, root, sum)"
},
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: int
- def pathSum_hashtable(self, root, sum): :type root: TreeNode :type sum: int :rtype: int
- def path... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: int
- def pathSum_hashtable(self, root, sum): :type root: TreeNode :type sum: int :rtype: int
- def path... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
<|body_0|>
def pathSum_hashtable(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
<|body_1|>
def pathSum_failed(self, root, sum):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
def search(node, sum):
if not node:
return 0
count = 0
if node.val == sum:
count += 1
count += search(node.left, sum - n... | the_stack_v2_python_sparse | src/lt_437.py | oxhead/CodingYourWay | train | 0 | |
eab96c529f9e70bb8947f994cc16013633d2a84f | [
"res = []\n\ndef f(node):\n if node is not None:\n res.append(str(node.val))\n f(node.left)\n f(node.right)\nf(root)\nreturn ' '.join(res)",
"res = None\nfor i in data.split():\n i = int(i)\n res = insert(res, i)\nreturn res"
] | <|body_start_0|>
res = []
def f(node):
if node is not None:
res.append(str(node.val))
f(node.left)
f(node.right)
f(root)
return ' '.join(res)
<|end_body_0|>
<|body_start_1|>
res = None
for i in data.split():
... | 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_017153 | 976 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | f4da5a5dbda640b9bcbe14cb60a72c422b5d6240 | <|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"""
res = []
def f(node):
if node is not None:
res.append(str(node.val))
f(node.left)
f(node.right)
f(root)
... | the_stack_v2_python_sparse | leetcode/449.py | phlalx/algorithms | train | 0 | |
7b68256b40c277ef2e6d3eb26675c4a8d7bf005d | [
"super(InternalProcessing, self).__init__()\nset_seed()\nself._hidden_size = kwargs.get('hidden_size', 128)\nself._expansion_size = kwargs.get('expansion_size', 128)\nself._activation_fn = kwargs.get('activation_fn', 'sigmoid')\nself._seqlen = kwargs.get('seqlen', 150)\nself.device = torch.device('cuda' if torch.cu... | <|body_start_0|>
super(InternalProcessing, self).__init__()
set_seed()
self._hidden_size = kwargs.get('hidden_size', 128)
self._expansion_size = kwargs.get('expansion_size', 128)
self._activation_fn = kwargs.get('activation_fn', 'sigmoid')
self._seqlen = kwargs.get('seqle... | InternalProcessing | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InternalProcessing:
def __init__(self, **kwargs):
""": expansion_size (int): : hidden_size (int):"""
<|body_0|>
def build(self, weight=0.5):
"""Generates matrixes and layers to implement internal processing. : batch_size (int):"""
<|body_1|>
def forward(... | stack_v2_sparse_classes_36k_train_017154 | 28,550 | permissive | [
{
"docstring": ": expansion_size (int): : hidden_size (int):",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Generates matrixes and layers to implement internal processing. : batch_size (int):",
"name": "build",
"signature": "def build(self, weight=0.... | 5 | stack_v2_sparse_classes_30k_train_006974 | Implement the Python class `InternalProcessing` described below.
Class description:
Implement the InternalProcessing class.
Method signatures and docstrings:
- def __init__(self, **kwargs): : expansion_size (int): : hidden_size (int):
- def build(self, weight=0.5): Generates matrixes and layers to implement internal ... | Implement the Python class `InternalProcessing` described below.
Class description:
Implement the InternalProcessing class.
Method signatures and docstrings:
- def __init__(self, **kwargs): : expansion_size (int): : hidden_size (int):
- def build(self, weight=0.5): Generates matrixes and layers to implement internal ... | a730e02153709b9c0e7f83deb0042ae9f9c1ce15 | <|skeleton|>
class InternalProcessing:
def __init__(self, **kwargs):
""": expansion_size (int): : hidden_size (int):"""
<|body_0|>
def build(self, weight=0.5):
"""Generates matrixes and layers to implement internal processing. : batch_size (int):"""
<|body_1|>
def forward(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InternalProcessing:
def __init__(self, **kwargs):
""": expansion_size (int): : hidden_size (int):"""
super(InternalProcessing, self).__init__()
set_seed()
self._hidden_size = kwargs.get('hidden_size', 128)
self._expansion_size = kwargs.get('expansion_size', 128)
... | the_stack_v2_python_sparse | model/snn.py | licj1/Siamese-RNN-Self-Attention | train | 0 | |
61aa0263881b34fb650b43e81dcd876c1d936cd4 | [
"def dfs(i, j, si, sj):\n if i >= m or j >= n or k < si + sj or ((i, j) in visited):\n return 0\n visited.add((i, j))\n return 1 + dfs(i + 1, j, si + 1 if (i + 1) % 10 else si - 8, sj) + dfs(i, j + 1, si, sj + 1 if (j + 1) % 10 else sj - 8)\nvisited = set()\nreturn dfs(0, 0, 0, 0)",
"queue, visite... | <|body_start_0|>
def dfs(i, j, si, sj):
if i >= m or j >= n or k < si + sj or ((i, j) in visited):
return 0
visited.add((i, j))
return 1 + dfs(i + 1, j, si + 1 if (i + 1) % 10 else si - 8, sj) + dfs(i, j + 1, si, sj + 1 if (j + 1) % 10 else sj - 8)
vis... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
"""每遍历一个点都记到visited si + sj 为数位和 个位或者10位增加1,可以有数位增量的计算公式"""
<|body_0|>
def movingCount1(self, m: int, n: int, k: int) -> int:
"""每当把一个值推出栈时,只要根据它变化的值符合条件,则加到栈里面"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_017155 | 1,579 | no_license | [
{
"docstring": "每遍历一个点都记到visited si + sj 为数位和 个位或者10位增加1,可以有数位增量的计算公式",
"name": "movingCount",
"signature": "def movingCount(self, m: int, n: int, k: int) -> int"
},
{
"docstring": "每当把一个值推出栈时,只要根据它变化的值符合条件,则加到栈里面",
"name": "movingCount1",
"signature": "def movingCount1(self, m: int, n: ... | 2 | stack_v2_sparse_classes_30k_train_010498 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def movingCount(self, m: int, n: int, k: int) -> int: 每遍历一个点都记到visited si + sj 为数位和 个位或者10位增加1,可以有数位增量的计算公式
- def movingCount1(self, m: int, n: int, k: int) -> int: 每当把一个值推出栈时,只要... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def movingCount(self, m: int, n: int, k: int) -> int: 每遍历一个点都记到visited si + sj 为数位和 个位或者10位增加1,可以有数位增量的计算公式
- def movingCount1(self, m: int, n: int, k: int) -> int: 每当把一个值推出栈时,只要... | 4a27fdd976268bf4daf8eee447efd754f1e0bb02 | <|skeleton|>
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
"""每遍历一个点都记到visited si + sj 为数位和 个位或者10位增加1,可以有数位增量的计算公式"""
<|body_0|>
def movingCount1(self, m: int, n: int, k: int) -> int:
"""每当把一个值推出栈时,只要根据它变化的值符合条件,则加到栈里面"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
"""每遍历一个点都记到visited si + sj 为数位和 个位或者10位增加1,可以有数位增量的计算公式"""
def dfs(i, j, si, sj):
if i >= m or j >= n or k < si + sj or ((i, j) in visited):
return 0
visited.add((i, j))
return ... | the_stack_v2_python_sparse | ji-qi-ren-de-yun-dong-fan-wei-lcof.py | Angel888/suanfa | train | 0 | |
16b69d97835887027f37fd816331299ec1250108 | [
"self.title.append(title)\nself.description.append(description)\nself.assignee.append(assignee)\nself.status.append(status)\nself.dueDate.append(dueDate)\nself.tags.append(tags)\nsuper(Issue, self).__init__()",
"self.validate_object()\nif kind is None or kind == 'create':\n self.only_available_attrs(['title', ... | <|body_start_0|>
self.title.append(title)
self.description.append(description)
self.assignee.append(assignee)
self.status.append(status)
self.dueDate.append(dueDate)
self.tags.append(tags)
super(Issue, self).__init__()
<|end_body_0|>
<|body_start_1|>
self... | CodeDiscussionsByChange | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodeDiscussionsByChange:
def __init__(self, title: str=Empty, description=Empty, assignee: str=Empty, status: str=Empty, dueDate: str=Empty, tags: list=Empty):
""":param title: :param description: :param assignee: :param status: :param dueDate: :param tags:"""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_017156 | 2,112 | no_license | [
{
"docstring": ":param title: :param description: :param assignee: :param status: :param dueDate: :param tags:",
"name": "__init__",
"signature": "def __init__(self, title: str=Empty, description=Empty, assignee: str=Empty, status: str=Empty, dueDate: str=Empty, tags: list=Empty)"
},
{
"docstrin... | 2 | null | Implement the Python class `CodeDiscussionsByChange` described below.
Class description:
Implement the CodeDiscussionsByChange class.
Method signatures and docstrings:
- def __init__(self, title: str=Empty, description=Empty, assignee: str=Empty, status: str=Empty, dueDate: str=Empty, tags: list=Empty): :param title:... | Implement the Python class `CodeDiscussionsByChange` described below.
Class description:
Implement the CodeDiscussionsByChange class.
Method signatures and docstrings:
- def __init__(self, title: str=Empty, description=Empty, assignee: str=Empty, status: str=Empty, dueDate: str=Empty, tags: list=Empty): :param title:... | 623d23917ecf6761e7254d7d6a4881b6a05e11f8 | <|skeleton|>
class CodeDiscussionsByChange:
def __init__(self, title: str=Empty, description=Empty, assignee: str=Empty, status: str=Empty, dueDate: str=Empty, tags: list=Empty):
""":param title: :param description: :param assignee: :param status: :param dueDate: :param tags:"""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CodeDiscussionsByChange:
def __init__(self, title: str=Empty, description=Empty, assignee: str=Empty, status: str=Empty, dueDate: str=Empty, tags: list=Empty):
""":param title: :param description: :param assignee: :param status: :param dueDate: :param tags:"""
self.title.append(title)
... | the_stack_v2_python_sparse | space_sdk/space_types/code_discussions.py | AnthraxisBR/jetbrains-space-python-sdk | train | 0 | |
e0bc5a67c4d15d8faafc20f0f73bbb3473acf5c3 | [
"manager = self.request.registry.queryMultiAdapter((self.request, self.context), IManager)\napplicant = self.request.validated.get('document', self.request.validated.get('file'))\ndocument = manager.create(applicant)\nif manager.save():\n msg = 'Created auction bid document {}'.format(document.id)\n extra = c... | <|body_start_0|>
manager = self.request.registry.queryMultiAdapter((self.request, self.context), IManager)
applicant = self.request.validated.get('document', self.request.validated.get('file'))
document = manager.create(applicant)
if manager.save():
msg = 'Created auction bid... | AuctionBidDocumentResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuctionBidDocumentResource:
def collection_post(self):
"""Auction Bid Document Upload"""
<|body_0|>
def patch(self):
"""Auction Bid Document Update"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
manager = self.request.registry.queryMultiAdapter((se... | stack_v2_sparse_classes_36k_train_017157 | 2,519 | permissive | [
{
"docstring": "Auction Bid Document Upload",
"name": "collection_post",
"signature": "def collection_post(self)"
},
{
"docstring": "Auction Bid Document Update",
"name": "patch",
"signature": "def patch(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014930 | Implement the Python class `AuctionBidDocumentResource` described below.
Class description:
Implement the AuctionBidDocumentResource class.
Method signatures and docstrings:
- def collection_post(self): Auction Bid Document Upload
- def patch(self): Auction Bid Document Update | Implement the Python class `AuctionBidDocumentResource` described below.
Class description:
Implement the AuctionBidDocumentResource class.
Method signatures and docstrings:
- def collection_post(self): Auction Bid Document Upload
- def patch(self): Auction Bid Document Update
<|skeleton|>
class AuctionBidDocumentRe... | 05c9ea3db1b1d290521b1430286ff2e5064819cd | <|skeleton|>
class AuctionBidDocumentResource:
def collection_post(self):
"""Auction Bid Document Upload"""
<|body_0|>
def patch(self):
"""Auction Bid Document Update"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuctionBidDocumentResource:
def collection_post(self):
"""Auction Bid Document Upload"""
manager = self.request.registry.queryMultiAdapter((self.request, self.context), IManager)
applicant = self.request.validated.get('document', self.request.validated.get('file'))
document = m... | the_stack_v2_python_sparse | openprocurement/auctions/geb/views/bid_document.py | andrey484/openprocurement.auctions.geb | train | 0 | |
e4072504afac839bf1c01667f230cd527291ff1d | [
"self.logger.debug('Resolving query of type %s', query.query_type)\nfor s in query.selectables:\n self.logger.debug(' ...with selectable %r', s.selectable.raw)\nprocess_queries = query.selectables\nif query.selectables[0].parent:\n if query.selectables[0].parent.is_type('set_expression'):\n process_q... | <|body_start_0|>
self.logger.debug('Resolving query of type %s', query.query_type)
for s in query.selectables:
self.logger.debug(' ...with selectable %r', s.selectable.raw)
process_queries = query.selectables
if query.selectables[0].parent:
if query.selectables[... | Queries within set query produce different numbers of columns. **Anti-pattern** When writing set expressions, all queries must return the same number of columns. .. code-block:: sql WITH cte AS ( SELECT a, b FROM foo ) SELECT * FROM cte UNION SELECT c, d, e FROM t **Best practice** Always specify columns when writing s... | Rule_AM07 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule_AM07:
"""Queries within set query produce different numbers of columns. **Anti-pattern** When writing set expressions, all queries must return the same number of columns. .. code-block:: sql WITH cte AS ( SELECT a, b FROM foo ) SELECT * FROM cte UNION SELECT c, d, e FROM t **Best practice** ... | stack_v2_sparse_classes_36k_train_017158 | 9,079 | permissive | [
{
"docstring": "Attempt to resolve a full query which may contain wildcards. NOTE: This requires a ``Query`` as input rather than just a ``Selectable`` and will delegate to ``__resolve_selectable`` once any Selectables have been identified. This method is *not* called on the initial set expression as that is ev... | 5 | stack_v2_sparse_classes_30k_train_019661 | Implement the Python class `Rule_AM07` described below.
Class description:
Queries within set query produce different numbers of columns. **Anti-pattern** When writing set expressions, all queries must return the same number of columns. .. code-block:: sql WITH cte AS ( SELECT a, b FROM foo ) SELECT * FROM cte UNION S... | Implement the Python class `Rule_AM07` described below.
Class description:
Queries within set query produce different numbers of columns. **Anti-pattern** When writing set expressions, all queries must return the same number of columns. .. code-block:: sql WITH cte AS ( SELECT a, b FROM foo ) SELECT * FROM cte UNION S... | a66da908907ee1eaf09d88a731025da29e7fca07 | <|skeleton|>
class Rule_AM07:
"""Queries within set query produce different numbers of columns. **Anti-pattern** When writing set expressions, all queries must return the same number of columns. .. code-block:: sql WITH cte AS ( SELECT a, b FROM foo ) SELECT * FROM cte UNION SELECT c, d, e FROM t **Best practice** ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rule_AM07:
"""Queries within set query produce different numbers of columns. **Anti-pattern** When writing set expressions, all queries must return the same number of columns. .. code-block:: sql WITH cte AS ( SELECT a, b FROM foo ) SELECT * FROM cte UNION SELECT c, d, e FROM t **Best practice** Always specif... | the_stack_v2_python_sparse | src/sqlfluff/rules/ambiguous/AM07.py | sqlfluff/sqlfluff | train | 5,931 |
638cddc6378496eb6b4971688f1fa2b3f0f596ba | [
"apicifc = self.get_data('apicifc')\ntrigger_xmls = self.get_data('trigger_xmls')\nfor graph, _ in trigger_xmls:\n tenant_name = graph.get('name')\n vdev = ACMD.system.get_vdev(Tenant.TENANT_DN % tenant_name, ifc=apicifc)\n partition_number = vdev.get('id')\n ctx_name = vdev.get('ctxName')\n ip_parti... | <|body_start_0|>
apicifc = self.get_data('apicifc')
trigger_xmls = self.get_data('trigger_xmls')
for graph, _ in trigger_xmls:
tenant_name = graph.get('name')
vdev = ACMD.system.get_vdev(Tenant.TENANT_DN % tenant_name, ifc=apicifc)
partition_number = vdev.get(... | This is like a healper class for trigger tests. All trigger tests can be run on any graph. To use this class: class Tests(InterfaceTestCase, BasicTriggers): ... | BasicTriggers | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicTriggers:
"""This is like a healper class for trigger tests. All trigger tests can be run on any graph. To use this class: class Tests(InterfaceTestCase, BasicTriggers): ..."""
def test_100_tenant(self):
"""1) Delete Tenant 2) Wait until graphs deleted from BIG-IQ and BIG-IPs 3)... | stack_v2_sparse_classes_36k_train_017159 | 3,975 | permissive | [
{
"docstring": "1) Delete Tenant 2) Wait until graphs deleted from BIG-IQ and BIG-IPs 3) Add back fvTenant",
"name": "test_100_tenant",
"signature": "def test_100_tenant(self)"
},
{
"docstring": "1) Delete 1 provider EPG 2) Wait until graphs deleted from BIG-IQ and BIG-IPs 3) Verify faults 4) Ad... | 5 | stack_v2_sparse_classes_30k_train_012657 | Implement the Python class `BasicTriggers` described below.
Class description:
This is like a healper class for trigger tests. All trigger tests can be run on any graph. To use this class: class Tests(InterfaceTestCase, BasicTriggers): ...
Method signatures and docstrings:
- def test_100_tenant(self): 1) Delete Tenan... | Implement the Python class `BasicTriggers` described below.
Class description:
This is like a healper class for trigger tests. All trigger tests can be run on any graph. To use this class: class Tests(InterfaceTestCase, BasicTriggers): ...
Method signatures and docstrings:
- def test_100_tenant(self): 1) Delete Tenan... | 40264ac83b3f1d2a30ebc1107927044f42c86f8a | <|skeleton|>
class BasicTriggers:
"""This is like a healper class for trigger tests. All trigger tests can be run on any graph. To use this class: class Tests(InterfaceTestCase, BasicTriggers): ..."""
def test_100_tenant(self):
"""1) Delete Tenant 2) Wait until graphs deleted from BIG-IQ and BIG-IPs 3)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicTriggers:
"""This is like a healper class for trigger tests. All trigger tests can be run on any graph. To use this class: class Tests(InterfaceTestCase, BasicTriggers): ..."""
def test_100_tenant(self):
"""1) Delete Tenant 2) Wait until graphs deleted from BIG-IQ and BIG-IPs 3) Add back fvT... | the_stack_v2_python_sparse | f5test/utils/mixins/apic/basic_triggers.py | jonozzz/nosest | train | 1 |
effb0514c1d90620f1ed8944e7e8ba35c287f066 | [
"self.user = 'Test User1337'\nself.subject = 'TDT4120'\nself.test_sub = 'TST4' + str(random.randint(0, 2000))",
"user_methods.add_user(self.user, self.subject)\nwith Capturing() as output:\n user_methods.add_user(self.user, self.subject)\nif len(output) > 0:\n self.assertEqual('User already exists', str(out... | <|body_start_0|>
self.user = 'Test User1337'
self.subject = 'TDT4120'
self.test_sub = 'TST4' + str(random.randint(0, 2000))
<|end_body_0|>
<|body_start_1|>
user_methods.add_user(self.user, self.subject)
with Capturing() as output:
user_methods.add_user(self.user, sel... | UserMethodTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserMethodTests:
def setUp(self):
"""Sets the test values which are sent to the database :return:"""
<|body_0|>
def test_user_methods(self):
"""Tests the various methods in user_methods.py as described onwards"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_017160 | 28,630 | no_license | [
{
"docstring": "Sets the test values which are sent to the database :return:",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests the various methods in user_methods.py as described onwards",
"name": "test_user_methods",
"signature": "def test_user_methods(self)"
... | 2 | stack_v2_sparse_classes_30k_train_000893 | Implement the Python class `UserMethodTests` described below.
Class description:
Implement the UserMethodTests class.
Method signatures and docstrings:
- def setUp(self): Sets the test values which are sent to the database :return:
- def test_user_methods(self): Tests the various methods in user_methods.py as describ... | Implement the Python class `UserMethodTests` described below.
Class description:
Implement the UserMethodTests class.
Method signatures and docstrings:
- def setUp(self): Sets the test values which are sent to the database :return:
- def test_user_methods(self): Tests the various methods in user_methods.py as describ... | 32bc79ce99ca81cfc6e36435cee3e95dcaf27035 | <|skeleton|>
class UserMethodTests:
def setUp(self):
"""Sets the test values which are sent to the database :return:"""
<|body_0|>
def test_user_methods(self):
"""Tests the various methods in user_methods.py as described onwards"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserMethodTests:
def setUp(self):
"""Sets the test values which are sent to the database :return:"""
self.user = 'Test User1337'
self.subject = 'TDT4120'
self.test_sub = 'TST4' + str(random.randint(0, 2000))
def test_user_methods(self):
"""Tests the various methods... | the_stack_v2_python_sparse | testing_methods.py | Pontius1007/Pekka-Paradise | train | 1 | |
f25c4ca8f74cd3079a0809aba38c573067e943f0 | [
"t_min, t_max, t_increment = (200.15, 220.15, 10.0)\nresult = SaturatedVapourPressureTable(t_min=t_min, t_max=t_max, t_increment=t_increment).process()\nself.assertEqual(result.attributes['minimum_temperature'], t_min)\nself.assertEqual(result.attributes['maximum_temperature'], t_max)\nself.assertEqual(result.attri... | <|body_start_0|>
t_min, t_max, t_increment = (200.15, 220.15, 10.0)
result = SaturatedVapourPressureTable(t_min=t_min, t_max=t_max, t_increment=t_increment).process()
self.assertEqual(result.attributes['minimum_temperature'], t_min)
self.assertEqual(result.attributes['maximum_temperature... | Test that the plugin functions as expected. | Test_process | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_process:
"""Test that the plugin functions as expected."""
def test_cube_attributes(self):
"""Test that returned cube has appropriate attributes."""
<|body_0|>
def test_cube_values(self):
"""Test that returned cube has expected values."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_017161 | 4,810 | permissive | [
{
"docstring": "Test that returned cube has appropriate attributes.",
"name": "test_cube_attributes",
"signature": "def test_cube_attributes(self)"
},
{
"docstring": "Test that returned cube has expected values.",
"name": "test_cube_values",
"signature": "def test_cube_values(self)"
},... | 3 | stack_v2_sparse_classes_30k_train_002896 | Implement the Python class `Test_process` described below.
Class description:
Test that the plugin functions as expected.
Method signatures and docstrings:
- def test_cube_attributes(self): Test that returned cube has appropriate attributes.
- def test_cube_values(self): Test that returned cube has expected values.
-... | Implement the Python class `Test_process` described below.
Class description:
Test that the plugin functions as expected.
Method signatures and docstrings:
- def test_cube_attributes(self): Test that returned cube has appropriate attributes.
- def test_cube_values(self): Test that returned cube has expected values.
-... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_process:
"""Test that the plugin functions as expected."""
def test_cube_attributes(self):
"""Test that returned cube has appropriate attributes."""
<|body_0|>
def test_cube_values(self):
"""Test that returned cube has expected values."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_process:
"""Test that the plugin functions as expected."""
def test_cube_attributes(self):
"""Test that returned cube has appropriate attributes."""
t_min, t_max, t_increment = (200.15, 220.15, 10.0)
result = SaturatedVapourPressureTable(t_min=t_min, t_max=t_max, t_increment=... | the_stack_v2_python_sparse | improver_tests/generate_ancillaries/test_SaturatedVapourPressureTable.py | metoppv/improver | train | 101 |
e5a06ce5c0bb6e1cd2a8cabc384c516f2222ec19 | [
"self.source = source\nself.rss_address = self.source.config.filter(config_key='rss_feed_address').first().config_value\nself.rss_feed = feedparser.parse(self.rss_address)",
"for job_info in self.rss_feed.entries:\n post = self.parse_job_to_post(job_info)\n yield post",
"logger.debug('Parsing: %s', job_in... | <|body_start_0|>
self.source = source
self.rss_address = self.source.config.filter(config_key='rss_feed_address').first().config_value
self.rss_feed = feedparser.parse(self.rss_address)
<|end_body_0|>
<|body_start_1|>
for job_info in self.rss_feed.entries:
post = self.parse_... | Wrapper for the RssFeed source. | RssFeed | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RssFeed:
"""Wrapper for the RssFeed source."""
def __init__(self, source):
"""Parse the API."""
<|body_0|>
def jobs(self):
"""Iterate through all available jobs."""
<|body_1|>
def parse_job_to_post(self, job_info):
"""Convert from the rss fee... | stack_v2_sparse_classes_36k_train_017162 | 1,712 | permissive | [
{
"docstring": "Parse the API.",
"name": "__init__",
"signature": "def __init__(self, source)"
},
{
"docstring": "Iterate through all available jobs.",
"name": "jobs",
"signature": "def jobs(self)"
},
{
"docstring": "Convert from the rss feed format to a Post.",
"name": "pars... | 3 | stack_v2_sparse_classes_30k_train_013036 | Implement the Python class `RssFeed` described below.
Class description:
Wrapper for the RssFeed source.
Method signatures and docstrings:
- def __init__(self, source): Parse the API.
- def jobs(self): Iterate through all available jobs.
- def parse_job_to_post(self, job_info): Convert from the rss feed format to a P... | Implement the Python class `RssFeed` described below.
Class description:
Wrapper for the RssFeed source.
Method signatures and docstrings:
- def __init__(self, source): Parse the API.
- def jobs(self): Iterate through all available jobs.
- def parse_job_to_post(self, job_info): Convert from the rss feed format to a P... | 7882aa8ed42afe689e594a3e10c9fc6369f70bf5 | <|skeleton|>
class RssFeed:
"""Wrapper for the RssFeed source."""
def __init__(self, source):
"""Parse the API."""
<|body_0|>
def jobs(self):
"""Iterate through all available jobs."""
<|body_1|>
def parse_job_to_post(self, job_info):
"""Convert from the rss fee... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RssFeed:
"""Wrapper for the RssFeed source."""
def __init__(self, source):
"""Parse the API."""
self.source = source
self.rss_address = self.source.config.filter(config_key='rss_feed_address').first().config_value
self.rss_feed = feedparser.parse(self.rss_address)
def... | the_stack_v2_python_sparse | freelancefinder/remotes/sources/rss_feed/rss_feed.py | simo97/freelancefinder | train | 0 |
ae599ab2276eb4f0f40c7ce7dd745fc3b0b2527f | [
"self.sprite = pygame.image.load(spritepath)\ncw, ch = charsize\nsw, sh = (self.sprite.get_width() / cw, self.sprite.get_height() / ch)\nspacewidth = spacewidth if spacewidth is not None else cw * 0.4\nself.height = ch\nself.chars = {}\nfor y in range(sh):\n for x in range(sw):\n char = chr(x + y * sw)\n ... | <|body_start_0|>
self.sprite = pygame.image.load(spritepath)
cw, ch = charsize
sw, sh = (self.sprite.get_width() / cw, self.sprite.get_height() / ch)
spacewidth = spacewidth if spacewidth is not None else cw * 0.4
self.height = ch
self.chars = {}
for y in range(sh... | Font | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Font:
def __init__(self, spritepath, charsize, mono=False, spacewidth=None):
"""Given a sprite that is a grid of characters, and the dimensions of each character, slice it into a dict of surfaces mapped to each character in ASCII sequence, starting at 0."""
<|body_0|>
def re... | stack_v2_sparse_classes_36k_train_017163 | 3,921 | no_license | [
{
"docstring": "Given a sprite that is a grid of characters, and the dimensions of each character, slice it into a dict of surfaces mapped to each character in ASCII sequence, starting at 0.",
"name": "__init__",
"signature": "def __init__(self, spritepath, charsize, mono=False, spacewidth=None)"
},
... | 4 | stack_v2_sparse_classes_30k_train_012798 | Implement the Python class `Font` described below.
Class description:
Implement the Font class.
Method signatures and docstrings:
- def __init__(self, spritepath, charsize, mono=False, spacewidth=None): Given a sprite that is a grid of characters, and the dimensions of each character, slice it into a dict of surfaces... | Implement the Python class `Font` described below.
Class description:
Implement the Font class.
Method signatures and docstrings:
- def __init__(self, spritepath, charsize, mono=False, spacewidth=None): Given a sprite that is a grid of characters, and the dimensions of each character, slice it into a dict of surfaces... | 6c769822a65ee0be48922da88f9910068ad58a4f | <|skeleton|>
class Font:
def __init__(self, spritepath, charsize, mono=False, spacewidth=None):
"""Given a sprite that is a grid of characters, and the dimensions of each character, slice it into a dict of surfaces mapped to each character in ASCII sequence, starting at 0."""
<|body_0|>
def re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Font:
def __init__(self, spritepath, charsize, mono=False, spacewidth=None):
"""Given a sprite that is a grid of characters, and the dimensions of each character, slice it into a dict of surfaces mapped to each character in ASCII sequence, starting at 0."""
self.sprite = pygame.image.load(spri... | the_stack_v2_python_sparse | pyg/font.py | saltire/roverchip-tdd | train | 0 | |
36dbfed16e7ad4e03314fc81ffe28e2205216e57 | [
"def six_addr():\n ans = ''\n tmp = ''\n for i in range(6):\n tmp = letters[random.randint(0, 10000) % 62]\n ans = ans + tmp\n return ans\nif longUrl in full_tiny:\n return 'http://tinyurl.com/' + full_tiny[longUrl]\nelse:\n suffix = six_addr()\n full_tiny[longUrl] = suffix\n t... | <|body_start_0|>
def six_addr():
ans = ''
tmp = ''
for i in range(6):
tmp = letters[random.randint(0, 10000) % 62]
ans = ans + tmp
return ans
if longUrl in full_tiny:
return 'http://tinyurl.com/' + full_tiny[long... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_017164 | 3,449 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL. :type longUrl: str :rtype: str",
"name": "encode",
"signature": "def encode(self, longUrl)"
},
{
"docstring": "Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str",
"name": "decode",
"signature": "def decode(self,... | 2 | stack_v2_sparse_classes_30k_train_011839 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | db2cd34ee759721858a96d123e3cab4084e69129 | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
def six_addr():
ans = ''
tmp = ''
for i in range(6):
tmp = letters[random.randint(0, 10000) % 62]
ans = ans + tmp
... | the_stack_v2_python_sparse | Algorithm-Medium/535_Encode_and_Decode_TinyURL.py | yz5308/Python_Leetcode | train | 0 | |
aa81ee9a8e3e87e2be61d70693ecad0ba0351a21 | [
"dp, sm = ({0: -1}, 0)\nright, cnt = (-1, 0)\nfor i in range(len(nums)):\n sm += nums[i]\n if sm - target in dp:\n left = dp[sm - target]\n if right <= left:\n cnt += 1\n right = i\n dp[sm] = i\nreturn cnt",
"sm = [0]\nfor i in nums:\n sm.append(sm[-1] + i)\nm, righ... | <|body_start_0|>
dp, sm = ({0: -1}, 0)
right, cnt = (-1, 0)
for i in range(len(nums)):
sm += nums[i]
if sm - target in dp:
left = dp[sm - target]
if right <= left:
cnt += 1
right = i
dp[sm... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxNonOverlappingOnepass(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def maxNonOverlapping(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_017165 | 2,266 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "maxNonOverlappingOnepass",
"signature": "def maxNonOverlappingOnepass(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "maxNonOverlapping",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_006657 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxNonOverlappingOnepass(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def maxNonOverlapping(self, nums, target): :type nums: List[int] :type tar... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxNonOverlappingOnepass(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def maxNonOverlapping(self, nums, target): :type nums: List[int] :type tar... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def maxNonOverlappingOnepass(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def maxNonOverlapping(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxNonOverlappingOnepass(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
dp, sm = ({0: -1}, 0)
right, cnt = (-1, 0)
for i in range(len(nums)):
sm += nums[i]
if sm - target in dp:
left = dp[sm -... | the_stack_v2_python_sparse | M/MaximumNumberofNon-OverlappingSubarraysWithSumEqualsTarget.py | bssrdf/pyleet | train | 2 | |
a636ab10d3ae523135a311cff300cc44d98ccba7 | [
"if not root:\n return 0\nif not root.left and (not root.right):\n return 1\nq = [root]\nstep = 1\nwhile q:\n s = len(q)\n for i in range(s):\n cur = q.pop(0)\n if not cur.left and (not cur.right):\n return step\n if cur.left:\n q.append(cur.left)\n if c... | <|body_start_0|>
if not root:
return 0
if not root.left and (not root.right):
return 1
q = [root]
step = 1
while q:
s = len(q)
for i in range(s):
cur = q.pop(0)
if not cur.left and (not cur.right):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth1(self, root):
""":type root: TreeNode :rtype: int :迭代"""
<|body_0|>
def minDepth(self, root):
""":type root: TreeNode :rtype: int :递归"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
if... | stack_v2_sparse_classes_36k_train_017166 | 1,888 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int :迭代",
"name": "minDepth1",
"signature": "def minDepth1(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int :递归",
"name": "minDepth",
"signature": "def minDepth(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth1(self, root): :type root: TreeNode :rtype: int :迭代
- def minDepth(self, root): :type root: TreeNode :rtype: int :递归 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth1(self, root): :type root: TreeNode :rtype: int :迭代
- def minDepth(self, root): :type root: TreeNode :rtype: int :递归
<|skeleton|>
class Solution:
def minDepth1(... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def minDepth1(self, root):
""":type root: TreeNode :rtype: int :迭代"""
<|body_0|>
def minDepth(self, root):
""":type root: TreeNode :rtype: int :递归"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth1(self, root):
""":type root: TreeNode :rtype: int :迭代"""
if not root:
return 0
if not root.left and (not root.right):
return 1
q = [root]
step = 1
while q:
s = len(q)
for i in range(s):
... | the_stack_v2_python_sparse | 111.二叉树的最小深度.py | yangyuxiang1996/leetcode | train | 0 | |
614d94f1a5d86a22086afd8a228b1981f59d1b8c | [
"super().__init__(columns=columns, rows=rows, spacing=spacing, ref_cell=device, origin=origin, rotation=rotation, magnification=magnification, x_reflection=x_reflection, ignore_missing=False)\nself.parent = device\nself.owner = None",
"bbox = self.get_bounding_box()\nif bbox is None:\n bbox = ((0, 0), (0, 0))\... | <|body_start_0|>
super().__init__(columns=columns, rows=rows, spacing=spacing, ref_cell=device, origin=origin, rotation=rotation, magnification=magnification, x_reflection=x_reflection, ignore_missing=False)
self.parent = device
self.owner = None
<|end_body_0|>
<|body_start_1|>
bbox = s... | Multiple references to an existing cell in an array format. Args: device : Component The referenced Component. columns : int Number of columns in the array. rows : int Number of rows in the array. spacing : array-like[2] of int or float Distances between adjacent columns and adjacent rows. origin : array-like[2] of int... | CellArray | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CellArray:
"""Multiple references to an existing cell in an array format. Args: device : Component The referenced Component. columns : int Number of columns in the array. rows : int Number of rows in the array. spacing : array-like[2] of int or float Distances between adjacent columns and adjacen... | stack_v2_sparse_classes_36k_train_017167 | 30,147 | permissive | [
{
"docstring": "Initialize CellArray.",
"name": "__init__",
"signature": "def __init__(self, device, columns, rows, spacing, origin=(0, 0), rotation=0, magnification=None, x_reflection=False)"
},
{
"docstring": "Returns the bounding box of the CellArray.",
"name": "bbox",
"signature": "d... | 5 | stack_v2_sparse_classes_30k_train_001814 | Implement the Python class `CellArray` described below.
Class description:
Multiple references to an existing cell in an array format. Args: device : Component The referenced Component. columns : int Number of columns in the array. rows : int Number of rows in the array. spacing : array-like[2] of int or float Distanc... | Implement the Python class `CellArray` described below.
Class description:
Multiple references to an existing cell in an array format. Args: device : Component The referenced Component. columns : int Number of columns in the array. rows : int Number of rows in the array. spacing : array-like[2] of int or float Distanc... | aa7fb0d33ee888a3fa9e865fd8796d8c6ce73db1 | <|skeleton|>
class CellArray:
"""Multiple references to an existing cell in an array format. Args: device : Component The referenced Component. columns : int Number of columns in the array. rows : int Number of rows in the array. spacing : array-like[2] of int or float Distances between adjacent columns and adjacen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CellArray:
"""Multiple references to an existing cell in an array format. Args: device : Component The referenced Component. columns : int Number of columns in the array. rows : int Number of rows in the array. spacing : array-like[2] of int or float Distances between adjacent columns and adjacent rows. origi... | the_stack_v2_python_sparse | gdsfactory/component_layout.py | JonathanCauchon/gdsfactory | train | 0 |
b88a2f61695b55b2a75b5e08c71a5b89677b0385 | [
"if subject:\n self.subject = subject\nreturn super().is_active(request)",
"try:\n return self.is_active_for_user(self.subject)\nexcept AttributeError:\n return self.is_active_for_user(request.user)"
] | <|body_start_0|>
if subject:
self.subject = subject
return super().is_active(request)
<|end_body_0|>
<|body_start_1|>
try:
return self.is_active_for_user(self.subject)
except AttributeError:
return self.is_active_for_user(request.user)
<|end_body_1|>
| Custom Flag model to check if User is subject of a feature. Waffle's standard Flag is designed to check a request's User, not any other User. We want to support User-related feature control outside requests. A related thread suggested using fake requests; this might still be necessary as this customization hasn't remov... | FeatureFlag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureFlag:
"""Custom Flag model to check if User is subject of a feature. Waffle's standard Flag is designed to check a request's User, not any other User. We want to support User-related feature control outside requests. A related thread suggested using fake requests; this might still be neces... | stack_v2_sparse_classes_36k_train_017168 | 10,351 | permissive | [
{
"docstring": "Check if flag is active. Stores subject User if provided.",
"name": "is_active",
"signature": "def is_active(self, request, subject=None)"
},
{
"docstring": "Use instance subject for User if set, otherwise request User.",
"name": "_is_active_for_user",
"signature": "def _... | 2 | null | Implement the Python class `FeatureFlag` described below.
Class description:
Custom Flag model to check if User is subject of a feature. Waffle's standard Flag is designed to check a request's User, not any other User. We want to support User-related feature control outside requests. A related thread suggested using f... | Implement the Python class `FeatureFlag` described below.
Class description:
Custom Flag model to check if User is subject of a feature. Waffle's standard Flag is designed to check a request's User, not any other User. We want to support User-related feature control outside requests. A related thread suggested using f... | a2e3bf3b95d7fcfb2cdffe3a42f86cb6e09674e4 | <|skeleton|>
class FeatureFlag:
"""Custom Flag model to check if User is subject of a feature. Waffle's standard Flag is designed to check a request's User, not any other User. We want to support User-related feature control outside requests. A related thread suggested using fake requests; this might still be neces... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureFlag:
"""Custom Flag model to check if User is subject of a feature. Waffle's standard Flag is designed to check a request's User, not any other User. We want to support User-related feature control outside requests. A related thread suggested using fake requests; this might still be necessary as this ... | the_stack_v2_python_sparse | open_humans/models.py | madprime/open-humans | train | 2 |
493d26bfc4332a1be146beae6d8285858fa1e047 | [
"self._buffer = None\nself._page_size = page_size\nself._search = search",
"if not self._buffer:\n self._buffer = await self._search.fetch(self._page_size) or []\ntry:\n return self._buffer.pop(0)\nexcept IndexError:\n raise StopAsyncIteration"
] | <|body_start_0|>
self._buffer = None
self._page_size = page_size
self._search = search
<|end_body_0|>
<|body_start_1|>
if not self._buffer:
self._buffer = await self._search.fetch(self._page_size) or []
try:
return self._buffer.pop(0)
except Index... | A generic record search async iterator. | IterVCRecordSearch | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IterVCRecordSearch:
"""A generic record search async iterator."""
def __init__(self, search: VCRecordSearch, page_size: int=None):
"""Instantiate a new `IterVCRecordSearch` instance."""
<|body_0|>
async def __anext__(self):
"""Async iterator magic method."""
... | stack_v2_sparse_classes_36k_train_017169 | 4,078 | permissive | [
{
"docstring": "Instantiate a new `IterVCRecordSearch` instance.",
"name": "__init__",
"signature": "def __init__(self, search: VCRecordSearch, page_size: int=None)"
},
{
"docstring": "Async iterator magic method.",
"name": "__anext__",
"signature": "async def __anext__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001381 | Implement the Python class `IterVCRecordSearch` described below.
Class description:
A generic record search async iterator.
Method signatures and docstrings:
- def __init__(self, search: VCRecordSearch, page_size: int=None): Instantiate a new `IterVCRecordSearch` instance.
- async def __anext__(self): Async iterator ... | Implement the Python class `IterVCRecordSearch` described below.
Class description:
A generic record search async iterator.
Method signatures and docstrings:
- def __init__(self, search: VCRecordSearch, page_size: int=None): Instantiate a new `IterVCRecordSearch` instance.
- async def __anext__(self): Async iterator ... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class IterVCRecordSearch:
"""A generic record search async iterator."""
def __init__(self, search: VCRecordSearch, page_size: int=None):
"""Instantiate a new `IterVCRecordSearch` instance."""
<|body_0|>
async def __anext__(self):
"""Async iterator magic method."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IterVCRecordSearch:
"""A generic record search async iterator."""
def __init__(self, search: VCRecordSearch, page_size: int=None):
"""Instantiate a new `IterVCRecordSearch` instance."""
self._buffer = None
self._page_size = page_size
self._search = search
async def __... | the_stack_v2_python_sparse | aries_cloudagent/storage/vc_holder/base.py | hyperledger/aries-cloudagent-python | train | 370 |
2ca896048ca7bd589f7b9e2c6683912333343845 | [
"num_rows = args.get('rows') or 100\nquery = g.db.query(Machine)\nif args['realm'] == 'local':\n query = query.filter(Machine.realm == 'local', Machine.instance_name == args['instance_name'])\nelse:\n query = query.filter(Machine.realm == args['realm'], Machine.instance_name == args['instance_name'], Machine.... | <|body_start_0|>
num_rows = args.get('rows') or 100
query = g.db.query(Machine)
if args['realm'] == 'local':
query = query.filter(Machine.realm == 'local', Machine.instance_name == args['instance_name'])
else:
query = query.filter(Machine.realm == args['realm'], M... | The interface to battle server machines. Each physical machine (for example ec2 instance) has a machine resource here. Each machine resource has zero or more battle server resources. A machine is defined as a set of the parameters for the post call below. If an instance gets a new publicIP address for example, it will ... | MachinesAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MachinesAPI:
"""The interface to battle server machines. Each physical machine (for example ec2 instance) has a machine resource here. Each machine resource has zero or more battle server resources. A machine is defined as a set of the parameters for the post call below. If an instance gets a new... | stack_v2_sparse_classes_36k_train_017170 | 10,491 | permissive | [
{
"docstring": "Get a list of machines",
"name": "get",
"signature": "def get(self, args)"
},
{
"docstring": "Register a machine",
"name": "post",
"signature": "def post(self, args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000588 | Implement the Python class `MachinesAPI` described below.
Class description:
The interface to battle server machines. Each physical machine (for example ec2 instance) has a machine resource here. Each machine resource has zero or more battle server resources. A machine is defined as a set of the parameters for the pos... | Implement the Python class `MachinesAPI` described below.
Class description:
The interface to battle server machines. Each physical machine (for example ec2 instance) has a machine resource here. Each machine resource has zero or more battle server resources. A machine is defined as a set of the parameters for the pos... | 2771bb46db7fd331448f9db3cfb257fab7f89bcc | <|skeleton|>
class MachinesAPI:
"""The interface to battle server machines. Each physical machine (for example ec2 instance) has a machine resource here. Each machine resource has zero or more battle server resources. A machine is defined as a set of the parameters for the post call below. If an instance gets a new... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MachinesAPI:
"""The interface to battle server machines. Each physical machine (for example ec2 instance) has a machine resource here. Each machine resource has zero or more battle server resources. A machine is defined as a set of the parameters for the post call below. If an instance gets a new publicIP add... | the_stack_v2_python_sparse | driftbase/api/machines.py | directivegames/drift-base | train | 1 |
694c6325561a13082dcd8001feb878d7dfc5cd6c | [
"if user_id is None or type(user_id) != str:\n return None\nid = uuid.uuid4()\nid = str(id)\nSessionAuth.user_id_by_session_id[id] = user_id\nreturn id",
"if session_id is None or type(session_id) != str:\n return None\nvalue = SessionAuth.user_id_by_session_id.get(session_id)\nreturn value",
"cookie_valu... | <|body_start_0|>
if user_id is None or type(user_id) != str:
return None
id = uuid.uuid4()
id = str(id)
SessionAuth.user_id_by_session_id[id] = user_id
return id
<|end_body_0|>
<|body_start_1|>
if session_id is None or type(session_id) != str:
ret... | SessionAuth subclass | SessionAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionAuth:
"""SessionAuth subclass"""
def create_session(self, user_id: str=None) -> str:
"""Create session method"""
<|body_0|>
def user_id_for_session_id(self, session_id: str=None) -> str:
"""User id method"""
<|body_1|>
def current_user(self, r... | stack_v2_sparse_classes_36k_train_017171 | 1,634 | no_license | [
{
"docstring": "Create session method",
"name": "create_session",
"signature": "def create_session(self, user_id: str=None) -> str"
},
{
"docstring": "User id method",
"name": "user_id_for_session_id",
"signature": "def user_id_for_session_id(self, session_id: str=None) -> str"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_019595 | Implement the Python class `SessionAuth` described below.
Class description:
SessionAuth subclass
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: Create session method
- def user_id_for_session_id(self, session_id: str=None) -> str: User id method
- def current_user(self, reque... | Implement the Python class `SessionAuth` described below.
Class description:
SessionAuth subclass
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: Create session method
- def user_id_for_session_id(self, session_id: str=None) -> str: User id method
- def current_user(self, reque... | 014fc078421a2daca65322c51b367a936fa8e20a | <|skeleton|>
class SessionAuth:
"""SessionAuth subclass"""
def create_session(self, user_id: str=None) -> str:
"""Create session method"""
<|body_0|>
def user_id_for_session_id(self, session_id: str=None) -> str:
"""User id method"""
<|body_1|>
def current_user(self, r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionAuth:
"""SessionAuth subclass"""
def create_session(self, user_id: str=None) -> str:
"""Create session method"""
if user_id is None or type(user_id) != str:
return None
id = uuid.uuid4()
id = str(id)
SessionAuth.user_id_by_session_id[id] = user_i... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_auth.py | Nicolanz/holbertonschool-web_back_end | train | 0 |
09108311ac2bdb88b0447bf3bee91a5ed03f0a3c | [
"if uid == 0:\n user = User_Info.objects.get(email=request.session.get('login'))\nelse:\n user = User_Info.objects.filter(id=uid)\n if not user.exists():\n return JsonResponse({'status': False, 'err': '用户不存在'}, status=404)\n user = user[0]\narticles = Article.objects.filter(author=user)\nmarkets ... | <|body_start_0|>
if uid == 0:
user = User_Info.objects.get(email=request.session.get('login'))
else:
user = User_Info.objects.filter(id=uid)
if not user.exists():
return JsonResponse({'status': False, 'err': '用户不存在'}, status=404)
user = use... | UserDashBoardView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDashBoardView:
def get(self, request, uid=0):
"""用户控制台 :param request: :return:"""
<|body_0|>
def put(self, request):
"""用户修改信息 :param request: :return:"""
<|body_1|>
def post(self, request):
"""新增/更换头像 :param request: :return:"""
<|b... | stack_v2_sparse_classes_36k_train_017172 | 5,399 | no_license | [
{
"docstring": "用户控制台 :param request: :return:",
"name": "get",
"signature": "def get(self, request, uid=0)"
},
{
"docstring": "用户修改信息 :param request: :return:",
"name": "put",
"signature": "def put(self, request)"
},
{
"docstring": "新增/更换头像 :param request: :return:",
"name":... | 3 | stack_v2_sparse_classes_30k_train_004220 | Implement the Python class `UserDashBoardView` described below.
Class description:
Implement the UserDashBoardView class.
Method signatures and docstrings:
- def get(self, request, uid=0): 用户控制台 :param request: :return:
- def put(self, request): 用户修改信息 :param request: :return:
- def post(self, request): 新增/更换头像 :para... | Implement the Python class `UserDashBoardView` described below.
Class description:
Implement the UserDashBoardView class.
Method signatures and docstrings:
- def get(self, request, uid=0): 用户控制台 :param request: :return:
- def put(self, request): 用户修改信息 :param request: :return:
- def post(self, request): 新增/更换头像 :para... | 526dea540048fc92260bce611c520c50af744e0b | <|skeleton|>
class UserDashBoardView:
def get(self, request, uid=0):
"""用户控制台 :param request: :return:"""
<|body_0|>
def put(self, request):
"""用户修改信息 :param request: :return:"""
<|body_1|>
def post(self, request):
"""新增/更换头像 :param request: :return:"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserDashBoardView:
def get(self, request, uid=0):
"""用户控制台 :param request: :return:"""
if uid == 0:
user = User_Info.objects.get(email=request.session.get('login'))
else:
user = User_Info.objects.filter(id=uid)
if not user.exists():
r... | the_stack_v2_python_sparse | apps/account/views/userInfo/userInfo.py | DICKQI/ALGYunXS | train | 0 | |
4d6b4b4031852fe1080435e31f790f5523a8d35e | [
"k = k % len(nums)\nmove = len(nums) - k\nfor i in range(move):\n n = nums.pop(0)\n nums.append(n)",
"k = k % len(nums)\nfor i in range(k):\n d = nums.pop(len(nums) - 1)\n nums.insert(0, d)",
"k = k % len(nums)\nnums[:] = nums[::-1]\nnums[:k] = nums[:k][::-1]\nnums[k:] = nums[k:][::-1]"
] | <|body_start_0|>
k = k % len(nums)
move = len(nums) - k
for i in range(move):
n = nums.pop(0)
nums.append(n)
<|end_body_0|>
<|body_start_1|>
k = k % len(nums)
for i in range(k):
d = nums.pop(len(nums) - 1)
nums.insert(0, d)
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotateV2(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_017173 | 891 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums: List[int], k: int) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "rotateV2",
"signature": "def rotateV2(self, nums:... | 3 | stack_v2_sparse_classes_30k_train_017927 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead.
- def rotateV2(self, nums: List[int], k: int) -> None: Do not return anyt... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead.
- def rotateV2(self, nums: List[int], k: int) -> None: Do not return anyt... | 266def94df8245f90ea5b6885fc472470b189e51 | <|skeleton|>
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotateV2(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
k = k % len(nums)
move = len(nums) - k
for i in range(move):
n = nums.pop(0)
nums.append(n)
def rotateV2(self, nums: List[int], ... | the_stack_v2_python_sparse | 189_Rotate_Array.py | GuangyuZheng/leet_code_python | train | 2 | |
d8563700a3a3f692b6d2de0ba6bebd2735787b42 | [
"max_heap = []\nitem_dict = {}\nresult = []\nfor i in range(len(nums)):\n item = [-nums[i], False]\n heapq.heappush(max_heap, item)\n if nums[i] not in item_dict:\n item_dict[nums[i]] = [item]\n else:\n item_dict[nums[i]].append(item)\n if i - k >= 0:\n item_to_remove = nums[i - ... | <|body_start_0|>
max_heap = []
item_dict = {}
result = []
for i in range(len(nums)):
item = [-nums[i], False]
heapq.heappush(max_heap, item)
if nums[i] not in item_dict:
item_dict[nums[i]] = [item]
else:
item... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
"""O(NlogN) solution, using tombstone marker without poping from heap please note that heapq support pushing list of item, first item in list will be used for comparison :param nums: :param k: :return:"""
... | stack_v2_sparse_classes_36k_train_017174 | 2,264 | no_license | [
{
"docstring": "O(NlogN) solution, using tombstone marker without poping from heap please note that heapq support pushing list of item, first item in list will be used for comparison :param nums: :param k: :return:",
"name": "maxSlidingWindow",
"signature": "def maxSlidingWindow(self, nums: List[int], k... | 2 | stack_v2_sparse_classes_30k_train_003145 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: O(NlogN) solution, using tombstone marker without poping from heap please note that heapq support pushing list o... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: O(NlogN) solution, using tombstone marker without poping from heap please note that heapq support pushing list o... | 46bd8d1b44cb19aa773cc072cc9be97e9a0e348d | <|skeleton|>
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
"""O(NlogN) solution, using tombstone marker without poping from heap please note that heapq support pushing list of item, first item in list will be used for comparison :param nums: :param k: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
"""O(NlogN) solution, using tombstone marker without poping from heap please note that heapq support pushing list of item, first item in list will be used for comparison :param nums: :param k: :return:"""
max_heap = []... | the_stack_v2_python_sparse | src/python/data_structure/heap/239_sliding_window_maximum.py | alannesta/algo4 | train | 0 | |
965bcf457c6d6c424f9bd74f8b96fc491108547e | [
"pathmap = PathMap.query.filter_by(id=pathmap_id).first()\nif not pathmap:\n return (jsonify(error='No pathmap with that id'), NOT_FOUND)\nout = pathmap.to_dict(unpack_relationships=False)\nif pathmap.tag:\n out['tag'] = pathmap.tag.tag\ndel out['tag_id']\nreturn (jsonify(out), OK)",
"pathmap = PathMap.quer... | <|body_start_0|>
pathmap = PathMap.query.filter_by(id=pathmap_id).first()
if not pathmap:
return (jsonify(error='No pathmap with that id'), NOT_FOUND)
out = pathmap.to_dict(unpack_relationships=False)
if pathmap.tag:
out['tag'] = pathmap.tag.tag
del out['t... | SinglePathMapAPI | [
"BSD-3-Clause",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SinglePathMapAPI:
def get(self, pathmap_id):
"""A ``GET`` to this endpoint will return a single path map specified by pathmap_id .. http:get:: /api/v1/pathmaps/<int:pathmap_id> HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/pathmaps/1 HTTP/1.1 Accept: application/json **Response**... | stack_v2_sparse_classes_36k_train_017175 | 11,366 | permissive | [
{
"docstring": "A ``GET`` to this endpoint will return a single path map specified by pathmap_id .. http:get:: /api/v1/pathmaps/<int:pathmap_id> HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/pathmaps/1 HTTP/1.1 Accept: application/json **Response** .. sourcecode:: http HTTP/1.1 200 OK Content-Type: appl... | 3 | stack_v2_sparse_classes_30k_train_017017 | Implement the Python class `SinglePathMapAPI` described below.
Class description:
Implement the SinglePathMapAPI class.
Method signatures and docstrings:
- def get(self, pathmap_id): A ``GET`` to this endpoint will return a single path map specified by pathmap_id .. http:get:: /api/v1/pathmaps/<int:pathmap_id> HTTP/1... | Implement the Python class `SinglePathMapAPI` described below.
Class description:
Implement the SinglePathMapAPI class.
Method signatures and docstrings:
- def get(self, pathmap_id): A ``GET`` to this endpoint will return a single path map specified by pathmap_id .. http:get:: /api/v1/pathmaps/<int:pathmap_id> HTTP/1... | ea04bbcb807eb669415c569417b4b1b68e75d29d | <|skeleton|>
class SinglePathMapAPI:
def get(self, pathmap_id):
"""A ``GET`` to this endpoint will return a single path map specified by pathmap_id .. http:get:: /api/v1/pathmaps/<int:pathmap_id> HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/pathmaps/1 HTTP/1.1 Accept: application/json **Response**... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SinglePathMapAPI:
def get(self, pathmap_id):
"""A ``GET`` to this endpoint will return a single path map specified by pathmap_id .. http:get:: /api/v1/pathmaps/<int:pathmap_id> HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/pathmaps/1 HTTP/1.1 Accept: application/json **Response** .. sourcecode... | the_stack_v2_python_sparse | pyfarm/master/api/pathmaps.py | pyfarm/pyfarm-master | train | 2 | |
28755fbf8da5168fea25a028cfe6f0efbf85d26f | [
"self.means = means\nself.sigmas = sigmas\nself.weights = weights",
"def normpdf(x, mu, sigma):\n \"\"\"\n The pdf of the normal distribution\n :param x: quantile on which to sample the density function\n :param mu: scalar vector of mean of each of the Gaussians\n :p... | <|body_start_0|>
self.means = means
self.sigmas = sigmas
self.weights = weights
<|end_body_0|>
<|body_start_1|>
def normpdf(x, mu, sigma):
"""
The pdf of the normal distribution
:param x: quantile on which to sample the density functio... | DataDistribution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataDistribution:
def __init__(self, means, sigmas, weights):
"""Initialize class variables :param means: vector of means of dimension d for each distribution in mixture :param sigmas: vector of variances of dimension d for each distribution in mixture :param weights: vector of weights o... | stack_v2_sparse_classes_36k_train_017176 | 4,355 | no_license | [
{
"docstring": "Initialize class variables :param means: vector of means of dimension d for each distribution in mixture :param sigmas: vector of variances of dimension d for each distribution in mixture :param weights: vector of weights of dimension d for each distribution in mixture",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_001519 | Implement the Python class `DataDistribution` described below.
Class description:
Implement the DataDistribution class.
Method signatures and docstrings:
- def __init__(self, means, sigmas, weights): Initialize class variables :param means: vector of means of dimension d for each distribution in mixture :param sigmas... | Implement the Python class `DataDistribution` described below.
Class description:
Implement the DataDistribution class.
Method signatures and docstrings:
- def __init__(self, means, sigmas, weights): Initialize class variables :param means: vector of means of dimension d for each distribution in mixture :param sigmas... | cf9d7b4a1fa561beb5f32f97022807c04db260bb | <|skeleton|>
class DataDistribution:
def __init__(self, means, sigmas, weights):
"""Initialize class variables :param means: vector of means of dimension d for each distribution in mixture :param sigmas: vector of variances of dimension d for each distribution in mixture :param weights: vector of weights o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataDistribution:
def __init__(self, means, sigmas, weights):
"""Initialize class variables :param means: vector of means of dimension d for each distribution in mixture :param sigmas: vector of variances of dimension d for each distribution in mixture :param weights: vector of weights of dimension d ... | the_stack_v2_python_sparse | Python/AQM/gaus-mark.py | menquist/Michael_Enquist | train | 4 | |
32a4e3304ba9c207642f37aad96e1f4fdf2ee3ec | [
"self.jwt_secret = jwt_secret\nself.jwt_issuer = jwt_issuer\nself.jwt_audiences = jwt_audiences\nself.default_lifespan = default_lifespan\nreturn",
"if lifespan is None:\n lifespan = self.default_lifespan\nprint('TokenAgent.create_for_user: ' + str(user.to_jdata()))\ntoken_payload = create_user_payload_now(use... | <|body_start_0|>
self.jwt_secret = jwt_secret
self.jwt_issuer = jwt_issuer
self.jwt_audiences = jwt_audiences
self.default_lifespan = default_lifespan
return
<|end_body_0|>
<|body_start_1|>
if lifespan is None:
lifespan = self.default_lifespan
print('... | Class that creates JWT tokens for users. | TokenAgent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenAgent:
"""Class that creates JWT tokens for users."""
def __init__(self, jwt_secret, jwt_issuer, jwt_audiences, default_lifespan=None):
"""Initializes self. Args: jwt_secret (str): The symmetric secret for signing tokens. jwt_issuer (str): The issuer string to use ("who issued t... | stack_v2_sparse_classes_36k_train_017177 | 6,662 | permissive | [
{
"docstring": "Initializes self. Args: jwt_secret (str): The symmetric secret for signing tokens. jwt_issuer (str): The issuer string to use (\"who issued this token?\"). jwt_audiences (List[str]): The audiences list to use (\"who should accept this token?\"). default_lifespan(datetime.timedelta): if no lifesp... | 4 | null | Implement the Python class `TokenAgent` described below.
Class description:
Class that creates JWT tokens for users.
Method signatures and docstrings:
- def __init__(self, jwt_secret, jwt_issuer, jwt_audiences, default_lifespan=None): Initializes self. Args: jwt_secret (str): The symmetric secret for signing tokens. ... | Implement the Python class `TokenAgent` described below.
Class description:
Class that creates JWT tokens for users.
Method signatures and docstrings:
- def __init__(self, jwt_secret, jwt_issuer, jwt_audiences, default_lifespan=None): Initializes self. Args: jwt_secret (str): The symmetric secret for signing tokens. ... | 947af72a51c99096ddcce3c3c71bef8a144a17bb | <|skeleton|>
class TokenAgent:
"""Class that creates JWT tokens for users."""
def __init__(self, jwt_secret, jwt_issuer, jwt_audiences, default_lifespan=None):
"""Initializes self. Args: jwt_secret (str): The symmetric secret for signing tokens. jwt_issuer (str): The issuer string to use ("who issued t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenAgent:
"""Class that creates JWT tokens for users."""
def __init__(self, jwt_secret, jwt_issuer, jwt_audiences, default_lifespan=None):
"""Initializes self. Args: jwt_secret (str): The symmetric secret for signing tokens. jwt_issuer (str): The issuer string to use ("who issued this token?").... | the_stack_v2_python_sparse | nest_py/core/flask/accounts/token.py | bodom0015/platform | train | 0 |
a9c3ba960690756f88d22e81291e4d283be26e16 | [
"self.lr = lr\nself.b1 = b1\nself.b2 = b2\nself.num_params = num_params\nself.counter = 0\nself.momentum = [0 for _ in range(num_params)]\nself.velocity = [0 for _ in range(num_params)]",
"self.counter += 1\nepsilon = 1e-08\nnew_params = []\nfor i in range(self.num_params):\n self.momentum[i] = self.b1 * self.... | <|body_start_0|>
self.lr = lr
self.b1 = b1
self.b2 = b2
self.num_params = num_params
self.counter = 0
self.momentum = [0 for _ in range(num_params)]
self.velocity = [0 for _ in range(num_params)]
<|end_body_0|>
<|body_start_1|>
self.counter += 1
e... | Adamax | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Adamax:
def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.99):
"""Initializer for Adamax optimizer Inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 b1 : The ex... | stack_v2_sparse_classes_36k_train_017178 | 10,861 | no_license | [
{
"docstring": "Initializer for Adamax optimizer Inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 b1 : The exponential decay rate for the first moment(integer/float), default is 0.9 b2 : Th... | 2 | stack_v2_sparse_classes_30k_train_014046 | Implement the Python class `Adamax` described below.
Class description:
Implement the Adamax class.
Method signatures and docstrings:
- def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.99): Initializer for Adamax optimizer Inputs: num params: number of parameters which are ought to be passed lr: The learning r... | Implement the Python class `Adamax` described below.
Class description:
Implement the Adamax class.
Method signatures and docstrings:
- def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.99): Initializer for Adamax optimizer Inputs: num params: number of parameters which are ought to be passed lr: The learning r... | 9406b21aef9b2d94091d570e809f88a752277e30 | <|skeleton|>
class Adamax:
def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.99):
"""Initializer for Adamax optimizer Inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 b1 : The ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Adamax:
def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.99):
"""Initializer for Adamax optimizer Inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 b1 : The exponential deca... | the_stack_v2_python_sparse | optimizers.py | viswambhar-yasa/AuToDiFf | train | 0 | |
c62d9e8a0be736fd0678937837522b59f51a32e6 | [
"py_typecheck.check_callable(executor_stack_fn)\nself._executor_stack_fn = executor_stack_fn\nself._executors = {}",
"py_typecheck.check_type(cardinalities, dict)\nkey = _get_hashable_key(cardinalities)\nex = self._executors.get(key)\nif ex is not None:\n return ex\nex = self._executor_stack_fn(cardinalities)\... | <|body_start_0|>
py_typecheck.check_callable(executor_stack_fn)
self._executor_stack_fn = executor_stack_fn
self._executors = {}
<|end_body_0|>
<|body_start_1|>
py_typecheck.check_type(cardinalities, dict)
key = _get_hashable_key(cardinalities)
ex = self._executors.get(k... | Implementation of executor factory holding an executor per cardinality. | ExecutorFactoryImpl | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecutorFactoryImpl:
"""Implementation of executor factory holding an executor per cardinality."""
def __init__(self, executor_stack_fn: Callable[[CardinalitiesType], executor_base.Executor]):
"""Initializes `ExecutorFactoryImpl`. Args: executor_stack_fn: Callable taking a mapping fr... | stack_v2_sparse_classes_36k_train_017179 | 9,860 | permissive | [
{
"docstring": "Initializes `ExecutorFactoryImpl`. Args: executor_stack_fn: Callable taking a mapping from `placement_literals.PlacementLiteral` to integers, and returning an `executor_base.Executor`. The returned executor will be configured to handle these cardinalities.",
"name": "__init__",
"signatur... | 3 | null | Implement the Python class `ExecutorFactoryImpl` described below.
Class description:
Implementation of executor factory holding an executor per cardinality.
Method signatures and docstrings:
- def __init__(self, executor_stack_fn: Callable[[CardinalitiesType], executor_base.Executor]): Initializes `ExecutorFactoryImp... | Implement the Python class `ExecutorFactoryImpl` described below.
Class description:
Implementation of executor factory holding an executor per cardinality.
Method signatures and docstrings:
- def __init__(self, executor_stack_fn: Callable[[CardinalitiesType], executor_base.Executor]): Initializes `ExecutorFactoryImp... | 7797df103bf965a9d0cd70e20ae61066650382d9 | <|skeleton|>
class ExecutorFactoryImpl:
"""Implementation of executor factory holding an executor per cardinality."""
def __init__(self, executor_stack_fn: Callable[[CardinalitiesType], executor_base.Executor]):
"""Initializes `ExecutorFactoryImpl`. Args: executor_stack_fn: Callable taking a mapping fr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExecutorFactoryImpl:
"""Implementation of executor factory holding an executor per cardinality."""
def __init__(self, executor_stack_fn: Callable[[CardinalitiesType], executor_base.Executor]):
"""Initializes `ExecutorFactoryImpl`. Args: executor_stack_fn: Callable taking a mapping from `placement... | the_stack_v2_python_sparse | tensorflow_federated/python/core/impl/executors/executor_factory.py | tf-encrypted/federated | train | 1 |
47bb8aa05bf73b791bb98ecf170221d9f5307c1b | [
"config_files = [config_filepath] if config_filepath else []\nconfig_files.extend(['.amaas.cfg', os.path.expanduser(os.path.join('~', '.amaas.cfg')), os.path.join('', 'etc', 'amaas.cfg')])\nparser = ConfigParser()\nparser.read(config_files)\nself.file_config = parser",
"value = os.environ.get('AMAAS_{}'.format(na... | <|body_start_0|>
config_files = [config_filepath] if config_filepath else []
config_files.extend(['.amaas.cfg', os.path.expanduser(os.path.join('~', '.amaas.cfg')), os.path.join('', 'etc', 'amaas.cfg')])
parser = ConfigParser()
parser.read(config_files)
self.file_config = parser
... | Factory for building config object. | ConfigFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFactory:
"""Factory for building config object."""
def __init__(self, config_filepath=None):
"""Create new config factory."""
<|body_0|>
def lookup(self, section, name):
"""Lookup config value."""
<|body_1|>
def api_config(self, stage=None):
... | stack_v2_sparse_classes_36k_train_017180 | 5,444 | permissive | [
{
"docstring": "Create new config factory.",
"name": "__init__",
"signature": "def __init__(self, config_filepath=None)"
},
{
"docstring": "Lookup config value.",
"name": "lookup",
"signature": "def lookup(self, section, name)"
},
{
"docstring": "Create api config based on stage.... | 4 | stack_v2_sparse_classes_30k_train_016134 | Implement the Python class `ConfigFactory` described below.
Class description:
Factory for building config object.
Method signatures and docstrings:
- def __init__(self, config_filepath=None): Create new config factory.
- def lookup(self, section, name): Lookup config value.
- def api_config(self, stage=None): Create... | Implement the Python class `ConfigFactory` described below.
Class description:
Factory for building config object.
Method signatures and docstrings:
- def __init__(self, config_filepath=None): Create new config factory.
- def lookup(self, section, name): Lookup config value.
- def api_config(self, stage=None): Create... | bd77884de6e5ab05d864638addeb4bb338a51183 | <|skeleton|>
class ConfigFactory:
"""Factory for building config object."""
def __init__(self, config_filepath=None):
"""Create new config factory."""
<|body_0|>
def lookup(self, section, name):
"""Lookup config value."""
<|body_1|>
def api_config(self, stage=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigFactory:
"""Factory for building config object."""
def __init__(self, config_filepath=None):
"""Create new config factory."""
config_files = [config_filepath] if config_filepath else []
config_files.extend(['.amaas.cfg', os.path.expanduser(os.path.join('~', '.amaas.cfg')), o... | the_stack_v2_python_sparse | amaascore/config.py | amaas-fintech/amaas-core-sdk-python | train | 0 |
8b01bd68dd6920ffa002e805848834898176c3f6 | [
"Path(log_file_path).mkdir(parents=True, exist_ok=True)\nlog_filename = Path(log_file_path, 'dbt_sugar_log.log')\nlogger = logging.getLogger('dbt-sugar logger')\nlogger.setLevel(logging.DEBUG)\nf_handler = logging.FileHandler(log_filename)\nf_handler.setLevel(logging.DEBUG)\nf_format = logging.Formatter('%(asctime)... | <|body_start_0|>
Path(log_file_path).mkdir(parents=True, exist_ok=True)
log_filename = Path(log_file_path, 'dbt_sugar_log.log')
logger = logging.getLogger('dbt-sugar logger')
logger.setLevel(logging.DEBUG)
f_handler = logging.FileHandler(log_filename)
f_handler.setLevel(l... | Manages the logs formats and levels. We have 2 loggers one to stout and one to a logger file. General logger level is DEBUG and each handler is set dynamically based on log-level CLI args | LogManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogManager:
"""Manages the logs formats and levels. We have 2 loggers one to stout and one to a logger file. General logger level is DEBUG and each handler is set dynamically based on log-level CLI args"""
def __init__(self, log_file_path: Path=Path(Path.cwd(), 'dbt_sugar_logs'), log_to_cons... | stack_v2_sparse_classes_36k_train_017181 | 2,698 | permissive | [
{
"docstring": "Log manager constructor. can take and override log path + whether to stout or not. Args: log_file_path (Path, optional): Custom path to logger file. Defaults to Path(Path.cwd(), \"dbt_sugar_log\"). log_to_console (bool, optional): When true logs will also be pushed into stout. Defaults to True."... | 2 | stack_v2_sparse_classes_30k_train_019906 | Implement the Python class `LogManager` described below.
Class description:
Manages the logs formats and levels. We have 2 loggers one to stout and one to a logger file. General logger level is DEBUG and each handler is set dynamically based on log-level CLI args
Method signatures and docstrings:
- def __init__(self,... | Implement the Python class `LogManager` described below.
Class description:
Manages the logs formats and levels. We have 2 loggers one to stout and one to a logger file. General logger level is DEBUG and each handler is set dynamically based on log-level CLI args
Method signatures and docstrings:
- def __init__(self,... | 1b1c3a193b48cbd3d5002c8ff71fb904c94a9825 | <|skeleton|>
class LogManager:
"""Manages the logs formats and levels. We have 2 loggers one to stout and one to a logger file. General logger level is DEBUG and each handler is set dynamically based on log-level CLI args"""
def __init__(self, log_file_path: Path=Path(Path.cwd(), 'dbt_sugar_logs'), log_to_cons... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogManager:
"""Manages the logs formats and levels. We have 2 loggers one to stout and one to a logger file. General logger level is DEBUG and each handler is set dynamically based on log-level CLI args"""
def __init__(self, log_file_path: Path=Path(Path.cwd(), 'dbt_sugar_logs'), log_to_console: bool=Tru... | the_stack_v2_python_sparse | dbt_sugar/core/logger.py | z3z1ma/dbt-sugar | train | 1 |
1b0f74feca4f6fe4f71e4405f11880a178f4e31c | [
"query = full_query = self.db.query(orm.Group)\nsub_scope = self.parsed_scopes['list:groups']\nif sub_scope != Scope.ALL:\n if not set(sub_scope).issubset({'group'}):\n self.log.warning(f'Invalid filter on list:group for {self.current_user}: {sub_scope}')\n raise web.HTTPError(403)\n query = que... | <|body_start_0|>
query = full_query = self.db.query(orm.Group)
sub_scope = self.parsed_scopes['list:groups']
if sub_scope != Scope.ALL:
if not set(sub_scope).issubset({'group'}):
self.log.warning(f'Invalid filter on list:group for {self.current_user}: {sub_scope}')
... | GroupListAPIHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupListAPIHandler:
def get(self):
"""List groups"""
<|body_0|>
async def post(self):
"""POST creates Multiple groups"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
query = full_query = self.db.query(orm.Group)
sub_scope = self.parsed_scop... | stack_v2_sparse_classes_36k_train_017182 | 8,154 | permissive | [
{
"docstring": "List groups",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "POST creates Multiple groups",
"name": "post",
"signature": "async def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011058 | Implement the Python class `GroupListAPIHandler` described below.
Class description:
Implement the GroupListAPIHandler class.
Method signatures and docstrings:
- def get(self): List groups
- async def post(self): POST creates Multiple groups | Implement the Python class `GroupListAPIHandler` described below.
Class description:
Implement the GroupListAPIHandler class.
Method signatures and docstrings:
- def get(self): List groups
- async def post(self): POST creates Multiple groups
<|skeleton|>
class GroupListAPIHandler:
def get(self):
"""List... | 7757dea8a463e75d8a540e85deee45c1635dd273 | <|skeleton|>
class GroupListAPIHandler:
def get(self):
"""List groups"""
<|body_0|>
async def post(self):
"""POST creates Multiple groups"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupListAPIHandler:
def get(self):
"""List groups"""
query = full_query = self.db.query(orm.Group)
sub_scope = self.parsed_scopes['list:groups']
if sub_scope != Scope.ALL:
if not set(sub_scope).issubset({'group'}):
self.log.warning(f'Invalid filter ... | the_stack_v2_python_sparse | jupyterhub/apihandlers/groups.py | jupyterhub/jupyterhub | train | 6,751 | |
55f6ed61a37b05e2fff1983015f12edc3e766994 | [
"parser = ArgumentParser(prog=self._canonical_alias, description=type(self).__doc__, formatter_class=help_formatter)\nfor arg in copy.deepcopy(type(self).arguments):\n if 'action' in arg:\n raise TypeError('arguments may not specify an action')\n arg['action'] = self._make_argument_action(arg['type'], ... | <|body_start_0|>
parser = ArgumentParser(prog=self._canonical_alias, description=type(self).__doc__, formatter_class=help_formatter)
for arg in copy.deepcopy(type(self).arguments):
if 'action' in arg:
raise TypeError('arguments may not specify an action')
arg['act... | ParsingMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParsingMixin:
def get_parser(self):
"""Returns the argument parser for this command."""
<|body_0|>
def _make_argument_action(self, type, permission_level):
"""Constructs and returns an argparse action. The action first validates the arguments' usage against the permi... | stack_v2_sparse_classes_36k_train_017183 | 6,997 | permissive | [
{
"docstring": "Returns the argument parser for this command.",
"name": "get_parser",
"signature": "def get_parser(self)"
},
{
"docstring": "Constructs and returns an argparse action. The action first validates the arguments' usage against the permission checker and then stores the arguments int... | 2 | null | Implement the Python class `ParsingMixin` described below.
Class description:
Implement the ParsingMixin class.
Method signatures and docstrings:
- def get_parser(self): Returns the argument parser for this command.
- def _make_argument_action(self, type, permission_level): Constructs and returns an argparse action. ... | Implement the Python class `ParsingMixin` described below.
Class description:
Implement the ParsingMixin class.
Method signatures and docstrings:
- def get_parser(self): Returns the argument parser for this command.
- def _make_argument_action(self, type, permission_level): Constructs and returns an argparse action. ... | 892d39a4e37d3bd4dae8de7469ddaf03b5537f43 | <|skeleton|>
class ParsingMixin:
def get_parser(self):
"""Returns the argument parser for this command."""
<|body_0|>
def _make_argument_action(self, type, permission_level):
"""Constructs and returns an argparse action. The action first validates the arguments' usage against the permi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParsingMixin:
def get_parser(self):
"""Returns the argument parser for this command."""
parser = ArgumentParser(prog=self._canonical_alias, description=type(self).__doc__, formatter_class=help_formatter)
for arg in copy.deepcopy(type(self).arguments):
if 'action' in arg:
... | the_stack_v2_python_sparse | tars/helpers/basecommand/parsing.py | rossjrw/tars | train | 1 | |
318b2e93ae4383e9492397a8596f33a0287dfee9 | [
"sum = 0\nif not root:\n return 0\nif root.left and (not root.left.left) and (not root.left.right):\n sum += root.left.val\nsum += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)\nreturn sum",
"res = 0\nif not root:\n return res\nstack = [root]\nwhile stack:\n node = stack.pop(0)\n ... | <|body_start_0|>
sum = 0
if not root:
return 0
if root.left and (not root.left.left) and (not root.left.right):
sum += root.left.val
sum += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
return sum
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumOfLeftLeaves2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sum = 0
if not root:
... | stack_v2_sparse_classes_36k_train_017184 | 1,046 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumOfLeftLeaves",
"signature": "def sumOfLeftLeaves(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumOfLeftLeaves2",
"signature": "def sumOfLeftLeaves2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012020 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfLeftLeaves(self, root): :type root: TreeNode :rtype: int
- def sumOfLeftLeaves2(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfLeftLeaves(self, root): :type root: TreeNode :rtype: int
- def sumOfLeftLeaves2(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def sumO... | 88a822c48ef50187507d0f75ce65ecc39e849839 | <|skeleton|>
class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumOfLeftLeaves2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
sum = 0
if not root:
return 0
if root.left and (not root.left.left) and (not root.left.right):
sum += root.left.val
sum += self.sumOfLeftLeaves(root.left) + self.su... | the_stack_v2_python_sparse | bwu/binary_tree/404-sum-of-left-leaves.py | captainhcg/leetcode-in-py-and-go | train | 1 | |
4a40063f32e9df7433c4dcb16dccf1cac2088b2b | [
"reg_grad = None\nloss_grad = None\nN = np.shape(self.x)[0]\ngrad_sum = np.zeros((1, self.ndims + 1))\nfor i in range(N):\n wTx = np.matmul([self.x[i]], self.w)\n hinge = y[i] * wTx\n if hinge < 1:\n grad_sum = grad_sum - y[i] * self.x[i]\nreg_grad = np.transpose(grad_sum)\nloss_grad = self.w_decay_... | <|body_start_0|>
reg_grad = None
loss_grad = None
N = np.shape(self.x)[0]
grad_sum = np.zeros((1, self.ndims + 1))
for i in range(N):
wTx = np.matmul([self.x[i]], self.w)
hinge = y[i] * wTx
if hinge < 1:
grad_sum = grad_sum - y[... | Implements a linear regression mode model | SupportVectorMachine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupportVectorMachine:
"""Implements a linear regression mode model"""
def backward(self, f, y):
"""Performs the backward operation based on the loss in total_loss. By backward operation, it means to compute the gradient of the loss w.r.t w. Hint: You may need to use self.x, and you m... | stack_v2_sparse_classes_36k_train_017185 | 3,683 | no_license | [
{
"docstring": "Performs the backward operation based on the loss in total_loss. By backward operation, it means to compute the gradient of the loss w.r.t w. Hint: You may need to use self.x, and you made need to change the forward operation. Args: f(numpy.ndarray): Output of forward operation, dimension (N,1).... | 3 | stack_v2_sparse_classes_30k_train_001404 | Implement the Python class `SupportVectorMachine` described below.
Class description:
Implements a linear regression mode model
Method signatures and docstrings:
- def backward(self, f, y): Performs the backward operation based on the loss in total_loss. By backward operation, it means to compute the gradient of the ... | Implement the Python class `SupportVectorMachine` described below.
Class description:
Implements a linear regression mode model
Method signatures and docstrings:
- def backward(self, f, y): Performs the backward operation based on the loss in total_loss. By backward operation, it means to compute the gradient of the ... | b825789e27260139c2d1e7a8ef8299ded2fde9d7 | <|skeleton|>
class SupportVectorMachine:
"""Implements a linear regression mode model"""
def backward(self, f, y):
"""Performs the backward operation based on the loss in total_loss. By backward operation, it means to compute the gradient of the loss w.r.t w. Hint: You may need to use self.x, and you m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SupportVectorMachine:
"""Implements a linear regression mode model"""
def backward(self, f, y):
"""Performs the backward operation based on the loss in total_loss. By backward operation, it means to compute the gradient of the loss w.r.t w. Hint: You may need to use self.x, and you made need to c... | the_stack_v2_python_sparse | Support_Vector_Machine/models/support_vector_machine.py | gracesc7/Machine-Learning-cs446 | train | 1 |
943f5c3b00fe9584a6e9a24d7d44644ba8e0b603 | [
"self.d = defaultdict(list)\nfor i, word in enumerate(words):\n self.d[word] += (i,)",
"d = self.d\nindexes1, indexes2 = (d[word1], d[word2])\ni = j = 0\n_min = float('inf')\nwhile i < len(indexes1) and j < len(indexes2):\n _min = min(_min, abs(indexes1[i] - indexes2[j]))\n if indexes1[i] < indexes2[j]:\... | <|body_start_0|>
self.d = defaultdict(list)
for i, word in enumerate(words):
self.d[word] += (i,)
<|end_body_0|>
<|body_start_1|>
d = self.d
indexes1, indexes2 = (d[word1], d[word2])
i = j = 0
_min = float('inf')
while i < len(indexes1) and j < len(in... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_017186 | 1,039 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | stack_v2_sparse_classes_30k_train_013344 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | 036a29d681cc91f2317d454e04530d7375d55478 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.d = defaultdict(list)
for i, word in enumerate(words):
self.d[word] += (i,)
def shortest(self, word1, word2):
"""Adds a word into the data structure.... | the_stack_v2_python_sparse | leetcode/shortest_word_distance_ii_v2.py | myliu/python-algorithm | train | 0 | |
6805731d9538ef129ad4c21ca56f4e9d5b34c141 | [
"if isinstance(ids, (int, long)):\n ids = [ids]\nwizard = self.browse(ids)\nactive_model = self._context.get('active_model')\nmsg = '{} has to be called from a \"module_prototyper\" , not a \"{}\"'\nassert active_model == 'module_prototyper', msg.format(self, active_model)\nprototypes = self.env[active_model].br... | <|body_start_0|>
if isinstance(ids, (int, long)):
ids = [ids]
wizard = self.browse(ids)
active_model = self._context.get('active_model')
msg = '{} has to be called from a "module_prototyper" , not a "{}"'
assert active_model == 'module_prototyper', msg.format(self, ac... | PrototypeModuleExport | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrototypeModuleExport:
def action_export(self, ids):
"""Export a zip file containing the module based on the information provided in the prototype, using the templates chosen in the wizard."""
<|body_0|>
def zip_files(wizard, prototypes):
"""Takes a set of file and z... | stack_v2_sparse_classes_36k_train_017187 | 4,764 | no_license | [
{
"docstring": "Export a zip file containing the module based on the information provided in the prototype, using the templates chosen in the wizard.",
"name": "action_export",
"signature": "def action_export(self, ids)"
},
{
"docstring": "Takes a set of file and zips them. :param file_details: ... | 2 | null | Implement the Python class `PrototypeModuleExport` described below.
Class description:
Implement the PrototypeModuleExport class.
Method signatures and docstrings:
- def action_export(self, ids): Export a zip file containing the module based on the information provided in the prototype, using the templates chosen in ... | Implement the Python class `PrototypeModuleExport` described below.
Class description:
Implement the PrototypeModuleExport class.
Method signatures and docstrings:
- def action_export(self, ids): Export a zip file containing the module based on the information provided in the prototype, using the templates chosen in ... | 5a4fd72991c846d5cb7c5082f6bdfef5b2bca572 | <|skeleton|>
class PrototypeModuleExport:
def action_export(self, ids):
"""Export a zip file containing the module based on the information provided in the prototype, using the templates chosen in the wizard."""
<|body_0|>
def zip_files(wizard, prototypes):
"""Takes a set of file and z... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrototypeModuleExport:
def action_export(self, ids):
"""Export a zip file containing the module based on the information provided in the prototype, using the templates chosen in the wizard."""
if isinstance(ids, (int, long)):
ids = [ids]
wizard = self.browse(ids)
ac... | the_stack_v2_python_sparse | yuancloud/extend/emaker/wizard/module_prototyper_module_export.py | cash2one/yuancloud | train | 0 | |
c5ac869aee631ae9977cdf3612f3014421b913dd | [
"try:\n return_data = ''\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n return_data = ''\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_dat... | <|body_start_0|>
try:
return_data = ''
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '404', 'result': str(e)}
return Response(json.dumps(return_data))
<|end_body_0|>
<|body_start_1|>
try:
retu... | ServiceManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceManager:
def post(self, request, nnid):
"""Set configurations for predict service --- # Class Name : ServiceManager # Description: Set configurations for predict service (not implemented yet)"""
<|body_0|>
def get(self, request, nnid):
"""Set configurations fo... | stack_v2_sparse_classes_36k_train_017188 | 2,125 | permissive | [
{
"docstring": "Set configurations for predict service --- # Class Name : ServiceManager # Description: Set configurations for predict service (not implemented yet)",
"name": "post",
"signature": "def post(self, request, nnid)"
},
{
"docstring": "Set configurations for predict service --- # Clas... | 4 | null | Implement the Python class `ServiceManager` described below.
Class description:
Implement the ServiceManager class.
Method signatures and docstrings:
- def post(self, request, nnid): Set configurations for predict service --- # Class Name : ServiceManager # Description: Set configurations for predict service (not imp... | Implement the Python class `ServiceManager` described below.
Class description:
Implement the ServiceManager class.
Method signatures and docstrings:
- def post(self, request, nnid): Set configurations for predict service --- # Class Name : ServiceManager # Description: Set configurations for predict service (not imp... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class ServiceManager:
def post(self, request, nnid):
"""Set configurations for predict service --- # Class Name : ServiceManager # Description: Set configurations for predict service (not implemented yet)"""
<|body_0|>
def get(self, request, nnid):
"""Set configurations fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServiceManager:
def post(self, request, nnid):
"""Set configurations for predict service --- # Class Name : ServiceManager # Description: Set configurations for predict service (not implemented yet)"""
try:
return_data = ''
return Response(json.dumps(return_data))
... | the_stack_v2_python_sparse | api/views/service_manager.py | yurimkoo/tensormsa | train | 1 | |
8ce47345a5b3e9be28aff1618a2ef79edd482e34 | [
"self.config_entry = entry\nself.lametric = LaMetricDevice(host=entry.data[CONF_HOST], api_key=entry.data[CONF_API_KEY], session=async_get_clientsession(hass))\nsuper().__init__(hass, LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL)",
"try:\n return await self.lametric.device()\nexcept LaMetricAuthenticatio... | <|body_start_0|>
self.config_entry = entry
self.lametric = LaMetricDevice(host=entry.data[CONF_HOST], api_key=entry.data[CONF_API_KEY], session=async_get_clientsession(hass))
super().__init__(hass, LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL)
<|end_body_0|>
<|body_start_1|>
try:
... | The LaMetric Data Update Coordinator. | LaMetricDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LaMetricDataUpdateCoordinator:
"""The LaMetric Data Update Coordinator."""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialize the LaMatric coordinator."""
<|body_0|>
async def _async_update_data(self) -> Device:
"""Fetch device inf... | stack_v2_sparse_classes_36k_train_017189 | 1,627 | permissive | [
{
"docstring": "Initialize the LaMatric coordinator.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None"
},
{
"docstring": "Fetch device information of the LaMetric device.",
"name": "_async_update_data",
"signature": "async def _async... | 2 | stack_v2_sparse_classes_30k_train_018398 | Implement the Python class `LaMetricDataUpdateCoordinator` described below.
Class description:
The LaMetric Data Update Coordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: Initialize the LaMatric coordinator.
- async def _async_update_data(self) -> Dev... | Implement the Python class `LaMetricDataUpdateCoordinator` described below.
Class description:
The LaMetric Data Update Coordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: Initialize the LaMatric coordinator.
- async def _async_update_data(self) -> Dev... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class LaMetricDataUpdateCoordinator:
"""The LaMetric Data Update Coordinator."""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialize the LaMatric coordinator."""
<|body_0|>
async def _async_update_data(self) -> Device:
"""Fetch device inf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LaMetricDataUpdateCoordinator:
"""The LaMetric Data Update Coordinator."""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialize the LaMatric coordinator."""
self.config_entry = entry
self.lametric = LaMetricDevice(host=entry.data[CONF_HOST], api_key=e... | the_stack_v2_python_sparse | homeassistant/components/lametric/coordinator.py | home-assistant/core | train | 35,501 |
bad617e9e3060caf4b738b09c15b047fd9a317fe | [
"next_num_id = self._next_numId\nnum = CT_Num.new(next_num_id, abstractNum_id)\nreturn self._insert_num(num)",
"xpath = './w:num[@w:numId=\"%d\"]' % numId\ntry:\n return self.xpath(xpath)[0]\nexcept IndexError:\n raise KeyError('no <w:num> element with numId %d' % numId)",
"numId_strs = self.xpath('./w:nu... | <|body_start_0|>
next_num_id = self._next_numId
num = CT_Num.new(next_num_id, abstractNum_id)
return self._insert_num(num)
<|end_body_0|>
<|body_start_1|>
xpath = './w:num[@w:numId="%d"]' % numId
try:
return self.xpath(xpath)[0]
except IndexError:
... | ``<w:numbering>`` element, the root element of a numbering part, i.e. numbering.xml | CT_Numbering | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CT_Numbering:
"""``<w:numbering>`` element, the root element of a numbering part, i.e. numbering.xml"""
def add_num(self, abstractNum_id):
"""Return a newly added CT_Num (<w:num>) element referencing the abstract numbering definition identified by *abstractNum_id*."""
<|body_... | stack_v2_sparse_classes_36k_train_017190 | 4,119 | permissive | [
{
"docstring": "Return a newly added CT_Num (<w:num>) element referencing the abstract numbering definition identified by *abstractNum_id*.",
"name": "add_num",
"signature": "def add_num(self, abstractNum_id)"
},
{
"docstring": "Return the ``<w:num>`` child element having ``numId`` attribute mat... | 3 | null | Implement the Python class `CT_Numbering` described below.
Class description:
``<w:numbering>`` element, the root element of a numbering part, i.e. numbering.xml
Method signatures and docstrings:
- def add_num(self, abstractNum_id): Return a newly added CT_Num (<w:num>) element referencing the abstract numbering defi... | Implement the Python class `CT_Numbering` described below.
Class description:
``<w:numbering>`` element, the root element of a numbering part, i.e. numbering.xml
Method signatures and docstrings:
- def add_num(self, abstractNum_id): Return a newly added CT_Num (<w:num>) element referencing the abstract numbering defi... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class CT_Numbering:
"""``<w:numbering>`` element, the root element of a numbering part, i.e. numbering.xml"""
def add_num(self, abstractNum_id):
"""Return a newly added CT_Num (<w:num>) element referencing the abstract numbering definition identified by *abstractNum_id*."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CT_Numbering:
"""``<w:numbering>`` element, the root element of a numbering part, i.e. numbering.xml"""
def add_num(self, abstractNum_id):
"""Return a newly added CT_Num (<w:num>) element referencing the abstract numbering definition identified by *abstractNum_id*."""
next_num_id = self._... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/docx/oxml/numbering.py | ryfeus/lambda-packs | train | 1,283 |
d3a82ab7a9fb0c09a33689689363b6f1e29d4dfb | [
"self.click(self.ele_main_ProductButton)\nself.click(self.ele_product_addproductButton)\nself.sendKeys(self.ele_addproduct_productNameBox, productName)\nself.sendKeys(self.ele_addproduct_productCodeBox, productCode)\nself.click(self.ele_addproduct_productLeaderBox)\nself.click(self.ele_addproduct_productLeaderResul... | <|body_start_0|>
self.click(self.ele_main_ProductButton)
self.click(self.ele_product_addproductButton)
self.sendKeys(self.ele_addproduct_productNameBox, productName)
self.sendKeys(self.ele_addproduct_productCodeBox, productCode)
self.click(self.ele_addproduct_productLeaderBox)
... | AddProductPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddProductPage:
def addproduct_success(self, productName, productCode, productDescription):
"""添加产品"""
<|body_0|>
def verifyaddproduct_success(self, productName):
"""验证添加产品"""
<|body_1|>
def verifyaddproduct_Fail(self, errordescription='『产品名称』不能为空。'):
... | stack_v2_sparse_classes_36k_train_017191 | 4,318 | no_license | [
{
"docstring": "添加产品",
"name": "addproduct_success",
"signature": "def addproduct_success(self, productName, productCode, productDescription)"
},
{
"docstring": "验证添加产品",
"name": "verifyaddproduct_success",
"signature": "def verifyaddproduct_success(self, productName)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_018329 | Implement the Python class `AddProductPage` described below.
Class description:
Implement the AddProductPage class.
Method signatures and docstrings:
- def addproduct_success(self, productName, productCode, productDescription): 添加产品
- def verifyaddproduct_success(self, productName): 验证添加产品
- def verifyaddproduct_Fail... | Implement the Python class `AddProductPage` described below.
Class description:
Implement the AddProductPage class.
Method signatures and docstrings:
- def addproduct_success(self, productName, productCode, productDescription): 添加产品
- def verifyaddproduct_success(self, productName): 验证添加产品
- def verifyaddproduct_Fail... | 8a24452bcd80b78ecea8bd49b9a07c6b0aac530d | <|skeleton|>
class AddProductPage:
def addproduct_success(self, productName, productCode, productDescription):
"""添加产品"""
<|body_0|>
def verifyaddproduct_success(self, productName):
"""验证添加产品"""
<|body_1|>
def verifyaddproduct_Fail(self, errordescription='『产品名称』不能为空。'):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddProductPage:
def addproduct_success(self, productName, productCode, productDescription):
"""添加产品"""
self.click(self.ele_main_ProductButton)
self.click(self.ele_product_addproductButton)
self.sendKeys(self.ele_addproduct_productNameBox, productName)
self.sendKeys(self... | the_stack_v2_python_sparse | webFrameWork_moiiee/page/zentao/addproductPage.py | yuquan1006/WEB_PROJECT | train | 0 | |
56aacdbdd721ff4b31f737ef028256e3745e7931 | [
"if k <= 0 or not tinput or k > len(tinput):\n return []\nheapq.heapify(tinput)\nreturn [heapq.heappop(tinput) for _ in range(k)]",
"if k <= 0 or not tinput or k > len(tinput):\n return []\nmax_heap = []\nfor x in tinput:\n if len(max_heap) < k:\n heapq.heappush(max_heap, -x)\n elif max_heap[0]... | <|body_start_0|>
if k <= 0 or not tinput or k > len(tinput):
return []
heapq.heapify(tinput)
return [heapq.heappop(tinput) for _ in range(k)]
<|end_body_0|>
<|body_start_1|>
if k <= 0 or not tinput or k > len(tinput):
return []
max_heap = []
for x... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def GetLeastNumbers_Solution_min(self, tinput, k):
"""输出最小的K个数字"""
<|body_0|>
def GetLeastNumbers_Solution_max(self, tinput, k):
"""使用最大堆来模拟,这个也是最合理的"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if k <= 0 or not tinput or k > len(tinput... | stack_v2_sparse_classes_36k_train_017192 | 1,037 | no_license | [
{
"docstring": "输出最小的K个数字",
"name": "GetLeastNumbers_Solution_min",
"signature": "def GetLeastNumbers_Solution_min(self, tinput, k)"
},
{
"docstring": "使用最大堆来模拟,这个也是最合理的",
"name": "GetLeastNumbers_Solution_max",
"signature": "def GetLeastNumbers_Solution_max(self, tinput, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def GetLeastNumbers_Solution_min(self, tinput, k): 输出最小的K个数字
- def GetLeastNumbers_Solution_max(self, tinput, k): 使用最大堆来模拟,这个也是最合理的 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def GetLeastNumbers_Solution_min(self, tinput, k): 输出最小的K个数字
- def GetLeastNumbers_Solution_max(self, tinput, k): 使用最大堆来模拟,这个也是最合理的
<|skeleton|>
class Solution:
def GetLeas... | 3b8b36bcf8a983de4d8ce29734a85b6bfbe59fbc | <|skeleton|>
class Solution:
def GetLeastNumbers_Solution_min(self, tinput, k):
"""输出最小的K个数字"""
<|body_0|>
def GetLeastNumbers_Solution_max(self, tinput, k):
"""使用最大堆来模拟,这个也是最合理的"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def GetLeastNumbers_Solution_min(self, tinput, k):
"""输出最小的K个数字"""
if k <= 0 or not tinput or k > len(tinput):
return []
heapq.heapify(tinput)
return [heapq.heappop(tinput) for _ in range(k)]
def GetLeastNumbers_Solution_max(self, tinput, k):
... | the_stack_v2_python_sparse | TargetOffer/40、最小的K个数.py | a625687551/Leetcode | train | 0 | |
e125e655a8febcb816ca069eaaa3bbd2076ae4e7 | [
"super(GroupNormGenerated, self).__init__()\nself.num_groups = num_groups\nself.num_channels = num_channels\nself.eps = eps\nself.bottleneck = nn.Linear(E_1, E_2)\nself.affine = nn.Linear(E_2, num_channels + num_channels)",
"batch_size = x.shape[0]\ninstrument = self.bottleneck(instrument)\naffine = self.affine(i... | <|body_start_0|>
super(GroupNormGenerated, self).__init__()
self.num_groups = num_groups
self.num_channels = num_channels
self.eps = eps
self.bottleneck = nn.Linear(E_1, E_2)
self.affine = nn.Linear(E_2, num_channels + num_channels)
<|end_body_0|>
<|body_start_1|>
... | Group normalization layer with scale and bias factor created with a linear transformation of the instrument embedding | GroupNormGenerated | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupNormGenerated:
"""Group normalization layer with scale and bias factor created with a linear transformation of the instrument embedding"""
def __init__(self, E_1, E_2, num_groups, num_channels, eps=1e-08):
"""Arguments: E_1 {int} -- Dimension of the instrument embedding E_2 {int... | stack_v2_sparse_classes_36k_train_017193 | 37,269 | no_license | [
{
"docstring": "Arguments: E_1 {int} -- Dimension of the instrument embedding E_2 {int} -- Dimension of the instrument embedding bottleneck num_groups {int} -- Number of normalized groups num_channels {int} -- Number of channels Keyword Arguments: eps {int} -- Constant for numerical stability (default: {1e-8})"... | 2 | stack_v2_sparse_classes_30k_train_002514 | Implement the Python class `GroupNormGenerated` described below.
Class description:
Group normalization layer with scale and bias factor created with a linear transformation of the instrument embedding
Method signatures and docstrings:
- def __init__(self, E_1, E_2, num_groups, num_channels, eps=1e-08): Arguments: E_... | Implement the Python class `GroupNormGenerated` described below.
Class description:
Group normalization layer with scale and bias factor created with a linear transformation of the instrument embedding
Method signatures and docstrings:
- def __init__(self, E_1, E_2, num_groups, num_channels, eps=1e-08): Arguments: E_... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class GroupNormGenerated:
"""Group normalization layer with scale and bias factor created with a linear transformation of the instrument embedding"""
def __init__(self, E_1, E_2, num_groups, num_channels, eps=1e-08):
"""Arguments: E_1 {int} -- Dimension of the instrument embedding E_2 {int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupNormGenerated:
"""Group normalization layer with scale and bias factor created with a linear transformation of the instrument embedding"""
def __init__(self, E_1, E_2, num_groups, num_channels, eps=1e-08):
"""Arguments: E_1 {int} -- Dimension of the instrument embedding E_2 {int} -- Dimensio... | the_stack_v2_python_sparse | generated/test_pfnet_research_meta_tasnet.py | jansel/pytorch-jit-paritybench | train | 35 |
987960badf80458cb3cde7066c2171e61b49b579 | [
"nn.Module.__init__(self)\nself.params = {'num_inputs': num_inputs, 'num_outputs': num_outputs, 'a_values': None if a_values is None else a_values.tolist(), 'b_values': None if b_values is None else b_values.tolist(), 'layer_channels': layer_channels}\nself.num_inputs = num_inputs\nif b_values is None:\n self.a_... | <|body_start_0|>
nn.Module.__init__(self)
self.params = {'num_inputs': num_inputs, 'num_outputs': num_outputs, 'a_values': None if a_values is None else a_values.tolist(), 'b_values': None if b_values is None else b_values.tolist(), 'layer_channels': layer_channels}
self.num_inputs = num_inputs
... | MLP which uses Fourier features as a preprocessing step. | BaseFourierFeatureMLP | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFourierFeatureMLP:
"""MLP which uses Fourier features as a preprocessing step."""
def __init__(self, num_inputs: int, num_outputs: int, a_values: Optional[torch.Tensor], b_values: Optional[torch.Tensor], layer_channels: List[int]):
"""Constructor. Args: num_inputs (int): Number o... | stack_v2_sparse_classes_36k_train_017194 | 8,060 | permissive | [
{
"docstring": "Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int): Number of dimensions in the output a_values (torch.Tensor): a values for encoding b_values (torch.Tensor): b values for encoding layer_channels (List[int]): Number of channels per layer.",
"name": "__in... | 3 | stack_v2_sparse_classes_30k_train_021448 | Implement the Python class `BaseFourierFeatureMLP` described below.
Class description:
MLP which uses Fourier features as a preprocessing step.
Method signatures and docstrings:
- def __init__(self, num_inputs: int, num_outputs: int, a_values: Optional[torch.Tensor], b_values: Optional[torch.Tensor], layer_channels: ... | Implement the Python class `BaseFourierFeatureMLP` described below.
Class description:
MLP which uses Fourier features as a preprocessing step.
Method signatures and docstrings:
- def __init__(self, num_inputs: int, num_outputs: int, a_values: Optional[torch.Tensor], b_values: Optional[torch.Tensor], layer_channels: ... | 94a402cab47a2bd6241608308371490079af4d53 | <|skeleton|>
class BaseFourierFeatureMLP:
"""MLP which uses Fourier features as a preprocessing step."""
def __init__(self, num_inputs: int, num_outputs: int, a_values: Optional[torch.Tensor], b_values: Optional[torch.Tensor], layer_channels: List[int]):
"""Constructor. Args: num_inputs (int): Number o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseFourierFeatureMLP:
"""MLP which uses Fourier features as a preprocessing step."""
def __init__(self, num_inputs: int, num_outputs: int, a_values: Optional[torch.Tensor], b_values: Optional[torch.Tensor], layer_channels: List[int]):
"""Constructor. Args: num_inputs (int): Number of dimensions ... | the_stack_v2_python_sparse | draugr/torch_utilities/architectures/mlp_variants/fourier.py | cnheider/draugr | train | 4 |
2d2be295ae22ec7be495e9bebc28f5283928e949 | [
"self.base = base\nval = ''\nallowed_chars = self.ALLOWED[:self.base]\nif default is not None:\n if not isinstance(default, (int, str, Decimal)):\n raise ValueError(\"default: Only 'str', 'int', 'long' or Decimal input allowed\")\n if isinstance(default, str) and len(default):\n validation_re = ... | <|body_start_0|>
self.base = base
val = ''
allowed_chars = self.ALLOWED[:self.base]
if default is not None:
if not isinstance(default, (int, str, Decimal)):
raise ValueError("default: Only 'str', 'int', 'long' or Decimal input allowed")
if isinstan... | Edit widget for integer values | IntegerEdit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntegerEdit:
"""Edit widget for integer values"""
def __init__(self, caption='', default=None, base=10):
"""caption -- caption markup default -- default edit value >>> IntegerEdit(u"", 42) <IntegerEdit selectable flow widget '42' edit_pos=2> >>> e, size = IntegerEdit(u"", "5002"), (1... | stack_v2_sparse_classes_36k_train_017195 | 10,901 | permissive | [
{
"docstring": "caption -- caption markup default -- default edit value >>> IntegerEdit(u\"\", 42) <IntegerEdit selectable flow widget '42' edit_pos=2> >>> e, size = IntegerEdit(u\"\", \"5002\"), (10,) >>> e.keypress(size, 'home') >>> e.keypress(size, 'delete') >>> assert e.edit_text == \"002\" >>> e.keypress(s... | 2 | stack_v2_sparse_classes_30k_train_017967 | Implement the Python class `IntegerEdit` described below.
Class description:
Edit widget for integer values
Method signatures and docstrings:
- def __init__(self, caption='', default=None, base=10): caption -- caption markup default -- default edit value >>> IntegerEdit(u"", 42) <IntegerEdit selectable flow widget '4... | Implement the Python class `IntegerEdit` described below.
Class description:
Edit widget for integer values
Method signatures and docstrings:
- def __init__(self, caption='', default=None, base=10): caption -- caption markup default -- default edit value >>> IntegerEdit(u"", 42) <IntegerEdit selectable flow widget '4... | 95b7a061eabd6f2b607fba79e007186030f02720 | <|skeleton|>
class IntegerEdit:
"""Edit widget for integer values"""
def __init__(self, caption='', default=None, base=10):
"""caption -- caption markup default -- default edit value >>> IntegerEdit(u"", 42) <IntegerEdit selectable flow widget '42' edit_pos=2> >>> e, size = IntegerEdit(u"", "5002"), (1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IntegerEdit:
"""Edit widget for integer values"""
def __init__(self, caption='', default=None, base=10):
"""caption -- caption markup default -- default edit value >>> IntegerEdit(u"", 42) <IntegerEdit selectable flow widget '42' edit_pos=2> >>> e, size = IntegerEdit(u"", "5002"), (10,) >>> e.key... | the_stack_v2_python_sparse | Ricardo_OS/Python_backend/venv/lib/python3.8/site-packages/urwid/numedit.py | icl-rocketry/Avionics | train | 9 |
7fa5ff5b9487d6c49fc2535d165d8b46f8237ad6 | [
"rowNum = len(obstacleGrid)\ncolNum = len(obstacleGrid[0]) if rowNum > 0 else 0\nbtou = [[None for _ in range(colNum)] for _ in range(rowNum)]\nfor i in range(rowNum):\n for j in range(colNum):\n if obstacleGrid[i][j] == 1:\n btou[rowNum - i - 1][colNum - j - 1] = 0\nif obstacleGrid[rowNum - 1]... | <|body_start_0|>
rowNum = len(obstacleGrid)
colNum = len(obstacleGrid[0]) if rowNum > 0 else 0
btou = [[None for _ in range(colNum)] for _ in range(rowNum)]
for i in range(rowNum):
for j in range(colNum):
if obstacleGrid[i][j] == 1:
btou[ro... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_0|>
def uniquePathNoObstacles(self, m, n):
"""space m * n :param m: :param n: :return:"""
<|body_1|>
def uniquePathNoObstacles2(self,... | stack_v2_sparse_classes_36k_train_017196 | 2,346 | no_license | [
{
"docstring": ":type obstacleGrid: List[List[int]] :rtype: int",
"name": "uniquePathsWithObstacles",
"signature": "def uniquePathsWithObstacles(self, obstacleGrid)"
},
{
"docstring": "space m * n :param m: :param n: :return:",
"name": "uniquePathNoObstacles",
"signature": "def uniquePat... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePathsWithObstacles(self, obstacleGrid): :type obstacleGrid: List[List[int]] :rtype: int
- def uniquePathNoObstacles(self, m, n): space m * n :param m: :param n: :return... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePathsWithObstacles(self, obstacleGrid): :type obstacleGrid: List[List[int]] :rtype: int
- def uniquePathNoObstacles(self, m, n): space m * n :param m: :param n: :return... | e16702d2b3ec4e5054baad56f4320bc3b31676ad | <|skeleton|>
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_0|>
def uniquePathNoObstacles(self, m, n):
"""space m * n :param m: :param n: :return:"""
<|body_1|>
def uniquePathNoObstacles2(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
rowNum = len(obstacleGrid)
colNum = len(obstacleGrid[0]) if rowNum > 0 else 0
btou = [[None for _ in range(colNum)] for _ in range(rowNum)]
for i in range(r... | the_stack_v2_python_sparse | leetcode/medium/uniquePath.py | SuperMartinYang/learning_algorithm | train | 0 | |
62831eec658dca245327c24390e1ab33128ad9ac | [
"super(Image, self).__init__(*args, **kwargs)\nself.setVar('category', 'image')\nself.setVar('imageType', 'single')\nself.__computeImageSequence()",
"isImageSeq = self.__isStandardSequence()\nif not isImageSeq:\n isImageSeq = self.__isAmbiguousSequence()\nreturn isImageSeq",
"nameParts = self.pathHolder().ba... | <|body_start_0|>
super(Image, self).__init__(*args, **kwargs)
self.setVar('category', 'image')
self.setVar('imageType', 'single')
self.__computeImageSequence()
<|end_body_0|>
<|body_start_1|>
isImageSeq = self.__isStandardSequence()
if not isImageSeq:
isImage... | Abstracted image crawler. | Image | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Image:
"""Abstracted image crawler."""
def __init__(self, *args, **kwargs):
"""Create an image crawler."""
<|body_0|>
def isSequence(self):
"""Return if path holder is holding a file that is part of a image sequence."""
<|body_1|>
def __computeImageS... | stack_v2_sparse_classes_36k_train_017197 | 3,096 | permissive | [
{
"docstring": "Create an image crawler.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Return if path holder is holding a file that is part of a image sequence.",
"name": "isSequence",
"signature": "def isSequence(self)"
},
{
"docstri... | 5 | stack_v2_sparse_classes_30k_train_009011 | Implement the Python class `Image` described below.
Class description:
Abstracted image crawler.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create an image crawler.
- def isSequence(self): Return if path holder is holding a file that is part of a image sequence.
- def __computeImageSeque... | Implement the Python class `Image` described below.
Class description:
Abstracted image crawler.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create an image crawler.
- def isSequence(self): Return if path holder is holding a file that is part of a image sequence.
- def __computeImageSeque... | 0b1dc1f17b025f6b37c9a3cf5753a46cbbcd36ba | <|skeleton|>
class Image:
"""Abstracted image crawler."""
def __init__(self, *args, **kwargs):
"""Create an image crawler."""
<|body_0|>
def isSequence(self):
"""Return if path holder is holding a file that is part of a image sequence."""
<|body_1|>
def __computeImageS... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Image:
"""Abstracted image crawler."""
def __init__(self, *args, **kwargs):
"""Create an image crawler."""
super(Image, self).__init__(*args, **kwargs)
self.setVar('category', 'image')
self.setVar('imageType', 'single')
self.__computeImageSequence()
def isSequ... | the_stack_v2_python_sparse | src/lib/centipede/Crawler/Fs/Image/Image.py | ramgopal99/centipede | train | 0 |
fb396c5d00a91b4a2fbc078cd2a157dd9c9bb72b | [
"super(MIbyOneClassSVM, self).__init__(**kwargs)\nself._bags = None\nself._bag_predictions = None",
"self._bags = [np.asmatrix(bag) for bag in bags]\ny = np.asmatrix(y).reshape((-1, 1))\nlist_X_neg = []\nfor bag, cls in zip(self._bags, y):\n if cls == -1:\n list_X_neg += [bag]\nX_neg = np.vstack(list_X_... | <|body_start_0|>
super(MIbyOneClassSVM, self).__init__(**kwargs)
self._bags = None
self._bag_predictions = None
<|end_body_0|>
<|body_start_1|>
self._bags = [np.asmatrix(bag) for bag in bags]
y = np.asmatrix(y).reshape((-1, 1))
list_X_neg = []
for bag, cls in zip... | Single-Instance Learning applied to MI data | MIbyOneClassSVM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MIbyOneClassSVM:
"""Single-Instance Learning applied to MI data"""
def __init__(self, **kwargs):
"""@param kernel : the desired kernel function; can be linear, quadratic, polynomial, or rbf [default: linear] @param C : the loss/regularization tradeoff constant [default: 1.0] @param s... | stack_v2_sparse_classes_36k_train_017198 | 5,384 | no_license | [
{
"docstring": "@param kernel : the desired kernel function; can be linear, quadratic, polynomial, or rbf [default: linear] @param C : the loss/regularization tradeoff constant [default: 1.0] @param scale_C : if True [default], scale C by the number of examples @param p : polynomial degree when a 'polynomial' k... | 5 | stack_v2_sparse_classes_30k_train_017994 | Implement the Python class `MIbyOneClassSVM` described below.
Class description:
Single-Instance Learning applied to MI data
Method signatures and docstrings:
- def __init__(self, **kwargs): @param kernel : the desired kernel function; can be linear, quadratic, polynomial, or rbf [default: linear] @param C : the loss... | Implement the Python class `MIbyOneClassSVM` described below.
Class description:
Single-Instance Learning applied to MI data
Method signatures and docstrings:
- def __init__(self, **kwargs): @param kernel : the desired kernel function; can be linear, quadratic, polynomial, or rbf [default: linear] @param C : the loss... | 60da35f58ffe9e24e99b6b20dd7a46b02815ad79 | <|skeleton|>
class MIbyOneClassSVM:
"""Single-Instance Learning applied to MI data"""
def __init__(self, **kwargs):
"""@param kernel : the desired kernel function; can be linear, quadratic, polynomial, or rbf [default: linear] @param C : the loss/regularization tradeoff constant [default: 1.0] @param s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MIbyOneClassSVM:
"""Single-Instance Learning applied to MI data"""
def __init__(self, **kwargs):
"""@param kernel : the desired kernel function; can be linear, quadratic, polynomial, or rbf [default: linear] @param C : the loss/regularization tradeoff constant [default: 1.0] @param scale_C : if T... | the_stack_v2_python_sparse | Classif_Paintings/MILbenchmark/mialgo/MIbyOneClassSVM.py | ngonthier/Icono_Art_Analysis | train | 2 |
bd99975a2e10405a5a980d0e8d460aed4ebe8fd0 | [
"DriverClient.__init__(self)\nself.host = host\nself.cmd_port = cmd_port\nself.event_port = event_port\nself.cmd_host_string = 'tcp://%s:%i' % (self.host, self.cmd_port)\nself.event_host_string = 'tcp://%s:%i' % (self.host, self.event_port)\nself.zmq_context = None\nself.zmq_cmd_socket = None\nself.event_thread = N... | <|body_start_0|>
DriverClient.__init__(self)
self.host = host
self.cmd_port = cmd_port
self.event_port = event_port
self.cmd_host_string = 'tcp://%s:%i' % (self.host, self.cmd_port)
self.event_host_string = 'tcp://%s:%i' % (self.host, self.event_port)
self.zmq_con... | A class for communicating with a ZMQ-based driver process using python thread for catching asynchronous driver events. | ZmqDriverClient | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZmqDriverClient:
"""A class for communicating with a ZMQ-based driver process using python thread for catching asynchronous driver events."""
def __init__(self, host, cmd_port, event_port):
"""Initialize members. @param host Host string address of the driver process. @param cmd_port ... | stack_v2_sparse_classes_36k_train_017199 | 6,238 | permissive | [
{
"docstring": "Initialize members. @param host Host string address of the driver process. @param cmd_port Port number for the driver process command port. @param event_port Port number for the driver process event port.",
"name": "__init__",
"signature": "def __init__(self, host, cmd_port, event_port)"... | 4 | stack_v2_sparse_classes_30k_train_007868 | Implement the Python class `ZmqDriverClient` described below.
Class description:
A class for communicating with a ZMQ-based driver process using python thread for catching asynchronous driver events.
Method signatures and docstrings:
- def __init__(self, host, cmd_port, event_port): Initialize members. @param host Ho... | Implement the Python class `ZmqDriverClient` described below.
Class description:
A class for communicating with a ZMQ-based driver process using python thread for catching asynchronous driver events.
Method signatures and docstrings:
- def __init__(self, host, cmd_port, event_port): Initialize members. @param host Ho... | bdbf01f5614e7188ce19596704794466e5683b30 | <|skeleton|>
class ZmqDriverClient:
"""A class for communicating with a ZMQ-based driver process using python thread for catching asynchronous driver events."""
def __init__(self, host, cmd_port, event_port):
"""Initialize members. @param host Host string address of the driver process. @param cmd_port ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZmqDriverClient:
"""A class for communicating with a ZMQ-based driver process using python thread for catching asynchronous driver events."""
def __init__(self, host, cmd_port, event_port):
"""Initialize members. @param host Host string address of the driver process. @param cmd_port Port number f... | the_stack_v2_python_sparse | mi/core/instrument/zmq_driver_client.py | oceanobservatories/mi-instrument | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.