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
960dad9e69bd28bece2c661f9659311b32288b85
[ "input_logits = np.array([[[-1.0, -2.0, -3.0], [-4.0, -5.0, -6.0], [-7.0, -8.0, -9.0], [-10.0, -11.0, -12.0]]])\noutput_labels = np.array([[1, 2, 2]])\nloss = asr_loss.ctc(input_logits=input_logits, output_labels=output_labels, input_seq_len=[4], output_seq_len=[3])\nby_hand = -tf.reduce_logsumexp([np.sum([-2.0, -6...
<|body_start_0|> input_logits = np.array([[[-1.0, -2.0, -3.0], [-4.0, -5.0, -6.0], [-7.0, -8.0, -9.0], [-10.0, -11.0, -12.0]]]) output_labels = np.array([[1, 2, 2]]) loss = asr_loss.ctc(input_logits=input_logits, output_labels=output_labels, input_seq_len=[4], output_seq_len=[3]) by_hand...
ASRLossTest
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ASRLossTest: def testCTCByHand(self): """Enumerate a very simple lattice by hand and compare.""" <|body_0|> def testRNNTByHand(self): """Enumerate a very simple lattice by hand and compare.""" <|body_1|> <|end_skeleton|> <|body_start_0|> input_logit...
stack_v2_sparse_classes_36k_train_024000
12,682
permissive
[ { "docstring": "Enumerate a very simple lattice by hand and compare.", "name": "testCTCByHand", "signature": "def testCTCByHand(self)" }, { "docstring": "Enumerate a very simple lattice by hand and compare.", "name": "testRNNTByHand", "signature": "def testRNNTByHand(self)" } ]
2
null
Implement the Python class `ASRLossTest` described below. Class description: Implement the ASRLossTest class. Method signatures and docstrings: - def testCTCByHand(self): Enumerate a very simple lattice by hand and compare. - def testRNNTByHand(self): Enumerate a very simple lattice by hand and compare.
Implement the Python class `ASRLossTest` described below. Class description: Implement the ASRLossTest class. Method signatures and docstrings: - def testCTCByHand(self): Enumerate a very simple lattice by hand and compare. - def testRNNTByHand(self): Enumerate a very simple lattice by hand and compare. <|skeleton|>...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class ASRLossTest: def testCTCByHand(self): """Enumerate a very simple lattice by hand and compare.""" <|body_0|> def testRNNTByHand(self): """Enumerate a very simple lattice by hand and compare.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ASRLossTest: def testCTCByHand(self): """Enumerate a very simple lattice by hand and compare.""" input_logits = np.array([[[-1.0, -2.0, -3.0], [-4.0, -5.0, -6.0], [-7.0, -8.0, -9.0], [-10.0, -11.0, -12.0]]]) output_labels = np.array([[1, 2, 2]]) loss = asr_loss.ctc(input_logits...
the_stack_v2_python_sparse
entropy_semiring/asr_loss_test.py
Jimmy-INL/google-research
train
1
71d305bfd850dbee94b3f4b3c6a359dc403a8af3
[ "mongo = database.MongoDBConnection()\nwith mongo:\n db = mongo.connection.HPNortonDatabase\n products = db['products']\n customers = db['customers']\n rentals = db['rentals']\nproducts.drop()\ncustomers.drop()\nrentals.drop()", "directory_path = 'data'\ntuple1, tuple2 = database.import_data(directory...
<|body_start_0|> mongo = database.MongoDBConnection() with mongo: db = mongo.connection.HPNortonDatabase products = db['products'] customers = db['customers'] rentals = db['rentals'] products.drop() customers.drop() rentals.drop() <...
Tests for the database module
DatabaseTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DatabaseTests: """Tests for the database module""" def setUp(self): """Sets up database for each test""" <|body_0|> def test_import_data(self): """Tests the import_data function""" <|body_1|> def test_show_available_products(self): """Tests t...
stack_v2_sparse_classes_36k_train_024001
3,519
no_license
[ { "docstring": "Sets up database for each test", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Tests the import_data function", "name": "test_import_data", "signature": "def test_import_data(self)" }, { "docstring": "Tests the show_available_products module",...
4
stack_v2_sparse_classes_30k_train_012635
Implement the Python class `DatabaseTests` described below. Class description: Tests for the database module Method signatures and docstrings: - def setUp(self): Sets up database for each test - def test_import_data(self): Tests the import_data function - def test_show_available_products(self): Tests the show_availab...
Implement the Python class `DatabaseTests` described below. Class description: Tests for the database module Method signatures and docstrings: - def setUp(self): Sets up database for each test - def test_import_data(self): Tests the import_data function - def test_show_available_products(self): Tests the show_availab...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class DatabaseTests: """Tests for the database module""" def setUp(self): """Sets up database for each test""" <|body_0|> def test_import_data(self): """Tests the import_data function""" <|body_1|> def test_show_available_products(self): """Tests t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DatabaseTests: """Tests for the database module""" def setUp(self): """Sets up database for each test""" mongo = database.MongoDBConnection() with mongo: db = mongo.connection.HPNortonDatabase products = db['products'] customers = db['customers'...
the_stack_v2_python_sparse
students/amirg/lesson09/assignment/test_database.py
JavaRod/SP_Python220B_2019
train
1
5586f355622d9a833b912c75a80b06d1610c5fd4
[ "self.bandwidth_limit_overrides = bandwidth_limit_overrides\nself.io_rate = io_rate\nself.rate_limit_bytes_per_sec = rate_limit_bytes_per_sec\nself.timezone = timezone", "if dictionary is None:\n return None\nbandwidth_limit_overrides = None\nif dictionary.get('bandwidthLimitOverrides') != None:\n bandwidth...
<|body_start_0|> self.bandwidth_limit_overrides = bandwidth_limit_overrides self.io_rate = io_rate self.rate_limit_bytes_per_sec = rate_limit_bytes_per_sec self.timezone = timezone <|end_body_0|> <|body_start_1|> if dictionary is None: return None bandwidth_l...
Implementation of the 'BandwidthLimit' model. Specifies settings for limiting the data transfer rate between the local and remote Clusters or bandwidth limiting schedule for apollo. Only one of RateLimitBytesPerSec or IoRate should be set in this struct and corresponding BandwidthLimitOverrides should also be in the sa...
BandwidthLimit
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BandwidthLimit: """Implementation of the 'BandwidthLimit' model. Specifies settings for limiting the data transfer rate between the local and remote Clusters or bandwidth limiting schedule for apollo. Only one of RateLimitBytesPerSec or IoRate should be set in this struct and corresponding Bandwi...
stack_v2_sparse_classes_36k_train_024002
3,645
permissive
[ { "docstring": "Constructor for the BandwidthLimit class", "name": "__init__", "signature": "def __init__(self, bandwidth_limit_overrides=None, io_rate=None, rate_limit_bytes_per_sec=None, timezone=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (di...
2
null
Implement the Python class `BandwidthLimit` described below. Class description: Implementation of the 'BandwidthLimit' model. Specifies settings for limiting the data transfer rate between the local and remote Clusters or bandwidth limiting schedule for apollo. Only one of RateLimitBytesPerSec or IoRate should be set ...
Implement the Python class `BandwidthLimit` described below. Class description: Implementation of the 'BandwidthLimit' model. Specifies settings for limiting the data transfer rate between the local and remote Clusters or bandwidth limiting schedule for apollo. Only one of RateLimitBytesPerSec or IoRate should be set ...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class BandwidthLimit: """Implementation of the 'BandwidthLimit' model. Specifies settings for limiting the data transfer rate between the local and remote Clusters or bandwidth limiting schedule for apollo. Only one of RateLimitBytesPerSec or IoRate should be set in this struct and corresponding Bandwi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BandwidthLimit: """Implementation of the 'BandwidthLimit' model. Specifies settings for limiting the data transfer rate between the local and remote Clusters or bandwidth limiting schedule for apollo. Only one of RateLimitBytesPerSec or IoRate should be set in this struct and corresponding BandwidthLimitOverr...
the_stack_v2_python_sparse
cohesity_management_sdk/models/bandwidth_limit.py
cohesity/management-sdk-python
train
24
de17182cddb90b440f6b15abcb8626edf1c75ab8
[ "if not head or not head.next:\n return head\nnew_head = head.next\nhead.next, new_head.next = (self.swapPairs(new_head.next), head)\nreturn new_head", "pre, pre.next = (self, head)\nwhile pre.next and pre.next.next:\n a = pre.next\n b = a.next\n pre.next, b.next, a.next = (b, a, b.next)\n pre = a\...
<|body_start_0|> if not head or not head.next: return head new_head = head.next head.next, new_head.next = (self.swapPairs(new_head.next), head) return new_head <|end_body_0|> <|body_start_1|> pre, pre.next = (self, head) while pre.next and pre.next.next: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def swapPairs(self, head: ListNode) -> ListNode: """思路:递归 1。 终止条件:head 后只有 一个 node,即 not head or not head.next 2. 每层 返回值: 已排好序的后两个 node 的 head 3。 本 level 处理的 task,交换两个 node 空间复杂度 O(n)""" <|body_0|> def swapPairs(self, head: ListNode) -> ListNode: """思路:非递归 ...
stack_v2_sparse_classes_36k_train_024003
1,810
no_license
[ { "docstring": "思路:递归 1。 终止条件:head 后只有 一个 node,即 not head or not head.next 2. 每层 返回值: 已排好序的后两个 node 的 head 3。 本 level 处理的 task,交换两个 node 空间复杂度 O(n)", "name": "swapPairs", "signature": "def swapPairs(self, head: ListNode) -> ListNode" }, { "docstring": "思路:非递归 1。 终止条件:head 后只有 一个 node,即 not head ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def swapPairs(self, head: ListNode) -> ListNode: 思路:递归 1。 终止条件:head 后只有 一个 node,即 not head or not head.next 2. 每层 返回值: 已排好序的后两个 node 的 head 3。 本 level 处理的 task,交换两个 node 空间复杂度 O(...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def swapPairs(self, head: ListNode) -> ListNode: 思路:递归 1。 终止条件:head 后只有 一个 node,即 not head or not head.next 2. 每层 返回值: 已排好序的后两个 node 的 head 3。 本 level 处理的 task,交换两个 node 空间复杂度 O(...
4994b8b19abcdbcc0bda2944350e325242fadfd1
<|skeleton|> class Solution: def swapPairs(self, head: ListNode) -> ListNode: """思路:递归 1。 终止条件:head 后只有 一个 node,即 not head or not head.next 2. 每层 返回值: 已排好序的后两个 node 的 head 3。 本 level 处理的 task,交换两个 node 空间复杂度 O(n)""" <|body_0|> def swapPairs(self, head: ListNode) -> ListNode: """思路:非递归 ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def swapPairs(self, head: ListNode) -> ListNode: """思路:递归 1。 终止条件:head 后只有 一个 node,即 not head or not head.next 2. 每层 返回值: 已排好序的后两个 node 的 head 3。 本 level 处理的 task,交换两个 node 空间复杂度 O(n)""" if not head or not head.next: return head new_head = head.next head.n...
the_stack_v2_python_sparse
Week_01/swapPairs.py
NanZhang715/AlgorithmCHUNZHAO
train
0
9b9bcebf909b833790caaba0bbf3d85f85c851af
[ "max_len, left, right = (0, 0, 0)\nfor i in range(len(s)):\n if s[i] == '(':\n left += 1\n else:\n right += 1\n if left == right:\n max_len = max(max_len, 2 * right)\n if right > left:\n right, left = (0, 0)\nright, left = (0, 0)\nfor j in range(len(s))[::-1]:\n if s[j] ==...
<|body_start_0|> max_len, left, right = (0, 0, 0) for i in range(len(s)): if s[i] == '(': left += 1 else: right += 1 if left == right: max_len = max(max_len, 2 * right) if right > left: right,...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def get_longest_valid_parentheses(self, s: List[str]) -> int: """遍历所有的括号,计算有效字符串 Args: s: 字符串 Returns: 匹配字符串长度""" <|body_0|> def get_longest_valid_parentheses2(self, s: List[str]) -> int: """遍历所有的括号,计算有效字符串 Args: s: 字符串 Returns: 匹配字符串长度""" <|body_1|...
stack_v2_sparse_classes_36k_train_024004
3,876
permissive
[ { "docstring": "遍历所有的括号,计算有效字符串 Args: s: 字符串 Returns: 匹配字符串长度", "name": "get_longest_valid_parentheses", "signature": "def get_longest_valid_parentheses(self, s: List[str]) -> int" }, { "docstring": "遍历所有的括号,计算有效字符串 Args: s: 字符串 Returns: 匹配字符串长度", "name": "get_longest_valid_parentheses2", ...
4
stack_v2_sparse_classes_30k_train_007623
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def get_longest_valid_parentheses(self, s: List[str]) -> int: 遍历所有的括号,计算有效字符串 Args: s: 字符串 Returns: 匹配字符串长度 - def get_longest_valid_parentheses2(self, s: List[str]) -> int: 遍历所有的...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def get_longest_valid_parentheses(self, s: List[str]) -> int: 遍历所有的括号,计算有效字符串 Args: s: 字符串 Returns: 匹配字符串长度 - def get_longest_valid_parentheses2(self, s: List[str]) -> int: 遍历所有的...
50f35eef6a0ad63173efed10df3c835b1dceaa3f
<|skeleton|> class Solution: def get_longest_valid_parentheses(self, s: List[str]) -> int: """遍历所有的括号,计算有效字符串 Args: s: 字符串 Returns: 匹配字符串长度""" <|body_0|> def get_longest_valid_parentheses2(self, s: List[str]) -> int: """遍历所有的括号,计算有效字符串 Args: s: 字符串 Returns: 匹配字符串长度""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def get_longest_valid_parentheses(self, s: List[str]) -> int: """遍历所有的括号,计算有效字符串 Args: s: 字符串 Returns: 匹配字符串长度""" max_len, left, right = (0, 0, 0) for i in range(len(s)): if s[i] == '(': left += 1 else: right += 1 ...
the_stack_v2_python_sparse
src/leetcodepython/top100likedquestions/longest_valid_parentheses_32.py
zhangyu345293721/leetcode
train
101
24ef36fea0ae11af52da6ec553893a71854d273f
[ "if projects_directory is None:\n self.projects_directory = self.Defaults.projects_directory\nelse:\n self.projects_directory = projects_directory", "if projects_directory is None:\n projects_directory = self.projects_directory\nname = support.ensure_end(_string, '.sublime-project')\nreturn name in self....
<|body_start_0|> if projects_directory is None: self.projects_directory = self.Defaults.projects_directory else: self.projects_directory = projects_directory <|end_body_0|> <|body_start_1|> if projects_directory is None: projects_directory = self.projects_dir...
Attempt to open a project file by looking in a standardized location for all project files (usually located in the user's SublimeText packages directory).
OpenProjectFromName
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OpenProjectFromName: """Attempt to open a project file by looking in a standardized location for all project files (usually located in the user's SublimeText packages directory).""" def __init__(self, projects_directory=None): """Input is project file, in standard directory for subli...
stack_v2_sparse_classes_36k_train_024005
8,112
permissive
[ { "docstring": "Input is project file, in standard directory for sublime-project files.", "name": "__init__", "signature": "def __init__(self, projects_directory=None)" }, { "docstring": "@type: _string: str @returns: bool", "name": "matches", "signature": "def matches(self, _string, pro...
4
stack_v2_sparse_classes_30k_train_010536
Implement the Python class `OpenProjectFromName` described below. Class description: Attempt to open a project file by looking in a standardized location for all project files (usually located in the user's SublimeText packages directory). Method signatures and docstrings: - def __init__(self, projects_directory=None...
Implement the Python class `OpenProjectFromName` described below. Class description: Attempt to open a project file by looking in a standardized location for all project files (usually located in the user's SublimeText packages directory). Method signatures and docstrings: - def __init__(self, projects_directory=None...
6504a00e70e9c6be365f92dad69f4f4d5df41cf9
<|skeleton|> class OpenProjectFromName: """Attempt to open a project file by looking in a standardized location for all project files (usually located in the user's SublimeText packages directory).""" def __init__(self, projects_directory=None): """Input is project file, in standard directory for subli...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OpenProjectFromName: """Attempt to open a project file by looking in a standardized location for all project files (usually located in the user's SublimeText packages directory).""" def __init__(self, projects_directory=None): """Input is project file, in standard directory for sublime-project fi...
the_stack_v2_python_sparse
sublp/dispatch_cases.py
OaklandPeters/sublp
train
0
f20412d5bb783c6bef157c385a79cccaabc13634
[ "try:\n reset_password_code = self.request.query['reset_password_code']\nexcept KeyError:\n return make_response(success=False, message='Required param reset_password_code is not provided.', http_status=HTTPStatus.UNPROCESSABLE_ENTITY)\nreturn render_template('reset_password.html', self.request, {'reset_passw...
<|body_start_0|> try: reset_password_code = self.request.query['reset_password_code'] except KeyError: return make_response(success=False, message='Required param reset_password_code is not provided.', http_status=HTTPStatus.UNPROCESSABLE_ENTITY) return render_template('r...
Class that includes functionality for user password resetting.
AuthResetPasswordView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthResetPasswordView: """Class that includes functionality for user password resetting.""" async def get(self): """Render reset password form.""" <|body_0|> async def post(self): """Kick off user password resetting.""" <|body_1|> async def put(self)...
stack_v2_sparse_classes_36k_train_024006
15,662
permissive
[ { "docstring": "Render reset password form.", "name": "get", "signature": "async def get(self)" }, { "docstring": "Kick off user password resetting.", "name": "post", "signature": "async def post(self)" }, { "docstring": "Create a new password for user.", "name": "put", "...
3
stack_v2_sparse_classes_30k_train_018594
Implement the Python class `AuthResetPasswordView` described below. Class description: Class that includes functionality for user password resetting. Method signatures and docstrings: - async def get(self): Render reset password form. - async def post(self): Kick off user password resetting. - async def put(self): Cr...
Implement the Python class `AuthResetPasswordView` described below. Class description: Class that includes functionality for user password resetting. Method signatures and docstrings: - async def get(self): Render reset password form. - async def post(self): Kick off user password resetting. - async def put(self): Cr...
16b7154188f08b33f84d88caea217673cf989b2b
<|skeleton|> class AuthResetPasswordView: """Class that includes functionality for user password resetting.""" async def get(self): """Render reset password form.""" <|body_0|> async def post(self): """Kick off user password resetting.""" <|body_1|> async def put(self)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AuthResetPasswordView: """Class that includes functionality for user password resetting.""" async def get(self): """Render reset password form.""" try: reset_password_code = self.request.query['reset_password_code'] except KeyError: return make_response(suc...
the_stack_v2_python_sparse
server/app/api/auth.py
SpentlessInc/spentless-server
train
0
3ac688259da227071652034e0acaf2acf1f7fc31
[ "self.capacity = capacity\nself.map = {}\nself.cache = LinkedList()", "if key in self.map:\n node = self.map[key]\n self.cache.remove(node)\n self.cache.append(node)\n return node.value\nreturn -1", "if key not in self.map:\n if len(self.cache) == self.capacity:\n node = self.cache.pop()\n...
<|body_start_0|> self.capacity = capacity self.map = {} self.cache = LinkedList() <|end_body_0|> <|body_start_1|> if key in self.map: node = self.map[key] self.cache.remove(node) self.cache.append(node) return node.value return -1 ...
LRUCache
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k_train_024007
2,543
permissive
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: void", "name": "pu...
3
stack_v2_sparse_classes_30k_train_015249
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void <|sk...
ba84c192fb9995dd48ddc6d81c3153488dd3c698
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.capacity = capacity self.map = {} self.cache = LinkedList() def get(self, key): """:type key: int :rtype: int""" if key in self.map: node = self.map[key] self.cac...
the_stack_v2_python_sparse
Python/lru-cache.py
phucle2411/LeetCode
train
0
343f0a9fa219c9a2282edb13ac120fcdda76d6a4
[ "try:\n blockchain_name = blockchain_name.strip()\n if not blockchain_name:\n raise ValueError(\"Blockchain name can't be empty\")\n args = [NetworkController.MULTICHAIN_ARG, blockchain_name, NetworkController.GET_PEER_INFO_ARG]\n output = run(args, check=True, capture_output=True)\n json_peer...
<|body_start_0|> try: blockchain_name = blockchain_name.strip() if not blockchain_name: raise ValueError("Blockchain name can't be empty") args = [NetworkController.MULTICHAIN_ARG, blockchain_name, NetworkController.GET_PEER_INFO_ARG] output = run(...
NetworkController
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NetworkController: def get_peer_info(blockchain_name: str): """Returns information about the other nodes to which this node is connected. The main information that is returned is: "lastsend": (numeric) The date and time of the last send "lastrecv": (numeric) The data and time of the last...
stack_v2_sparse_classes_36k_train_024008
3,429
permissive
[ { "docstring": "Returns information about the other nodes to which this node is connected. The main information that is returned is: \"lastsend\": (numeric) The date and time of the last send \"lastrecv\": (numeric) The data and time of the last receive \"bytessent\": (numeric) The total bytes sent \"bytesrecv\...
2
stack_v2_sparse_classes_30k_train_007004
Implement the Python class `NetworkController` described below. Class description: Implement the NetworkController class. Method signatures and docstrings: - def get_peer_info(blockchain_name: str): Returns information about the other nodes to which this node is connected. The main information that is returned is: "l...
Implement the Python class `NetworkController` described below. Class description: Implement the NetworkController class. Method signatures and docstrings: - def get_peer_info(blockchain_name: str): Returns information about the other nodes to which this node is connected. The main information that is returned is: "l...
6be199fcaf836415b7d32ffb2cee911a9d600395
<|skeleton|> class NetworkController: def get_peer_info(blockchain_name: str): """Returns information about the other nodes to which this node is connected. The main information that is returned is: "lastsend": (numeric) The date and time of the last send "lastrecv": (numeric) The data and time of the last...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NetworkController: def get_peer_info(blockchain_name: str): """Returns information about the other nodes to which this node is connected. The main information that is returned is: "lastsend": (numeric) The date and time of the last send "lastrecv": (numeric) The data and time of the last receive "byte...
the_stack_v2_python_sparse
app/models/monitor/network_controller.py
talos-org/server
train
1
30d0b9f2447060de0572827bbd2cda6b7d967d91
[ "if name in ['width', 'height'] and name not in self.varNames():\n if hasOpenImageIO:\n imageInput = OpenImageIO.ImageInput.open(self.pathHolder().path())\n if imageInput is None:\n raise OiioReadFileError(\"Can't read information from file:\\n{}\".format(self.pathHolder().path()))\n ...
<|body_start_0|> if name in ['width', 'height'] and name not in self.varNames(): if hasOpenImageIO: imageInput = OpenImageIO.ImageInput.open(self.pathHolder().path()) if imageInput is None: raise OiioReadFileError("Can't read information from file:...
Open image io crawler.
Oiio
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Oiio: """Open image io crawler.""" def var(self, name): """Return var value using lazy loading implementation for width and height.""" <|body_0|> def __getWidthHeight(self): """Query width and height using ffprobe and set them as crawler variables.""" <|b...
stack_v2_sparse_classes_36k_train_024009
2,210
permissive
[ { "docstring": "Return var value using lazy loading implementation for width and height.", "name": "var", "signature": "def var(self, name)" }, { "docstring": "Query width and height using ffprobe and set them as crawler variables.", "name": "__getWidthHeight", "signature": "def __getWid...
2
stack_v2_sparse_classes_30k_train_010776
Implement the Python class `Oiio` described below. Class description: Open image io crawler. Method signatures and docstrings: - def var(self, name): Return var value using lazy loading implementation for width and height. - def __getWidthHeight(self): Query width and height using ffprobe and set them as crawler vari...
Implement the Python class `Oiio` described below. Class description: Open image io crawler. Method signatures and docstrings: - def var(self, name): Return var value using lazy loading implementation for width and height. - def __getWidthHeight(self): Query width and height using ffprobe and set them as crawler vari...
0b1dc1f17b025f6b37c9a3cf5753a46cbbcd36ba
<|skeleton|> class Oiio: """Open image io crawler.""" def var(self, name): """Return var value using lazy loading implementation for width and height.""" <|body_0|> def __getWidthHeight(self): """Query width and height using ffprobe and set them as crawler variables.""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Oiio: """Open image io crawler.""" def var(self, name): """Return var value using lazy loading implementation for width and height.""" if name in ['width', 'height'] and name not in self.varNames(): if hasOpenImageIO: imageInput = OpenImageIO.ImageInput.open(se...
the_stack_v2_python_sparse
src/lib/centipede/Crawler/Fs/Image/Oiio.py
ramgopal99/centipede
train
0
71a38762bd4415f29a7bab2ea5df45fcfd2b2736
[ "mock_index.search.side_effect = RuntimeError\nresponse, status_code, _ = health_check()\nself.assertEqual(response, 'DOWN', 'Response content should be DOWN')\nself.assertEqual(status_code, HTTPStatus.INTERNAL_SERVER_ERROR, 'Should return 500 status code.')", "mock_index.search.return_value = {'metadata': {}, 'r...
<|body_start_0|> mock_index.search.side_effect = RuntimeError response, status_code, _ = health_check() self.assertEqual(response, 'DOWN', 'Response content should be DOWN') self.assertEqual(status_code, HTTPStatus.INTERNAL_SERVER_ERROR, 'Should return 500 status code.') <|end_body_0|> ...
Tests for :func:`.health_check`.
TestHealthCheck
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestHealthCheck: """Tests for :func:`.health_check`.""" def test_index_is_down(self, mock_index): """Test returns 'DOWN' + status 500 when index raises an exception.""" <|body_0|> def test_index_returns_no_result(self, mock_index): """Test returns 'DOWN' + status...
stack_v2_sparse_classes_36k_train_024010
3,341
permissive
[ { "docstring": "Test returns 'DOWN' + status 500 when index raises an exception.", "name": "test_index_is_down", "signature": "def test_index_is_down(self, mock_index)" }, { "docstring": "Test returns 'DOWN' + status 500 when index returns no results.", "name": "test_index_returns_no_result"...
3
stack_v2_sparse_classes_30k_test_000594
Implement the Python class `TestHealthCheck` described below. Class description: Tests for :func:`.health_check`. Method signatures and docstrings: - def test_index_is_down(self, mock_index): Test returns 'DOWN' + status 500 when index raises an exception. - def test_index_returns_no_result(self, mock_index): Test re...
Implement the Python class `TestHealthCheck` described below. Class description: Tests for :func:`.health_check`. Method signatures and docstrings: - def test_index_is_down(self, mock_index): Test returns 'DOWN' + status 500 when index raises an exception. - def test_index_returns_no_result(self, mock_index): Test re...
e48f74bb2a858ae7bcf19d68f80cb6dcaa1f4761
<|skeleton|> class TestHealthCheck: """Tests for :func:`.health_check`.""" def test_index_is_down(self, mock_index): """Test returns 'DOWN' + status 500 when index raises an exception.""" <|body_0|> def test_index_returns_no_result(self, mock_index): """Test returns 'DOWN' + status...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestHealthCheck: """Tests for :func:`.health_check`.""" def test_index_is_down(self, mock_index): """Test returns 'DOWN' + status 500 when index raises an exception.""" mock_index.search.side_effect = RuntimeError response, status_code, _ = health_check() self.assertEqual(...
the_stack_v2_python_sparse
search/controllers/tests.py
arXiv/arxiv-search
train
54
7d2fce56982c6d54a4ede5b681be380be64e8019
[ "self.proof_type = proof_type\nself.proof_purpose = proof_purpose\nself.created = created\nself.domain = domain\nself.challenge = challenge\nself.credential_status = credential_status", "if isinstance(o, LDProofVCDetailOptions):\n return self.proof_type == o.proof_type and self.proof_purpose == o.proof_purpose...
<|body_start_0|> self.proof_type = proof_type self.proof_purpose = proof_purpose self.created = created self.domain = domain self.challenge = challenge self.credential_status = credential_status <|end_body_0|> <|body_start_1|> if isinstance(o, LDProofVCDetailOpti...
Linked Data Proof verifiable credential options model.
LDProofVCDetailOptions
[ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LDProofVCDetailOptions: """Linked Data Proof verifiable credential options model.""" def __init__(self, proof_type: Optional[str]=None, proof_purpose: Optional[str]=None, created: Optional[str]=None, domain: Optional[str]=None, challenge: Optional[str]=None, credential_status: Optional[dict]...
stack_v2_sparse_classes_36k_train_024011
4,481
permissive
[ { "docstring": "Initialize the LDProofVCDetailOptions instance.", "name": "__init__", "signature": "def __init__(self, proof_type: Optional[str]=None, proof_purpose: Optional[str]=None, created: Optional[str]=None, domain: Optional[str]=None, challenge: Optional[str]=None, credential_status: Optional[di...
2
stack_v2_sparse_classes_30k_train_000357
Implement the Python class `LDProofVCDetailOptions` described below. Class description: Linked Data Proof verifiable credential options model. Method signatures and docstrings: - def __init__(self, proof_type: Optional[str]=None, proof_purpose: Optional[str]=None, created: Optional[str]=None, domain: Optional[str]=No...
Implement the Python class `LDProofVCDetailOptions` described below. Class description: Linked Data Proof verifiable credential options model. Method signatures and docstrings: - def __init__(self, proof_type: Optional[str]=None, proof_purpose: Optional[str]=None, created: Optional[str]=None, domain: Optional[str]=No...
39cac36d8937ce84a9307ce100aaefb8bc05ec04
<|skeleton|> class LDProofVCDetailOptions: """Linked Data Proof verifiable credential options model.""" def __init__(self, proof_type: Optional[str]=None, proof_purpose: Optional[str]=None, created: Optional[str]=None, domain: Optional[str]=None, challenge: Optional[str]=None, credential_status: Optional[dict]...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LDProofVCDetailOptions: """Linked Data Proof verifiable credential options model.""" def __init__(self, proof_type: Optional[str]=None, proof_purpose: Optional[str]=None, created: Optional[str]=None, domain: Optional[str]=None, challenge: Optional[str]=None, credential_status: Optional[dict]=None) -> Non...
the_stack_v2_python_sparse
aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/models/cred_detail_options.py
hyperledger/aries-cloudagent-python
train
370
c04931815de578e33b98b3a2641e9b6ca6871b3b
[ "self.description = description\nself.vlan_id = vlan_id\nself.services = services", "if dictionary is None:\n return None\nvlan_id = dictionary.get('vlanId')\nservices = dictionary.get('services')\ndescription = dictionary.get('description')\nreturn cls(vlan_id, services, description)" ]
<|body_start_0|> self.description = description self.vlan_id = vlan_id self.services = services <|end_body_0|> <|body_start_1|> if dictionary is None: return None vlan_id = dictionary.get('vlanId') services = dictionary.get('services') description = d...
Implementation of the 'Rule3' model. TODO: type model description here. Attributes: description (string): A description for your Bonjour forwarding rule. Optional. vlan_id (string): The ID of the service VLAN. Required. services (list of ServiceEnum): A list of Bonjour services. At least one service must be specified. ...
Rule3Model
[ "MIT", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Rule3Model: """Implementation of the 'Rule3' model. TODO: type model description here. Attributes: description (string): A description for your Bonjour forwarding rule. Optional. vlan_id (string): The ID of the service VLAN. Required. services (list of ServiceEnum): A list of Bonjour services. At...
stack_v2_sparse_classes_36k_train_024012
2,165
permissive
[ { "docstring": "Constructor for the Rule3Model class", "name": "__init__", "signature": "def __init__(self, vlan_id=None, services=None, description=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the obj...
2
null
Implement the Python class `Rule3Model` described below. Class description: Implementation of the 'Rule3' model. TODO: type model description here. Attributes: description (string): A description for your Bonjour forwarding rule. Optional. vlan_id (string): The ID of the service VLAN. Required. services (list of Servi...
Implement the Python class `Rule3Model` described below. Class description: Implementation of the 'Rule3' model. TODO: type model description here. Attributes: description (string): A description for your Bonjour forwarding rule. Optional. vlan_id (string): The ID of the service VLAN. Required. services (list of Servi...
9894089eb013318243ae48869cc5130eb37f80c0
<|skeleton|> class Rule3Model: """Implementation of the 'Rule3' model. TODO: type model description here. Attributes: description (string): A description for your Bonjour forwarding rule. Optional. vlan_id (string): The ID of the service VLAN. Required. services (list of ServiceEnum): A list of Bonjour services. At...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Rule3Model: """Implementation of the 'Rule3' model. TODO: type model description here. Attributes: description (string): A description for your Bonjour forwarding rule. Optional. vlan_id (string): The ID of the service VLAN. Required. services (list of ServiceEnum): A list of Bonjour services. At least one se...
the_stack_v2_python_sparse
meraki_sdk/models/rule_3_model.py
RaulCatalano/meraki-python-sdk
train
1
ba805584c4da990698932610b1f9b705b0c1ab8b
[ "super(Separator, self).__init__()\nself.layer_norm = CumulativeLayerNorm(in_dim, eps=1e-08) if causal else nn.GroupNorm(1, in_dim, eps=1e-08)\nself.batch_norm = nn.Conv1d(in_dim, bn_dim, 1)\nself.receptive_field = 0\nself.dilated = dilated\nself.TCN = nn.ModuleList([])\nfor s in range(stack):\n for layer_id in ...
<|body_start_0|> super(Separator, self).__init__() self.layer_norm = CumulativeLayerNorm(in_dim, eps=1e-08) if causal else nn.GroupNorm(1, in_dim, eps=1e-08) self.batch_norm = nn.Conv1d(in_dim, bn_dim, 1) self.receptive_field = 0 self.dilated = dilated self.TCN = nn.Modul...
Separator Module Attributes: layer_norm {nn.Module} -- normalization layer either cLN or gLN batch_norm {nn.Module} -- 1 dimensionnal convolution layer receptive_field {int} -- receptive field of the module dilated {bool} -- is there dilation in the module conv layers ? TCN {nn.ModuleList} -- TCN module list (depth-wis...
Separator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Separator: """Separator Module Attributes: layer_norm {nn.Module} -- normalization layer either cLN or gLN batch_norm {nn.Module} -- 1 dimensionnal convolution layer receptive_field {int} -- receptive field of the module dilated {bool} -- is there dilation in the module conv layers ? TCN {nn.Modu...
stack_v2_sparse_classes_36k_train_024013
9,814
permissive
[ { "docstring": "Initialization Arguments: in_dim {int} -- input dimension out_dim {int} -- outpit dimension bn_dim {int} -- batch norm dimension hidden_dim {int} -- hidden dimension layers {int} -- number of layers per stack stack {int} -- number of stackes layers block Keyword Arguments: kernel {int} -- kernel...
2
stack_v2_sparse_classes_30k_train_010439
Implement the Python class `Separator` described below. Class description: Separator Module Attributes: layer_norm {nn.Module} -- normalization layer either cLN or gLN batch_norm {nn.Module} -- 1 dimensionnal convolution layer receptive_field {int} -- receptive field of the module dilated {bool} -- is there dilation i...
Implement the Python class `Separator` described below. Class description: Separator Module Attributes: layer_norm {nn.Module} -- normalization layer either cLN or gLN batch_norm {nn.Module} -- 1 dimensionnal convolution layer receptive_field {int} -- receptive field of the module dilated {bool} -- is there dilation i...
2415502fa8a38d4624b1c71e926f1723bdc8535c
<|skeleton|> class Separator: """Separator Module Attributes: layer_norm {nn.Module} -- normalization layer either cLN or gLN batch_norm {nn.Module} -- 1 dimensionnal convolution layer receptive_field {int} -- receptive field of the module dilated {bool} -- is there dilation in the module conv layers ? TCN {nn.Modu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Separator: """Separator Module Attributes: layer_norm {nn.Module} -- normalization layer either cLN or gLN batch_norm {nn.Module} -- 1 dimensionnal convolution layer receptive_field {int} -- receptive field of the module dilated {bool} -- is there dilation in the module conv layers ? TCN {nn.ModuleList} -- TC...
the_stack_v2_python_sparse
SPK_SP_Master/wass/convtasnet/modules.py
adamwhitakerwilson/speaker_separation
train
0
3b9223d319264e97597521239ae3efe167e2069e
[ "self.system = system\nself.devices = []\nself.group = {}", "if dev_name not in self.devices:\n self.devices.append(dev_name)\ngroup_name = self.system.__dict__[dev_name]._group\nif group_name not in self.group.keys():\n self.group[group_name] = {}", "if dev_name not in self.devices:\n self.system.Log....
<|body_start_0|> self.system = system self.devices = [] self.group = {} <|end_body_0|> <|body_start_1|> if dev_name not in self.devices: self.devices.append(dev_name) group_name = self.system.__dict__[dev_name]._group if group_name not in self.group.keys(): ...
Device Manager class. Maintains the loaded model list, groups and categories
DevMan
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DevMan: """Device Manager class. Maintains the loaded model list, groups and categories""" def __init__(self, system=None): """constructor for DevMan class""" <|body_0|> def register_device(self, dev_name): """register a device to the device list""" <|bod...
stack_v2_sparse_classes_36k_train_024014
1,921
permissive
[ { "docstring": "constructor for DevMan class", "name": "__init__", "signature": "def __init__(self, system=None)" }, { "docstring": "register a device to the device list", "name": "register_device", "signature": "def register_device(self, dev_name)" }, { "docstring": "register a ...
4
stack_v2_sparse_classes_30k_train_000315
Implement the Python class `DevMan` described below. Class description: Device Manager class. Maintains the loaded model list, groups and categories Method signatures and docstrings: - def __init__(self, system=None): constructor for DevMan class - def register_device(self, dev_name): register a device to the device ...
Implement the Python class `DevMan` described below. Class description: Device Manager class. Maintains the loaded model list, groups and categories Method signatures and docstrings: - def __init__(self, system=None): constructor for DevMan class - def register_device(self, dev_name): register a device to the device ...
769afa0ad85daf7a41d1434d44a47a72397e3627
<|skeleton|> class DevMan: """Device Manager class. Maintains the loaded model list, groups and categories""" def __init__(self, system=None): """constructor for DevMan class""" <|body_0|> def register_device(self, dev_name): """register a device to the device list""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DevMan: """Device Manager class. Maintains the loaded model list, groups and categories""" def __init__(self, system=None): """constructor for DevMan class""" self.system = system self.devices = [] self.group = {} def register_device(self, dev_name): """regist...
the_stack_v2_python_sparse
andes/variables/devman.py
buaaqq/andes
train
1
c0f0133a3e0145e891086ec9b63bfa05c8c66bfd
[ "super(ChassisCharmOperationTest, cls).setUpClass()\ncls.services = ['ovn-controller']\nif cls.application_name == 'ovn-chassis':\n principal_app_name = 'magpie'\nelse:\n principal_app_name = cls.application_name\nsource = zaza.model.get_application_config(principal_app_name)['source']['value']\nlogging.info(...
<|body_start_0|> super(ChassisCharmOperationTest, cls).setUpClass() cls.services = ['ovn-controller'] if cls.application_name == 'ovn-chassis': principal_app_name = 'magpie' else: principal_app_name = cls.application_name source = zaza.model.get_applicatio...
OVN Chassis Charm operation tests.
ChassisCharmOperationTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChassisCharmOperationTest: """OVN Chassis Charm operation tests.""" def setUpClass(cls): """Run class setup for OVN Chassis charm operation tests.""" <|body_0|> def test_prefer_chassis_as_gw(self): """Confirm effect of prefer-chassis-as-gw configuration option.""...
stack_v2_sparse_classes_36k_train_024015
37,617
permissive
[ { "docstring": "Run class setup for OVN Chassis charm operation tests.", "name": "setUpClass", "signature": "def setUpClass(cls)" }, { "docstring": "Confirm effect of prefer-chassis-as-gw configuration option.", "name": "test_prefer_chassis_as_gw", "signature": "def test_prefer_chassis_a...
3
stack_v2_sparse_classes_30k_train_004007
Implement the Python class `ChassisCharmOperationTest` described below. Class description: OVN Chassis Charm operation tests. Method signatures and docstrings: - def setUpClass(cls): Run class setup for OVN Chassis charm operation tests. - def test_prefer_chassis_as_gw(self): Confirm effect of prefer-chassis-as-gw co...
Implement the Python class `ChassisCharmOperationTest` described below. Class description: OVN Chassis Charm operation tests. Method signatures and docstrings: - def setUpClass(cls): Run class setup for OVN Chassis charm operation tests. - def test_prefer_chassis_as_gw(self): Confirm effect of prefer-chassis-as-gw co...
3b17ad9d97c57b6e62797d4e3333e4b83e43a447
<|skeleton|> class ChassisCharmOperationTest: """OVN Chassis Charm operation tests.""" def setUpClass(cls): """Run class setup for OVN Chassis charm operation tests.""" <|body_0|> def test_prefer_chassis_as_gw(self): """Confirm effect of prefer-chassis-as-gw configuration option.""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChassisCharmOperationTest: """OVN Chassis Charm operation tests.""" def setUpClass(cls): """Run class setup for OVN Chassis charm operation tests.""" super(ChassisCharmOperationTest, cls).setUpClass() cls.services = ['ovn-controller'] if cls.application_name == 'ovn-chassi...
the_stack_v2_python_sparse
zaza/openstack/charm_tests/ovn/tests.py
openstack-charmers/zaza-openstack-tests
train
7
3c701d9ad341d6e5509ba1908d9d574498b111dd
[ "for i in range(len(nums) - 1):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]\nreturn []", "d = {num: str(i) for i, num in enumerate(nums)}\nfor i, num in enumerate(nums):\n if target - num in d and int(d[target - num]) != i:\n return [i, int(...
<|body_start_0|> for i in range(len(nums) - 1): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j] return [] <|end_body_0|> <|body_start_1|> d = {num: str(i) for i, num in enumerate(nums)} for i, num in enumera...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: """暴力""" <|body_0|> def twoSum1(self, nums: List[int], target: int) -> List[int]: """字典实现O(1)查找""" <|body_1|> def twoSum2(self, nums: List[int], target: int) -> List[int]: """...
stack_v2_sparse_classes_36k_train_024016
1,538
no_license
[ { "docstring": "暴力", "name": "twoSum", "signature": "def twoSum(self, nums: List[int], target: int) -> List[int]" }, { "docstring": "字典实现O(1)查找", "name": "twoSum1", "signature": "def twoSum1(self, nums: List[int], target: int) -> List[int]" }, { "docstring": "更优化的写法", "name":...
3
stack_v2_sparse_classes_30k_train_010303
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum(self, nums: List[int], target: int) -> List[int]: 暴力 - def twoSum1(self, nums: List[int], target: int) -> List[int]: 字典实现O(1)查找 - def twoSum2(self, nums: List[int], ta...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum(self, nums: List[int], target: int) -> List[int]: 暴力 - def twoSum1(self, nums: List[int], target: int) -> List[int]: 字典实现O(1)查找 - def twoSum2(self, nums: List[int], ta...
ff7fe189ceaba761cbc8732781a865d597a6bf9f
<|skeleton|> class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: """暴力""" <|body_0|> def twoSum1(self, nums: List[int], target: int) -> List[int]: """字典实现O(1)查找""" <|body_1|> def twoSum2(self, nums: List[int], target: int) -> List[int]: """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: """暴力""" for i in range(len(nums) - 1): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j] return [] def twoSum1(self, nums: List[int...
the_stack_v2_python_sparse
2020.01.08-1.py
Narcissus7/LeetCode
train
0
8099d713ddfe3b87a55dae24e9181a76187e7a2b
[ "for cat, urlpart in category_mapping.items():\n self.category = cat\n url = '{}{}'.format(self.ROOT_CAT_URL, urlpart)\n yield scrapy.Request(url, meta={'_ours': {'category': cat}})", "links = set(response.css('.mw-category ul li a::attr(href)').extract())\nmeta = response.meta['_ours']\nfor rellink in l...
<|body_start_0|> for cat, urlpart in category_mapping.items(): self.category = cat url = '{}{}'.format(self.ROOT_CAT_URL, urlpart) yield scrapy.Request(url, meta={'_ours': {'category': cat}}) <|end_body_0|> <|body_start_1|> links = set(response.css('.mw-category ul l...
Scrapes any wikipedia category page.
WikipediaCategoryScraper
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WikipediaCategoryScraper: """Scrapes any wikipedia category page.""" def start_requests(self): """Determine which category starting url to run.""" <|body_0|> def parse(self, response): """Parse the response of each list category.""" <|body_1|> def pa...
stack_v2_sparse_classes_36k_train_024017
2,111
permissive
[ { "docstring": "Determine which category starting url to run.", "name": "start_requests", "signature": "def start_requests(self)" }, { "docstring": "Parse the response of each list category.", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "Parse a si...
3
stack_v2_sparse_classes_30k_train_004752
Implement the Python class `WikipediaCategoryScraper` described below. Class description: Scrapes any wikipedia category page. Method signatures and docstrings: - def start_requests(self): Determine which category starting url to run. - def parse(self, response): Parse the response of each list category. - def parse_...
Implement the Python class `WikipediaCategoryScraper` described below. Class description: Scrapes any wikipedia category page. Method signatures and docstrings: - def start_requests(self): Determine which category starting url to run. - def parse(self, response): Parse the response of each list category. - def parse_...
8515fcc4c86ef0a96f34278d90419e5fad2b48d3
<|skeleton|> class WikipediaCategoryScraper: """Scrapes any wikipedia category page.""" def start_requests(self): """Determine which category starting url to run.""" <|body_0|> def parse(self, response): """Parse the response of each list category.""" <|body_1|> def pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WikipediaCategoryScraper: """Scrapes any wikipedia category page.""" def start_requests(self): """Determine which category starting url to run.""" for cat, urlpart in category_mapping.items(): self.category = cat url = '{}{}'.format(self.ROOT_CAT_URL, urlpart) ...
the_stack_v2_python_sparse
plantstuff/scraping/scrapers/spiders/wikipedia.py
christabor/plantstuff
train
8
7ae090e3c40acbc3d2a58e93bb33a144ce09e380
[ "Agent_Base.__init__(self)\nself.value_state = np.zeros([num_car_max, num_car_max])\nself.posibility = 1 / (num_action * 2 + 1)\nself.posibility_state = self.posibility * np.ones([num_car_max, num_car_max, num_action * 2 + 1])\nself.gamma = gamma\nself.action = None\nself.state_old = None", "self.state_old = stat...
<|body_start_0|> Agent_Base.__init__(self) self.value_state = np.zeros([num_car_max, num_car_max]) self.posibility = 1 / (num_action * 2 + 1) self.posibility_state = self.posibility * np.ones([num_car_max, num_car_max, num_action * 2 + 1]) self.gamma = gamma self.action =...
this class is the policy iteration agent to find the car retal problem's optimal solution
PI_Agent
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PI_Agent: """this class is the policy iteration agent to find the car retal problem's optimal solution""" def __init__(self, num_car_max, num_action, gamma): """init the data arg: num_action: int, the num of the action num_cars_max: int, the max num of the cars that can sotp in one p...
stack_v2_sparse_classes_36k_train_024018
2,569
no_license
[ { "docstring": "init the data arg: num_action: int, the num of the action num_cars_max: int, the max num of the cars that can sotp in one place gamma: float,0-1, the discount of the last state's value", "name": "__init__", "signature": "def __init__(self, num_car_max, num_action, gamma)" }, { "d...
3
stack_v2_sparse_classes_30k_train_012188
Implement the Python class `PI_Agent` described below. Class description: this class is the policy iteration agent to find the car retal problem's optimal solution Method signatures and docstrings: - def __init__(self, num_car_max, num_action, gamma): init the data arg: num_action: int, the num of the action num_cars...
Implement the Python class `PI_Agent` described below. Class description: this class is the policy iteration agent to find the car retal problem's optimal solution Method signatures and docstrings: - def __init__(self, num_car_max, num_action, gamma): init the data arg: num_action: int, the num of the action num_cars...
180cc4d6370953e52b02822e7f7b54030ba656fa
<|skeleton|> class PI_Agent: """this class is the policy iteration agent to find the car retal problem's optimal solution""" def __init__(self, num_car_max, num_action, gamma): """init the data arg: num_action: int, the num of the action num_cars_max: int, the max num of the cars that can sotp in one p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PI_Agent: """this class is the policy iteration agent to find the car retal problem's optimal solution""" def __init__(self, num_car_max, num_action, gamma): """init the data arg: num_action: int, the num of the action num_cars_max: int, the max num of the cars that can sotp in one place gamma: f...
the_stack_v2_python_sparse
car_rental/pi_agent.py
DKuan/Reinforcement_Learning2018
train
0
48b1f53ee9faece58d8484e2bc6966c61088fc2a
[ "if not landscape:\n return 0\nnumOfLines = len(landscape)\nnumOfColumns = len(landscape[0])\nnumOfIslands = 0\nfor i in range(numOfLines):\n for j in range(numOfColumns):\n if landscape[i][j] == 1:\n numOfIslands += 1\n self.eraseIsland(landscape, i, j, numOfLines, numOfColumns)\...
<|body_start_0|> if not landscape: return 0 numOfLines = len(landscape) numOfColumns = len(landscape[0]) numOfIslands = 0 for i in range(numOfLines): for j in range(numOfColumns): if landscape[i][j] == 1: numOfIslands +=...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countIslands(self, landscape): """:type landscape: List[List[int]] :rtype: int""" <|body_0|> def eraseIsland(self, landscape, x, y, xBorder, yBorder): """:type landscape: List[List[int]], x: int, y: int, xBorder: int, yBorder: int :rtype: None""" ...
stack_v2_sparse_classes_36k_train_024019
1,407
no_license
[ { "docstring": ":type landscape: List[List[int]] :rtype: int", "name": "countIslands", "signature": "def countIslands(self, landscape)" }, { "docstring": ":type landscape: List[List[int]], x: int, y: int, xBorder: int, yBorder: int :rtype: None", "name": "eraseIsland", "signature": "def ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countIslands(self, landscape): :type landscape: List[List[int]] :rtype: int - def eraseIsland(self, landscape, x, y, xBorder, yBorder): :type landscape: List[List[int]], x: i...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countIslands(self, landscape): :type landscape: List[List[int]] :rtype: int - def eraseIsland(self, landscape, x, y, xBorder, yBorder): :type landscape: List[List[int]], x: i...
fa624b702129fa3efd6997791e4cd37c420e114e
<|skeleton|> class Solution: def countIslands(self, landscape): """:type landscape: List[List[int]] :rtype: int""" <|body_0|> def eraseIsland(self, landscape, x, y, xBorder, yBorder): """:type landscape: List[List[int]], x: int, y: int, xBorder: int, yBorder: int :rtype: None""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def countIslands(self, landscape): """:type landscape: List[List[int]] :rtype: int""" if not landscape: return 0 numOfLines = len(landscape) numOfColumns = len(landscape[0]) numOfIslands = 0 for i in range(numOfLines): for j in ...
the_stack_v2_python_sparse
p53/p53.py
zois-tasoulas/DailyInterviewPro
train
0
bb2b3cc6a66922612ff05e4ef2f2570d560087c1
[ "if not is_exe(exe_path):\n msg = '{0} is not an executable'.format(exe_path)\n raise NotExecutableError(msg)\nself._exe_path = exe_path", "self.__build_cmd(infile, outfile)\nif dry_run:\n results = Results(self._cmd, self._outfilename, None, None)\nelse:\n pipe = subprocess.run(self._cmd, shell=True,...
<|body_start_0|> if not is_exe(exe_path): msg = '{0} is not an executable'.format(exe_path) raise NotExecutableError(msg) self._exe_path = exe_path <|end_body_0|> <|body_start_1|> self.__build_cmd(infile, outfile) if dry_run: results = Results(self._c...
Class for working with MUSCLE
Muscle
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Muscle: """Class for working with MUSCLE""" def __init__(self, exe_path): """Instantiate with location of executable""" <|body_0|> def run(self, infile, outfile=None, dry_run=False): """Run MUSCLE on the single passed file Writes the alignment result alongside th...
stack_v2_sparse_classes_36k_train_024020
2,375
permissive
[ { "docstring": "Instantiate with location of executable", "name": "__init__", "signature": "def __init__(self, exe_path)" }, { "docstring": "Run MUSCLE on the single passed file Writes the alignment result alongside the input file Returns a tuple of output file, and the STDOUT, STDERR returned b...
3
null
Implement the Python class `Muscle` described below. Class description: Class for working with MUSCLE Method signatures and docstrings: - def __init__(self, exe_path): Instantiate with location of executable - def run(self, infile, outfile=None, dry_run=False): Run MUSCLE on the single passed file Writes the alignmen...
Implement the Python class `Muscle` described below. Class description: Class for working with MUSCLE Method signatures and docstrings: - def __init__(self, exe_path): Instantiate with location of executable - def run(self, infile, outfile=None, dry_run=False): Run MUSCLE on the single passed file Writes the alignmen...
a3c64198aad3709a5c4d969f48ae0af11fdc25db
<|skeleton|> class Muscle: """Class for working with MUSCLE""" def __init__(self, exe_path): """Instantiate with location of executable""" <|body_0|> def run(self, infile, outfile=None, dry_run=False): """Run MUSCLE on the single passed file Writes the alignment result alongside th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Muscle: """Class for working with MUSCLE""" def __init__(self, exe_path): """Instantiate with location of executable""" if not is_exe(exe_path): msg = '{0} is not an executable'.format(exe_path) raise NotExecutableError(msg) self._exe_path = exe_path d...
the_stack_v2_python_sparse
metapy/pycits/muscle.py
peterthorpe5/public_scripts
train
35
5240b1723e8848cc18f51f196f9265a821eb5062
[ "if not issubclass(enum, IntEnum):\n raise TypeError('enum must be an IntEnum subclass')\nself._enum = enum\nif default is None:\n self._default = None\nelif isinstance(default, enum):\n self._default = default\nelif isinstance(default, int):\n self._default = enum(int)\nelse:\n raise TypeError('defa...
<|body_start_0|> if not issubclass(enum, IntEnum): raise TypeError('enum must be an IntEnum subclass') self._enum = enum if default is None: self._default = None elif isinstance(default, enum): self._default = default elif isinstance(default, i...
Class to create a dynamic validator for IntEnum classes
IntEnumValidator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IntEnumValidator: """Class to create a dynamic validator for IntEnum classes""" def __init__(self, enum, default=None): """Parameters ---------- enum : :py:class:`enum.IntEnum` base enum class for this validator default : :py:class:`enum.IntEnum` | int | None default attribute of the...
stack_v2_sparse_classes_36k_train_024021
7,524
permissive
[ { "docstring": "Parameters ---------- enum : :py:class:`enum.IntEnum` base enum class for this validator default : :py:class:`enum.IntEnum` | int | None default attribute of the enum Raises ------ TypeError if enum is not an :py:class:`enum.IntEnum` class TypeError if default parameter is of invalid type", ...
3
stack_v2_sparse_classes_30k_train_007051
Implement the Python class `IntEnumValidator` described below. Class description: Class to create a dynamic validator for IntEnum classes Method signatures and docstrings: - def __init__(self, enum, default=None): Parameters ---------- enum : :py:class:`enum.IntEnum` base enum class for this validator default : :py:c...
Implement the Python class `IntEnumValidator` described below. Class description: Class to create a dynamic validator for IntEnum classes Method signatures and docstrings: - def __init__(self, enum, default=None): Parameters ---------- enum : :py:class:`enum.IntEnum` base enum class for this validator default : :py:c...
ab5377e3b16f1920d4d9ada443e1e9059715f0fb
<|skeleton|> class IntEnumValidator: """Class to create a dynamic validator for IntEnum classes""" def __init__(self, enum, default=None): """Parameters ---------- enum : :py:class:`enum.IntEnum` base enum class for this validator default : :py:class:`enum.IntEnum` | int | None default attribute of the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IntEnumValidator: """Class to create a dynamic validator for IntEnum classes""" def __init__(self, enum, default=None): """Parameters ---------- enum : :py:class:`enum.IntEnum` base enum class for this validator default : :py:class:`enum.IntEnum` | int | None default attribute of the enum Raises ...
the_stack_v2_python_sparse
PyPoE/shared/config/validator.py
Openarl/PyPoE
train
16
421a1c1ebb1125d9a8880968ae01ca61eede6773
[ "super().__init__()\n\ndef block(in_feat, out_feat, normalize=True):\n layers = [torch.nn.Linear(in_feat, out_feat)]\n if normalize:\n layers.append(torch.nn.BatchNorm1d(out_feat, 0.8))\n layers.append(torch.nn.LeakyReLU(0.2, inplace=True))\n return layers\nself.model = torch.nn.Sequential(*block...
<|body_start_0|> super().__init__() def block(in_feat, out_feat, normalize=True): layers = [torch.nn.Linear(in_feat, out_feat)] if normalize: layers.append(torch.nn.BatchNorm1d(out_feat, 0.8)) layers.append(torch.nn.LeakyReLU(0.2, inplace=True)) ...
A simple generative network
Generator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Generator: """A simple generative network""" def __init__(self, img_shape, latent_dim): """Parameters ---------- img_shape : tuple the shape of the images to generate (including channels, excluding batch dimension) latent_dim : int size of the latent noise dimension""" <|body...
stack_v2_sparse_classes_36k_train_024022
2,650
permissive
[ { "docstring": "Parameters ---------- img_shape : tuple the shape of the images to generate (including channels, excluding batch dimension) latent_dim : int size of the latent noise dimension", "name": "__init__", "signature": "def __init__(self, img_shape, latent_dim)" }, { "docstring": "Feeds ...
2
stack_v2_sparse_classes_30k_train_002380
Implement the Python class `Generator` described below. Class description: A simple generative network Method signatures and docstrings: - def __init__(self, img_shape, latent_dim): Parameters ---------- img_shape : tuple the shape of the images to generate (including channels, excluding batch dimension) latent_dim :...
Implement the Python class `Generator` described below. Class description: A simple generative network Method signatures and docstrings: - def __init__(self, img_shape, latent_dim): Parameters ---------- img_shape : tuple the shape of the images to generate (including channels, excluding batch dimension) latent_dim :...
1078f5030b8aac2bf022daf5fa14d66f74c3c893
<|skeleton|> class Generator: """A simple generative network""" def __init__(self, img_shape, latent_dim): """Parameters ---------- img_shape : tuple the shape of the images to generate (including channels, excluding batch dimension) latent_dim : int size of the latent noise dimension""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Generator: """A simple generative network""" def __init__(self, img_shape, latent_dim): """Parameters ---------- img_shape : tuple the shape of the images to generate (including channels, excluding batch dimension) latent_dim : int size of the latent noise dimension""" super().__init__() ...
the_stack_v2_python_sparse
dlutils/models/gans/wasserstein/models.py
justusschock/dl-utils
train
15
5ae84fcccbda78d095d76bc3a8c582fa17e68e84
[ "slow = fast = head\nwhile fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow is fast:\n break\nif not fast or not fast.next:\n return None\nwhile slow != head:\n slow = slow.next\n head = head.next\nreturn head", "slow = fast = head\nwhile fast and fast.next:\n s...
<|body_start_0|> slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow is fast: break if not fast or not fast.next: return None while slow != head: slow = slow.next ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def detectCycle(self, head): """Returns node where the cycle begins in the linked list, or None if there's no cycle. Time complexity: O(n). Space complexity: O(1), n is len(linked list).""" <|body_0|> def detectCycle(self, head): """More concise code versio...
stack_v2_sparse_classes_36k_train_024023
1,728
no_license
[ { "docstring": "Returns node where the cycle begins in the linked list, or None if there's no cycle. Time complexity: O(n). Space complexity: O(1), n is len(linked list).", "name": "detectCycle", "signature": "def detectCycle(self, head)" }, { "docstring": "More concise code version. Returns nod...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def detectCycle(self, head): Returns node where the cycle begins in the linked list, or None if there's no cycle. Time complexity: O(n). Space complexity: O(1), n is len(linked l...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def detectCycle(self, head): Returns node where the cycle begins in the linked list, or None if there's no cycle. Time complexity: O(n). Space complexity: O(1), n is len(linked l...
71b722ddfe8da04572e527b055cf8723d5c87bbf
<|skeleton|> class Solution: def detectCycle(self, head): """Returns node where the cycle begins in the linked list, or None if there's no cycle. Time complexity: O(n). Space complexity: O(1), n is len(linked list).""" <|body_0|> def detectCycle(self, head): """More concise code versio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def detectCycle(self, head): """Returns node where the cycle begins in the linked list, or None if there's no cycle. Time complexity: O(n). Space complexity: O(1), n is len(linked list).""" slow = fast = head while fast and fast.next: slow = slow.next ...
the_stack_v2_python_sparse
Linked_Lists/linked_list_cycle_2.py
vladn90/Algorithms
train
0
e30c5ddbcb322cb05cd077c16437e20f962c0124
[ "super(DatabaseWrapper, self).__init__(*args, **kwargs)\nops_cls = self.ops.__class__\nif not hasattr(ops_cls, 'binary_placeholder_sql'):\n from django.db.models.fields import BinaryField\n assert not hasattr(BinaryField, 'get_placeholder')\n ops_cls.binary_placeholder_sql = self._ops_binary_placeholder_sq...
<|body_start_0|> super(DatabaseWrapper, self).__init__(*args, **kwargs) ops_cls = self.ops.__class__ if not hasattr(ops_cls, 'binary_placeholder_sql'): from django.db.models.fields import BinaryField assert not hasattr(BinaryField, 'get_placeholder') ops_cls.b...
Database backend for MySQL. This is a specialized version of the standard Django MySQL database backend which adds backported compatibility fixes from newer versions of Django. Currently, this fixes an issue where contents going into a :py:class:`~django.db.models.BinaryField` could trigger a MySQL warning due to the b...
DatabaseWrapper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DatabaseWrapper: """Database backend for MySQL. This is a specialized version of the standard Django MySQL database backend which adds backported compatibility fixes from newer versions of Django. Currently, this fixes an issue where contents going into a :py:class:`~django.db.models.BinaryField`...
stack_v2_sparse_classes_36k_train_024024
3,962
no_license
[ { "docstring": "Initialize the database backend. Args: *args (tuple): Positional arguments for the backend. **kwargs (dict): Keyword arguments for the backend.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Return the placeholder format string for bin...
3
null
Implement the Python class `DatabaseWrapper` described below. Class description: Database backend for MySQL. This is a specialized version of the standard Django MySQL database backend which adds backported compatibility fixes from newer versions of Django. Currently, this fixes an issue where contents going into a :p...
Implement the Python class `DatabaseWrapper` described below. Class description: Database backend for MySQL. This is a specialized version of the standard Django MySQL database backend which adds backported compatibility fixes from newer versions of Django. Currently, this fixes an issue where contents going into a :p...
99ea69d80a3a393b0da4da3152ef26e808dd8487
<|skeleton|> class DatabaseWrapper: """Database backend for MySQL. This is a specialized version of the standard Django MySQL database backend which adds backported compatibility fixes from newer versions of Django. Currently, this fixes an issue where contents going into a :py:class:`~django.db.models.BinaryField`...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DatabaseWrapper: """Database backend for MySQL. This is a specialized version of the standard Django MySQL database backend which adds backported compatibility fixes from newer versions of Django. Currently, this fixes an issue where contents going into a :py:class:`~django.db.models.BinaryField` could trigge...
the_stack_v2_python_sparse
djblets/db/backends/mysql/base.py
chipx86/djblets
train
2
32cfffbc9e8b8e88e9c4cbbcd04ddcc6a58e643f
[ "user = User.objects.create_user(username=username, password=password)\nuser.groups.add(rol)\nreturn self.create(tipo=self.model.ADMINISTRATIVO, usuario=user, **kwargs)", "user = User.objects.create_user(username=username, password=password)\nuser.groups.add(rol)\nmedico = self.create(tipo=self.model.MEDICO, usua...
<|body_start_0|> user = User.objects.create_user(username=username, password=password) user.groups.add(rol) return self.create(tipo=self.model.ADMINISTRATIVO, usuario=user, **kwargs) <|end_body_0|> <|body_start_1|> user = User.objects.create_user(username=username, password=password) ...
Manager personalizado para el modelo Empleado.
EmpleadoManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmpleadoManager: """Manager personalizado para el modelo Empleado.""" def crear_empleado_administrativo(self, username, password, rol, **kwargs): """Permite crear un empleado administrativo""" <|body_0|> def crear_medico(self, username, password, rol, instituciones, **kw...
stack_v2_sparse_classes_36k_train_024025
2,324
no_license
[ { "docstring": "Permite crear un empleado administrativo", "name": "crear_empleado_administrativo", "signature": "def crear_empleado_administrativo(self, username, password, rol, **kwargs)" }, { "docstring": "Permite crear un empleado administrativo", "name": "crear_medico", "signature":...
2
null
Implement the Python class `EmpleadoManager` described below. Class description: Manager personalizado para el modelo Empleado. Method signatures and docstrings: - def crear_empleado_administrativo(self, username, password, rol, **kwargs): Permite crear un empleado administrativo - def crear_medico(self, username, pa...
Implement the Python class `EmpleadoManager` described below. Class description: Manager personalizado para el modelo Empleado. Method signatures and docstrings: - def crear_empleado_administrativo(self, username, password, rol, **kwargs): Permite crear un empleado administrativo - def crear_medico(self, username, pa...
b8f8df111432bfab537853ed8e8dbd4603e9707d
<|skeleton|> class EmpleadoManager: """Manager personalizado para el modelo Empleado.""" def crear_empleado_administrativo(self, username, password, rol, **kwargs): """Permite crear un empleado administrativo""" <|body_0|> def crear_medico(self, username, password, rol, instituciones, **kw...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EmpleadoManager: """Manager personalizado para el modelo Empleado.""" def crear_empleado_administrativo(self, username, password, rol, **kwargs): """Permite crear un empleado administrativo""" user = User.objects.create_user(username=username, password=password) user.groups.add(ro...
the_stack_v2_python_sparse
organizacional/managers.py
geovanniberdugo/medhis
train
0
2f8a5bb8f219fb8e4d1ee917bb35f56876c6dc43
[ "\"\"\"\n 1.find length of all string\n 2. Loop from smallest lenght string and pick charcter by character and compare them\n 3.if all the characters till now are same then add it to empty string\n 4. return if matching doesnot occur between character arra...
<|body_start_0|> """ 1.find length of all string 2. Loop from smallest lenght string and pick charcter by character and compare them 3.if all the characters till now are same then add it to empty string 4. return if ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestCommonPrefix(self, strs): """:type strs: List[str] :rtype: str""" <|body_0|> def longestCommonPrefix2(self, strs): """Vertical scanning algorithm.""" <|body_1|> <|end_skeleton|> <|body_start_0|> """ 1.fin...
stack_v2_sparse_classes_36k_train_024026
1,517
no_license
[ { "docstring": ":type strs: List[str] :rtype: str", "name": "longestCommonPrefix", "signature": "def longestCommonPrefix(self, strs)" }, { "docstring": "Vertical scanning algorithm.", "name": "longestCommonPrefix2", "signature": "def longestCommonPrefix2(self, strs)" } ]
2
stack_v2_sparse_classes_30k_train_014070
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str - def longestCommonPrefix2(self, strs): Vertical scanning algorithm.
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str - def longestCommonPrefix2(self, strs): Vertical scanning algorithm. <|skeleton|> class Solution: def...
bee7e3629f4b59fdc5223da91c66efc44f4dd262
<|skeleton|> class Solution: def longestCommonPrefix(self, strs): """:type strs: List[str] :rtype: str""" <|body_0|> def longestCommonPrefix2(self, strs): """Vertical scanning algorithm.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestCommonPrefix(self, strs): """:type strs: List[str] :rtype: str""" """ 1.find length of all string 2. Loop from smallest lenght string and pick charcter by character and compare them 3.if all the charac...
the_stack_v2_python_sparse
leetcode/easy/longestCommonPrefix.py
himanshush200599/codingPart
train
4
a6bcd0c1f4dabde45852ffb5ca6179d9005f5af2
[ "cols = [set() for _ in range(9)]\nfor row in range(9):\n if not row % 3:\n squares = (set(), set(), set())\n cur_row = set()\n for col in range(9):\n if board[row][col] == '.':\n continue\n for s in (cur_row, cols[col], squares[col // 3]):\n if board[row][col] in...
<|body_start_0|> cols = [set() for _ in range(9)] for row in range(9): if not row % 3: squares = (set(), set(), set()) cur_row = set() for col in range(9): if board[row][col] == '.': continue for s in...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isValidSudoku(self, board): """:type board: List[List[str]] :rtype: bool""" <|body_0|> def isValidSudoku(self, board): """:type board: List[List[str]] :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> cols = [set() for _ in ...
stack_v2_sparse_classes_36k_train_024027
1,311
no_license
[ { "docstring": ":type board: List[List[str]] :rtype: bool", "name": "isValidSudoku", "signature": "def isValidSudoku(self, board)" }, { "docstring": ":type board: List[List[str]] :rtype: bool", "name": "isValidSudoku", "signature": "def isValidSudoku(self, board)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isValidSudoku(self, board): :type board: List[List[str]] :rtype: bool - def isValidSudoku(self, board): :type board: List[List[str]] :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isValidSudoku(self, board): :type board: List[List[str]] :rtype: bool - def isValidSudoku(self, board): :type board: List[List[str]] :rtype: bool <|skeleton|> class Solution...
c27f19fac14b4acef8c631ad5569e1a5c29e9e1f
<|skeleton|> class Solution: def isValidSudoku(self, board): """:type board: List[List[str]] :rtype: bool""" <|body_0|> def isValidSudoku(self, board): """:type board: List[List[str]] :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isValidSudoku(self, board): """:type board: List[List[str]] :rtype: bool""" cols = [set() for _ in range(9)] for row in range(9): if not row % 3: squares = (set(), set(), set()) cur_row = set() for col in range(9): ...
the_stack_v2_python_sparse
leetcode/p0036 - Valid Sudoku.py
liseyko/CtCI
train
0
c00fe289eb2b02751a4404bf79361e1a4a5837bc
[ "try:\n sport = self.kwargs['sport']\nexcept KeyError:\n sport = 'nba'\nsite_sport_manager = sports.classes.SiteSportManager()\nteam_serializer_class = site_sport_manager.get_team_serializer_class(sport)\nreturn team_serializer_class", "try:\n sport = self.kwargs['sport']\nexcept KeyError:\n sport = '...
<|body_start_0|> try: sport = self.kwargs['sport'] except KeyError: sport = 'nba' site_sport_manager = sports.classes.SiteSportManager() team_serializer_class = site_sport_manager.get_team_serializer_class(sport) return team_serializer_class <|end_body_0|>...
Get the teams for the league teams for a sport.
LeagueTeamAPIView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LeagueTeamAPIView: """Get the teams for the league teams for a sport.""" def get_serializer_class(self): """use site sport manager to get the site_sport from the sport param""" <|body_0|> def get_queryset(self): """Return a QuerySet of the sports.<sport>.models.T...
stack_v2_sparse_classes_36k_train_024028
26,966
no_license
[ { "docstring": "use site sport manager to get the site_sport from the sport param", "name": "get_serializer_class", "signature": "def get_serializer_class(self)" }, { "docstring": "Return a QuerySet of the sports.<sport>.models.Team objects", "name": "get_queryset", "signature": "def get...
2
null
Implement the Python class `LeagueTeamAPIView` described below. Class description: Get the teams for the league teams for a sport. Method signatures and docstrings: - def get_serializer_class(self): use site sport manager to get the site_sport from the sport param - def get_queryset(self): Return a QuerySet of the sp...
Implement the Python class `LeagueTeamAPIView` described below. Class description: Get the teams for the league teams for a sport. Method signatures and docstrings: - def get_serializer_class(self): use site sport manager to get the site_sport from the sport param - def get_queryset(self): Return a QuerySet of the sp...
4796fa9d88b56f80def011e2b043ce595bfce8c4
<|skeleton|> class LeagueTeamAPIView: """Get the teams for the league teams for a sport.""" def get_serializer_class(self): """use site sport manager to get the site_sport from the sport param""" <|body_0|> def get_queryset(self): """Return a QuerySet of the sports.<sport>.models.T...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LeagueTeamAPIView: """Get the teams for the league teams for a sport.""" def get_serializer_class(self): """use site sport manager to get the site_sport from the sport param""" try: sport = self.kwargs['sport'] except KeyError: sport = 'nba' site_sp...
the_stack_v2_python_sparse
sports/views.py
nakamotohideyoshi/draftboard-web
train
0
bfcb2616c491d8ba0e893ad5f3c79aa9f45ba1f3
[ "if s == '':\n return ''\nss = s[::-1]\nfor i in range(len(s)):\n length = len(s) - i\n if ss[i:] == s[:length]:\n return ss + s[length:]", "if s == '':\n return ''\nss = s[::-1]\nfor i in range(len(s)):\n length = len(s) - i\n if s[i:] == ss[:length]:\n return s + ss[length:]", ...
<|body_start_0|> if s == '': return '' ss = s[::-1] for i in range(len(s)): length = len(s) - i if ss[i:] == s[:length]: return ss + s[length:] <|end_body_0|> <|body_start_1|> if s == '': return '' ss = s[::-1] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def shortestPalindrome_front(self, s: str) -> str: """暴力+串后加""" <|body_0|> def shortestPalindrome_behind(self, s: str) -> str: """暴力+串前加""" <|body_1|> def shortestPalindrome_advanced(self, s: str) -> str: """KMP 算法""" <|body_2|>...
stack_v2_sparse_classes_36k_train_024029
1,371
no_license
[ { "docstring": "暴力+串后加", "name": "shortestPalindrome_front", "signature": "def shortestPalindrome_front(self, s: str) -> str" }, { "docstring": "暴力+串前加", "name": "shortestPalindrome_behind", "signature": "def shortestPalindrome_behind(self, s: str) -> str" }, { "docstring": "KMP ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def shortestPalindrome_front(self, s: str) -> str: 暴力+串后加 - def shortestPalindrome_behind(self, s: str) -> str: 暴力+串前加 - def shortestPalindrome_advanced(self, s: str) -> str: KMP...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def shortestPalindrome_front(self, s: str) -> str: 暴力+串后加 - def shortestPalindrome_behind(self, s: str) -> str: 暴力+串前加 - def shortestPalindrome_advanced(self, s: str) -> str: KMP...
57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb
<|skeleton|> class Solution: def shortestPalindrome_front(self, s: str) -> str: """暴力+串后加""" <|body_0|> def shortestPalindrome_behind(self, s: str) -> str: """暴力+串前加""" <|body_1|> def shortestPalindrome_advanced(self, s: str) -> str: """KMP 算法""" <|body_2|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def shortestPalindrome_front(self, s: str) -> str: """暴力+串后加""" if s == '': return '' ss = s[::-1] for i in range(len(s)): length = len(s) - i if ss[i:] == s[:length]: return ss + s[length:] def shortestPalindro...
the_stack_v2_python_sparse
4_LEETCODE/11_Interview/网易/1_最短回文串.py
fzingithub/SwordRefers2Offer
train
1
1492bf743dc047775912780013abdc7a40967e4a
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn InvitedUserMessageInfo()", "from .recipient import Recipient\nfrom .recipient import Recipient\nfields: Dict[str, Callable[[Any], None]] = {'ccRecipients': lambda n: setattr(self, 'cc_recipients', n.get_collection_of_object_values(Reci...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return InvitedUserMessageInfo() <|end_body_0|> <|body_start_1|> from .recipient import Recipient from .recipient import Recipient fields: Dict[str, Callable[[Any], None]] = {'ccRecipien...
InvitedUserMessageInfo
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InvitedUserMessageInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitedUserMessageInfo: """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 ...
stack_v2_sparse_classes_36k_train_024030
3,574
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: InvitedUserMessageInfo", "name": "create_from_discriminator_value", "signature": "def create_from_discrimina...
3
stack_v2_sparse_classes_30k_train_000981
Implement the Python class `InvitedUserMessageInfo` described below. Class description: Implement the InvitedUserMessageInfo class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitedUserMessageInfo: Creates a new instance of the appropriate class b...
Implement the Python class `InvitedUserMessageInfo` described below. Class description: Implement the InvitedUserMessageInfo class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitedUserMessageInfo: Creates a new instance of the appropriate class b...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class InvitedUserMessageInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitedUserMessageInfo: """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 ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InvitedUserMessageInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitedUserMessageInfo: """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 Ret...
the_stack_v2_python_sparse
msgraph/generated/models/invited_user_message_info.py
microsoftgraph/msgraph-sdk-python
train
135
625a75bdb1290636b856394fe67b01093b214843
[ "s = db.session()\ntry:\n result = Folder.query.filter(or_(and_(Folder.is_sys == True, Folder.pid == pid), and_(Folder.is_sys == False, Folder.pid == pid, Folder.admin_id == admin_id))).order_by(Folder.id).all()\n return [value.to_json() for value in result]\nexcept Exception as e:\n print(e)\n return s...
<|body_start_0|> s = db.session() try: result = Folder.query.filter(or_(and_(Folder.is_sys == True, Folder.pid == pid), and_(Folder.is_sys == False, Folder.pid == pid, Folder.admin_id == admin_id))).order_by(Folder.id).all() return [value.to_json() for value in result] ex...
FolderModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FolderModel: def QueryFolderByParamRequest(self, pid, admin_id): """文件夹列表""" <|body_0|> def CreateFolderRequest(self, params): """新建文件夹""" <|body_1|> def ModifyFolderRequest(self, folder_id, params): """修改文件夹""" <|body_2|> def DelFol...
stack_v2_sparse_classes_36k_train_024031
2,905
permissive
[ { "docstring": "文件夹列表", "name": "QueryFolderByParamRequest", "signature": "def QueryFolderByParamRequest(self, pid, admin_id)" }, { "docstring": "新建文件夹", "name": "CreateFolderRequest", "signature": "def CreateFolderRequest(self, params)" }, { "docstring": "修改文件夹", "name": "Mo...
4
stack_v2_sparse_classes_30k_train_013051
Implement the Python class `FolderModel` described below. Class description: Implement the FolderModel class. Method signatures and docstrings: - def QueryFolderByParamRequest(self, pid, admin_id): 文件夹列表 - def CreateFolderRequest(self, params): 新建文件夹 - def ModifyFolderRequest(self, folder_id, params): 修改文件夹 - def Del...
Implement the Python class `FolderModel` described below. Class description: Implement the FolderModel class. Method signatures and docstrings: - def QueryFolderByParamRequest(self, pid, admin_id): 文件夹列表 - def CreateFolderRequest(self, params): 新建文件夹 - def ModifyFolderRequest(self, folder_id, params): 修改文件夹 - def Del...
62fe4b3e264176bb582a278c81814ed5ec13caec
<|skeleton|> class FolderModel: def QueryFolderByParamRequest(self, pid, admin_id): """文件夹列表""" <|body_0|> def CreateFolderRequest(self, params): """新建文件夹""" <|body_1|> def ModifyFolderRequest(self, folder_id, params): """修改文件夹""" <|body_2|> def DelFol...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FolderModel: def QueryFolderByParamRequest(self, pid, admin_id): """文件夹列表""" s = db.session() try: result = Folder.query.filter(or_(and_(Folder.is_sys == True, Folder.pid == pid), and_(Folder.is_sys == False, Folder.pid == pid, Folder.admin_id == admin_id))).order_by(Folder...
the_stack_v2_python_sparse
collection/v1/folder.py
huzidabanzhang/python-admin
train
32
2f529f3ddf7bf619c9adbd060d6bbbee550dc6d2
[ "url = 'https://www.youtube.com/watch?v=videoID'\nid = models.Publication().get_youtube_video_id(url)\nself.assertEqual(id, 'videoID')", "url = 'https://www.youtube.com/watch?v=videoID&feature=youtu.be'\nid = models.Publication().get_youtube_video_id(url)\nself.assertEqual(id, 'videoID')", "url = 'https://www.y...
<|body_start_0|> url = 'https://www.youtube.com/watch?v=videoID' id = models.Publication().get_youtube_video_id(url) self.assertEqual(id, 'videoID') <|end_body_0|> <|body_start_1|> url = 'https://www.youtube.com/watch?v=videoID&feature=youtu.be' id = models.Publication().get_you...
PublicationModelTestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PublicationModelTestCase: def test_get_youtube_video_id_with_v(self): """Extract Youtube video id from url with 'v' parameter""" <|body_0|> def test_get_youtube_video_id_with_multiple_parameters(self): """Extract Youtube video id from url with 'v' and other parameter...
stack_v2_sparse_classes_36k_train_024032
3,275
no_license
[ { "docstring": "Extract Youtube video id from url with 'v' parameter", "name": "test_get_youtube_video_id_with_v", "signature": "def test_get_youtube_video_id_with_v(self)" }, { "docstring": "Extract Youtube video id from url with 'v' and other parameters", "name": "test_get_youtube_video_id...
5
stack_v2_sparse_classes_30k_train_011542
Implement the Python class `PublicationModelTestCase` described below. Class description: Implement the PublicationModelTestCase class. Method signatures and docstrings: - def test_get_youtube_video_id_with_v(self): Extract Youtube video id from url with 'v' parameter - def test_get_youtube_video_id_with_multiple_par...
Implement the Python class `PublicationModelTestCase` described below. Class description: Implement the PublicationModelTestCase class. Method signatures and docstrings: - def test_get_youtube_video_id_with_v(self): Extract Youtube video id from url with 'v' parameter - def test_get_youtube_video_id_with_multiple_par...
347836d856c01b08fcd426cb676ab3c3e17237a6
<|skeleton|> class PublicationModelTestCase: def test_get_youtube_video_id_with_v(self): """Extract Youtube video id from url with 'v' parameter""" <|body_0|> def test_get_youtube_video_id_with_multiple_parameters(self): """Extract Youtube video id from url with 'v' and other parameter...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PublicationModelTestCase: def test_get_youtube_video_id_with_v(self): """Extract Youtube video id from url with 'v' parameter""" url = 'https://www.youtube.com/watch?v=videoID' id = models.Publication().get_youtube_video_id(url) self.assertEqual(id, 'videoID') def test_get...
the_stack_v2_python_sparse
backoffice/tests.py
nicolas-pantel/MiWo
train
0
d9d364f9b7086f945e2236ffdac438d52d111c8f
[ "len_A = len(A)\nsum_matrix = [[0 for _ in range(len_A)] for _ in range(len_A)]\nout = 0\nfor i in range(len_A - 1, -1, -1):\n for j in range(i, len_A):\n if i == j:\n sum_matrix[i][j] = A[i]\n else:\n sum_matrix[i][j] = sum_matrix[i + 1][j] + sum_matrix[i][i]\n if sum_...
<|body_start_0|> len_A = len(A) sum_matrix = [[0 for _ in range(len_A)] for _ in range(len_A)] out = 0 for i in range(len_A - 1, -1, -1): for j in range(i, len_A): if i == j: sum_matrix[i][j] = A[i] else: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def subarraysDivByK(self, A: List[int], K: int) -> int: """给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。 遍历每个子串求和,是否整除K,time out :param A: :param K: :return:""" <|body_0|> def subarraysDivByK2(self, A: List[int], K: int) -> int: """给定一个整数数组 A,返回其中元素之和可被 K 整除的(连...
stack_v2_sparse_classes_36k_train_024033
1,956
no_license
[ { "docstring": "给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。 遍历每个子串求和,是否整除K,time out :param A: :param K: :return:", "name": "subarraysDivByK", "signature": "def subarraysDivByK(self, A: List[int], K: int) -> int" }, { "docstring": "给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。 前缀和 + 同余定理,明天搞定 :param A:...
2
stack_v2_sparse_classes_30k_train_017383
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def subarraysDivByK(self, A: List[int], K: int) -> int: 给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。 遍历每个子串求和,是否整除K,time out :param A: :param K: :return: - def subarraysDivByK2(self...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def subarraysDivByK(self, A: List[int], K: int) -> int: 给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。 遍历每个子串求和,是否整除K,time out :param A: :param K: :return: - def subarraysDivByK2(self...
f7421522c437c952698736dbac8fb7ac6c0b8b88
<|skeleton|> class Solution: def subarraysDivByK(self, A: List[int], K: int) -> int: """给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。 遍历每个子串求和,是否整除K,time out :param A: :param K: :return:""" <|body_0|> def subarraysDivByK2(self, A: List[int], K: int) -> int: """给定一个整数数组 A,返回其中元素之和可被 K 整除的(连...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def subarraysDivByK(self, A: List[int], K: int) -> int: """给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。 遍历每个子串求和,是否整除K,time out :param A: :param K: :return:""" len_A = len(A) sum_matrix = [[0 for _ in range(len_A)] for _ in range(len_A)] out = 0 for i in range(le...
the_stack_v2_python_sparse
leetcode/daily_question/20200527_subarr_divbyk.py
whitepaper2/data_beauty
train
0
24ee2d99cff2e108f138bd61bd128ca9d8e0c17d
[ "required = [{'short_name': 'thetao'}, {'short_name': 'volcello', 'mip': 'fx'}]\nif project == 'CMIP6':\n required = [{'short_name': 'thetao'}, {'short_name': 'volcello', 'mip': 'Ofx'}]\nreturn required", "cube = cubes.extract_cube(Constraint(cube_func=lambda c: c.var_name == 'thetao'))\nvolume = cubes.extract...
<|body_start_0|> required = [{'short_name': 'thetao'}, {'short_name': 'volcello', 'mip': 'fx'}] if project == 'CMIP6': required = [{'short_name': 'thetao'}, {'short_name': 'volcello', 'mip': 'Ofx'}] return required <|end_body_0|> <|body_start_1|> cube = cubes.extract_cube(Co...
Derivation of variable `ohc`.
DerivedVariable
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DerivedVariable: """Derivation of variable `ohc`.""" def required(project): """Declare the variables needed for derivation.""" <|body_0|> def calculate(cubes): """Compute ocean heat content. Use c_p*rho_0= 4.09169e+6 J m-3 K-1 (Kuhlbrodt et al., 2015, Clim. Dyn.)...
stack_v2_sparse_classes_36k_train_024034
2,789
permissive
[ { "docstring": "Declare the variables needed for derivation.", "name": "required", "signature": "def required(project)" }, { "docstring": "Compute ocean heat content. Use c_p*rho_0= 4.09169e+6 J m-3 K-1 (Kuhlbrodt et al., 2015, Clim. Dyn.) Arguments --------- cube: iris.cube.Cube input cube. Ret...
2
stack_v2_sparse_classes_30k_train_021138
Implement the Python class `DerivedVariable` described below. Class description: Derivation of variable `ohc`. Method signatures and docstrings: - def required(project): Declare the variables needed for derivation. - def calculate(cubes): Compute ocean heat content. Use c_p*rho_0= 4.09169e+6 J m-3 K-1 (Kuhlbrodt et a...
Implement the Python class `DerivedVariable` described below. Class description: Derivation of variable `ohc`. Method signatures and docstrings: - def required(project): Declare the variables needed for derivation. - def calculate(cubes): Compute ocean heat content. Use c_p*rho_0= 4.09169e+6 J m-3 K-1 (Kuhlbrodt et a...
d5187438fea2928644cb53ecb26c6adb1e4cc947
<|skeleton|> class DerivedVariable: """Derivation of variable `ohc`.""" def required(project): """Declare the variables needed for derivation.""" <|body_0|> def calculate(cubes): """Compute ocean heat content. Use c_p*rho_0= 4.09169e+6 J m-3 K-1 (Kuhlbrodt et al., 2015, Clim. Dyn.)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DerivedVariable: """Derivation of variable `ohc`.""" def required(project): """Declare the variables needed for derivation.""" required = [{'short_name': 'thetao'}, {'short_name': 'volcello', 'mip': 'fx'}] if project == 'CMIP6': required = [{'short_name': 'thetao'}, {'...
the_stack_v2_python_sparse
esmvalcore/preprocessor/_derive/ohc.py
ESMValGroup/ESMValCore
train
41
052c9d398dc42ca204de3ae408302e861f7efc1a
[ "reader = csv.reader(data)\nnext(reader)\nreturn collections.Counter(map(lambda item: self.safe_name(item[4]), filter(lambda item: len(item[1].split('-')) != 2, reader)))", "if self.record[self.safe_name(name)] > 1:\n name = f'{name}_0x{code}'\nreturn self.safe_name(name)", "reader = csv.reader(data)\nnext(r...
<|body_start_0|> reader = csv.reader(data) next(reader) return collections.Counter(map(lambda item: self.safe_name(item[4]), filter(lambda item: len(item[1].split('-')) != 2, reader))) <|end_body_0|> <|body_start_1|> if self.record[self.safe_name(name)] > 1: name = f'{name}_...
Ethertype IEEE 802 Numbers
EtherType
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EtherType: """Ethertype IEEE 802 Numbers""" def count(self, data): """Count field records. Args: data (List[str]): CSV data. Returns: Counter: Field recordings.""" <|body_0|> def rename(self, name, code): """Rename duplicated fields. Args: name (str): Field name....
stack_v2_sparse_classes_36k_train_024035
3,362
permissive
[ { "docstring": "Count field records. Args: data (List[str]): CSV data. Returns: Counter: Field recordings.", "name": "count", "signature": "def count(self, data)" }, { "docstring": "Rename duplicated fields. Args: name (str): Field name. code (str): Field code (hex). Keyword Args: original (str)...
3
null
Implement the Python class `EtherType` described below. Class description: Ethertype IEEE 802 Numbers Method signatures and docstrings: - def count(self, data): Count field records. Args: data (List[str]): CSV data. Returns: Counter: Field recordings. - def rename(self, name, code): Rename duplicated fields. Args: na...
Implement the Python class `EtherType` described below. Class description: Ethertype IEEE 802 Numbers Method signatures and docstrings: - def count(self, data): Count field records. Args: data (List[str]): CSV data. Returns: Counter: Field recordings. - def rename(self, name, code): Rename duplicated fields. Args: na...
90cd07d67df28d5c5ab0585bc60f467a78d9db33
<|skeleton|> class EtherType: """Ethertype IEEE 802 Numbers""" def count(self, data): """Count field records. Args: data (List[str]): CSV data. Returns: Counter: Field recordings.""" <|body_0|> def rename(self, name, code): """Rename duplicated fields. Args: name (str): Field name....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EtherType: """Ethertype IEEE 802 Numbers""" def count(self, data): """Count field records. Args: data (List[str]): CSV data. Returns: Counter: Field recordings.""" reader = csv.reader(data) next(reader) return collections.Counter(map(lambda item: self.safe_name(item[4]), f...
the_stack_v2_python_sparse
pcapkit/vendor/reg/ethertype.py
stjordanis/PyPCAPKit
train
0
865c9c5272e70dcf34c3fd89acdcd33e4d463d16
[ "run_local_command_mock.return_value = [0, 'blah blah\\n381.99, GTX 1080 \\n']\ndriver, gpu_info = nvidia.get_gpu_info()\nself.assertEqual('381.99', driver)\nself.assertEqual('GTX 1080', gpu_info)", "run_local_command_mock.return_value = [0, 'blah\\n200.99, Quadro K900 \\n381.99, GTX 1080\\n']\ndriver, gpu_info =...
<|body_start_0|> run_local_command_mock.return_value = [0, 'blah blah\n381.99, GTX 1080 \n'] driver, gpu_info = nvidia.get_gpu_info() self.assertEqual('381.99', driver) self.assertEqual('GTX 1080', gpu_info) <|end_body_0|> <|body_start_1|> run_local_command_mock.return_value = [...
TestNvidiaTools
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestNvidiaTools: def test_get_gpu_info(self, run_local_command_mock): """Tests get gpu info parses expected value into expected components.""" <|body_0|> def test_get_gpu_info_quadro(self, run_local_command_mock): """Tests gpu info returns second entry if first entry...
stack_v2_sparse_classes_36k_train_024036
2,108
permissive
[ { "docstring": "Tests get gpu info parses expected value into expected components.", "name": "test_get_gpu_info", "signature": "def test_get_gpu_info(self, run_local_command_mock)" }, { "docstring": "Tests gpu info returns second entry if first entry is a Quadro.", "name": "test_get_gpu_info...
5
stack_v2_sparse_classes_30k_train_009616
Implement the Python class `TestNvidiaTools` described below. Class description: Implement the TestNvidiaTools class. Method signatures and docstrings: - def test_get_gpu_info(self, run_local_command_mock): Tests get gpu info parses expected value into expected components. - def test_get_gpu_info_quadro(self, run_loc...
Implement the Python class `TestNvidiaTools` described below. Class description: Implement the TestNvidiaTools class. Method signatures and docstrings: - def test_get_gpu_info(self, run_local_command_mock): Tests get gpu info parses expected value into expected components. - def test_get_gpu_info_quadro(self, run_loc...
b9f84203edad5e7e92161a9a634319db99631f3a
<|skeleton|> class TestNvidiaTools: def test_get_gpu_info(self, run_local_command_mock): """Tests get gpu info parses expected value into expected components.""" <|body_0|> def test_get_gpu_info_quadro(self, run_local_command_mock): """Tests gpu info returns second entry if first entry...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestNvidiaTools: def test_get_gpu_info(self, run_local_command_mock): """Tests get gpu info parses expected value into expected components.""" run_local_command_mock.return_value = [0, 'blah blah\n381.99, GTX 1080 \n'] driver, gpu_info = nvidia.get_gpu_info() self.assertEqual('...
the_stack_v2_python_sparse
oss_bench/tools/nvidia_test.py
tfboyd/benchmark_harness
train
7
98d97723ad272be70750d1be87e674158f396564
[ "self.prefix = [m[:] for m in matrix]\nself.m = len(matrix)\nself.n = len(matrix[0]) if matrix else 0\nif self.m == 0 or self.n == 0:\n return\nfor i in range(self.m):\n for j in range(1, self.n):\n self.prefix[i][j] += self.prefix[i][j - 1]\nfor j in range(self.n):\n for i in range(1, self.m):\n ...
<|body_start_0|> self.prefix = [m[:] for m in matrix] self.m = len(matrix) self.n = len(matrix[0]) if matrix else 0 if self.m == 0 or self.n == 0: return for i in range(self.m): for j in range(1, self.n): self.prefix[i][j] += self.prefix[i]...
NumMatrix
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" <|body_0|> def sumRegion(self, row1, col1, row2, col2): """:type row1: int :type col1: int :type row2: int :type col2: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_024037
1,360
no_license
[ { "docstring": ":type matrix: List[List[int]]", "name": "__init__", "signature": "def __init__(self, matrix)" }, { "docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int", "name": "sumRegion", "signature": "def sumRegion(self, row1, col1, row2, col2)" ...
2
null
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): :type matrix: List[List[int]] - def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:...
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): :type matrix: List[List[int]] - def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:...
0e35e4cc87bd41144b8e34302aafe776fec1b356
<|skeleton|> class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" <|body_0|> def sumRegion(self, row1, col1, row2, col2): """:type row1: int :type col1: int :type row2: int :type col2: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" self.prefix = [m[:] for m in matrix] self.m = len(matrix) self.n = len(matrix[0]) if matrix else 0 if self.m == 0 or self.n == 0: return for i in range(self.m): fo...
the_stack_v2_python_sparse
LeetCode/304-range_sum_query_2d_immutable.py
davll/practical-algorithms
train
0
0d8d92882f5ae73c5e0331d4909fc18495c4e7eb
[ "res = []\ncur = []\nnum_of_letters = 0\nfor w in words:\n if num_of_letters + len(w) + len(cur) > maxWidth:\n for i in range(maxWidth - num_of_letters):\n cur[i % (len(cur) - 1 or 1)] += ' '\n res.append(''.join(cur))\n cur = []\n num_of_letters = 0\n cur += [w]\n nu...
<|body_start_0|> res = [] cur = [] num_of_letters = 0 for w in words: if num_of_letters + len(w) + len(cur) > maxWidth: for i in range(maxWidth - num_of_letters): cur[i % (len(cur) - 1 or 1)] += ' ' res.append(''.join(cur)) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def fullJustify(self, words, maxWidth): """:type words: List[str] :type maxWidth: int :rtype: List[str]""" <|body_0|> def rewrite(self, words, maxWidth): """:type words: List[str] :type maxWidth: int :rtype: List[str]""" <|body_1|> <|end_skeleton|>...
stack_v2_sparse_classes_36k_train_024038
3,757
no_license
[ { "docstring": ":type words: List[str] :type maxWidth: int :rtype: List[str]", "name": "fullJustify", "signature": "def fullJustify(self, words, maxWidth)" }, { "docstring": ":type words: List[str] :type maxWidth: int :rtype: List[str]", "name": "rewrite", "signature": "def rewrite(self,...
2
stack_v2_sparse_classes_30k_train_019230
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def fullJustify(self, words, maxWidth): :type words: List[str] :type maxWidth: int :rtype: List[str] - def rewrite(self, words, maxWidth): :type words: List[str] :type maxWidth: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def fullJustify(self, words, maxWidth): :type words: List[str] :type maxWidth: int :rtype: List[str] - def rewrite(self, words, maxWidth): :type words: List[str] :type maxWidth: ...
6350568d16b0f8c49a020f055bb6d72e2705ea56
<|skeleton|> class Solution: def fullJustify(self, words, maxWidth): """:type words: List[str] :type maxWidth: int :rtype: List[str]""" <|body_0|> def rewrite(self, words, maxWidth): """:type words: List[str] :type maxWidth: int :rtype: List[str]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def fullJustify(self, words, maxWidth): """:type words: List[str] :type maxWidth: int :rtype: List[str]""" res = [] cur = [] num_of_letters = 0 for w in words: if num_of_letters + len(w) + len(cur) > maxWidth: for i in range(maxWidt...
the_stack_v2_python_sparse
co_linkedin/68_Text_Justification.py
vsdrun/lc_public
train
6
c05fe822e5fa5d462086dcca868ff740348f571c
[ "self.key: Optional[str] = None\nself.threshold: Optional[float] = None\nself.relation: Optional[str] = None\nkwargs.setdefault('relation', 'lt')\nkwargs.setdefault('key', 'ft_loss')\nkwargs.setdefault('threshold', 0.0)\nself.__dict__.update(kwargs)\nself.trainer = trainer\nlogging.info(f'Scorer-Configuration: {sel...
<|body_start_0|> self.key: Optional[str] = None self.threshold: Optional[float] = None self.relation: Optional[str] = None kwargs.setdefault('relation', 'lt') kwargs.setdefault('key', 'ft_loss') kwargs.setdefault('threshold', 0.0) self.__dict__.update(kwargs) ...
Scorer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Scorer: def __init__(self, trainer: Engine, **kwargs): """Parameters ---------- trainer : Engine The training-engine""" <|body_0|> def __call__(self, engine: Engine): """Determines an improvement during training.""" <|body_1|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_36k_train_024039
4,775
permissive
[ { "docstring": "Parameters ---------- trainer : Engine The training-engine", "name": "__init__", "signature": "def __init__(self, trainer: Engine, **kwargs)" }, { "docstring": "Determines an improvement during training.", "name": "__call__", "signature": "def __call__(self, engine: Engin...
2
stack_v2_sparse_classes_30k_train_008292
Implement the Python class `Scorer` described below. Class description: Implement the Scorer class. Method signatures and docstrings: - def __init__(self, trainer: Engine, **kwargs): Parameters ---------- trainer : Engine The training-engine - def __call__(self, engine: Engine): Determines an improvement during train...
Implement the Python class `Scorer` described below. Class description: Implement the Scorer class. Method signatures and docstrings: - def __init__(self, trainer: Engine, **kwargs): Parameters ---------- trainer : Engine The training-engine - def __call__(self, engine: Engine): Determines an improvement during train...
a511b03a2a2577d4ce372aa44e475df8005eb394
<|skeleton|> class Scorer: def __init__(self, trainer: Engine, **kwargs): """Parameters ---------- trainer : Engine The training-engine""" <|body_0|> def __call__(self, engine: Engine): """Determines an improvement during training.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Scorer: def __init__(self, trainer: Engine, **kwargs): """Parameters ---------- trainer : Engine The training-engine""" self.key: Optional[str] = None self.threshold: Optional[float] = None self.relation: Optional[str] = None kwargs.setdefault('relation', 'lt') ...
the_stack_v2_python_sparse
enel_service/modeling/losses.py
dos-group/enel-experiments
train
2
ac002677d76544540f077ca4c941b5bbc524e074
[ "l = 0\nr = len(nums) - 1\nmid = self.findMid(l, r, nums, target)\nif mid != -1:\n l = mid\n r = mid\n while l >= 0 and nums[l] == target:\n l -= 1\n while r < len(nums) and nums[r] == target:\n r += 1\n return [l + 1, r - 1]\nreturn [-1, -1]", "while l <= r:\n mid = (l + r) / 2\n ...
<|body_start_0|> l = 0 r = len(nums) - 1 mid = self.findMid(l, r, nums, target) if mid != -1: l = mid r = mid while l >= 0 and nums[l] == target: l -= 1 while r < len(nums) and nums[r] == target: r += 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def searchRange(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" <|body_0|> def findMid(self, l, r, nums, target): """Binary search""" <|body_1|> <|end_skeleton|> <|body_start_0|> l = 0 r = len(n...
stack_v2_sparse_classes_36k_train_024040
845
no_license
[ { "docstring": ":type nums: List[int] :type target: int :rtype: List[int]", "name": "searchRange", "signature": "def searchRange(self, nums, target)" }, { "docstring": "Binary search", "name": "findMid", "signature": "def findMid(self, l, r, nums, target)" } ]
2
stack_v2_sparse_classes_30k_train_016756
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def searchRange(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int] - def findMid(self, l, r, nums, target): Binary search
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def searchRange(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int] - def findMid(self, l, r, nums, target): Binary search <|skeleton|> class Solution...
ca8b2662330776d14962532ed8994dfeedadef70
<|skeleton|> class Solution: def searchRange(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" <|body_0|> def findMid(self, l, r, nums, target): """Binary search""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def searchRange(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" l = 0 r = len(nums) - 1 mid = self.findMid(l, r, nums, target) if mid != -1: l = mid r = mid while l >= 0 and nums[l] == ta...
the_stack_v2_python_sparse
Algo/Leetcode/034FirstAndLastPosInSortedArray.py
lawy623/Algorithm_Interview_Prep
train
2
6296f588d6a7a0f8b7e1cd7a392651324faad27d
[ "if numRows in self.check_list:\n return self.check_list[numRows]\nif numRows == 1:\n self.check_list[numRows] = [1]\n return [1]\nprev = self.generate_helper(numRows - 1)\ni = 0\nlst = [1]\nwhile i < len(prev) - 1:\n lst.append(prev[i] + prev[i + 1])\n i += 1\nlst.append(1)\nself.check_list[numRows]...
<|body_start_0|> if numRows in self.check_list: return self.check_list[numRows] if numRows == 1: self.check_list[numRows] = [1] return [1] prev = self.generate_helper(numRows - 1) i = 0 lst = [1] while i < len(prev) - 1: lst...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def generate_helper(self, numRows): """:type numRows: int :rtype: List[int]""" <|body_0|> def generate(self, numRows): """:type numRows: int :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> if numRows in self.check_l...
stack_v2_sparse_classes_36k_train_024041
1,700
no_license
[ { "docstring": ":type numRows: int :rtype: List[int]", "name": "generate_helper", "signature": "def generate_helper(self, numRows)" }, { "docstring": ":type numRows: int :rtype: List[List[int]]", "name": "generate", "signature": "def generate(self, numRows)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generate_helper(self, numRows): :type numRows: int :rtype: List[int] - def generate(self, numRows): :type numRows: int :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generate_helper(self, numRows): :type numRows: int :rtype: List[int] - def generate(self, numRows): :type numRows: int :rtype: List[List[int]] <|skeleton|> class Solution: ...
f7c165fedbdc9811fb7f1d2a43c797f5b5ac5322
<|skeleton|> class Solution: def generate_helper(self, numRows): """:type numRows: int :rtype: List[int]""" <|body_0|> def generate(self, numRows): """:type numRows: int :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def generate_helper(self, numRows): """:type numRows: int :rtype: List[int]""" if numRows in self.check_list: return self.check_list[numRows] if numRows == 1: self.check_list[numRows] = [1] return [1] prev = self.generate_helper(num...
the_stack_v2_python_sparse
pascal1.py
ilkaynazli/challenges
train
0
f94bdabda09a1dc0c9fee1917f6dafeccbed6270
[ "def sort_rule(x, y):\n a, b = (x + y, y + x)\n if a > b:\n return 1\n elif a < b:\n return -1\n else:\n return 0\nstrs = [str(num) for num in nums]\nstrs.sort(key=functools.cmp_to_key(sort_rule))\nreturn ''.join(strs)", "def fast_sort(l, r):\n if l >= r:\n return\n i...
<|body_start_0|> def sort_rule(x, y): a, b = (x + y, y + x) if a > b: return 1 elif a < b: return -1 else: return 0 strs = [str(num) for num in nums] strs.sort(key=functools.cmp_to_key(sort_rule)) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minNumber_1(self, nums: List[int]) -> str: """自定义排序 使用python内置排序函数 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:""" <|body_0|> def minNumber_2(self, nums: List[int]) -> str: """自定义排序 使用快速排序 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:""" <|...
stack_v2_sparse_classes_36k_train_024042
2,068
no_license
[ { "docstring": "自定义排序 使用python内置排序函数 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:", "name": "minNumber_1", "signature": "def minNumber_1(self, nums: List[int]) -> str" }, { "docstring": "自定义排序 使用快速排序 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:", "name": "minNumber_2", "signature":...
2
stack_v2_sparse_classes_30k_train_005480
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minNumber_1(self, nums: List[int]) -> str: 自定义排序 使用python内置排序函数 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return: - def minNumber_2(self, nums: List[int]) -> str: 自定义排序 使用快速排序 ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minNumber_1(self, nums: List[int]) -> str: 自定义排序 使用python内置排序函数 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return: - def minNumber_2(self, nums: List[int]) -> str: 自定义排序 使用快速排序 ...
62419b49000e79962bcdc99cd98afd2fb82ea345
<|skeleton|> class Solution: def minNumber_1(self, nums: List[int]) -> str: """自定义排序 使用python内置排序函数 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:""" <|body_0|> def minNumber_2(self, nums: List[int]) -> str: """自定义排序 使用快速排序 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:""" <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minNumber_1(self, nums: List[int]) -> str: """自定义排序 使用python内置排序函数 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:""" def sort_rule(x, y): a, b = (x + y, y + x) if a > b: return 1 elif a < b: return -1 ...
the_stack_v2_python_sparse
剑指 Offer(第 2 版)/minNumber.py
MaoningGuan/LeetCode
train
3
a1491a6ffffb229756e3b21af6431ba042fa5fd4
[ "fake_cfg = mock.MagicMock()\nfake_cfg.ssh_public_key_path = self.SSH_PUBLIC_KEY_PATH\nfake_cfg.machine_type = self.MACHINE_TYPE\nfake_cfg.network = self.NETWORK\nfake_cfg.zone = self.ZONE\nfake_cfg.resolution = '{x}x{y}x32x{dpi}'.format(x=self.X_RES, y=self.Y_RES, dpi=self.DPI)\nfake_cfg.metadata_variable = self.M...
<|body_start_0|> fake_cfg = mock.MagicMock() fake_cfg.ssh_public_key_path = self.SSH_PUBLIC_KEY_PATH fake_cfg.machine_type = self.MACHINE_TYPE fake_cfg.network = self.NETWORK fake_cfg.zone = self.ZONE fake_cfg.resolution = '{x}x{y}x32x{dpi}'.format(x=self.X_RES, y=self.Y_...
Test GoldfishComputeClient.
GoldfishComputeClientTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GoldfishComputeClientTest: """Test GoldfishComputeClient.""" def _GetFakeConfig(self): """Create a fake configuration object. Returns: A fake configuration mock object.""" <|body_0|> def setUp(self): """Set up the test.""" <|body_1|> def testCreateIn...
stack_v2_sparse_classes_36k_train_024043
5,985
permissive
[ { "docstring": "Create a fake configuration object. Returns: A fake configuration mock object.", "name": "_GetFakeConfig", "signature": "def _GetFakeConfig(self)" }, { "docstring": "Set up the test.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test CreateI...
3
stack_v2_sparse_classes_30k_train_014726
Implement the Python class `GoldfishComputeClientTest` described below. Class description: Test GoldfishComputeClient. Method signatures and docstrings: - def _GetFakeConfig(self): Create a fake configuration object. Returns: A fake configuration mock object. - def setUp(self): Set up the test. - def testCreateInstan...
Implement the Python class `GoldfishComputeClientTest` described below. Class description: Test GoldfishComputeClient. Method signatures and docstrings: - def _GetFakeConfig(self): Create a fake configuration object. Returns: A fake configuration mock object. - def setUp(self): Set up the test. - def testCreateInstan...
78a61ca023cbf1a0cecfef8b97df2b274ac3a988
<|skeleton|> class GoldfishComputeClientTest: """Test GoldfishComputeClient.""" def _GetFakeConfig(self): """Create a fake configuration object. Returns: A fake configuration mock object.""" <|body_0|> def setUp(self): """Set up the test.""" <|body_1|> def testCreateIn...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GoldfishComputeClientTest: """Test GoldfishComputeClient.""" def _GetFakeConfig(self): """Create a fake configuration object. Returns: A fake configuration mock object.""" fake_cfg = mock.MagicMock() fake_cfg.ssh_public_key_path = self.SSH_PUBLIC_KEY_PATH fake_cfg.machine_...
the_stack_v2_python_sparse
tools/acloud/internal/lib/goldfish_compute_client_test.py
ZYHGOD-1/Aosp11
train
0
468baf1e64e993c75261dca4da26a130cda50195
[ "a = nums[0]\nwhile a != nums[a]:\n temp = nums[a]\n nums[a] = a\n a = temp\nreturn a", "ans = 1\nl, r = (1, len(nums) - 1)\nwhile l <= r:\n m = (l + r) // 2\n n_smaller = sum((1 for n in nums if n < m))\n if n_smaller >= m:\n r = m - 1\n else:\n ans = m\n l = m + 1\nretu...
<|body_start_0|> a = nums[0] while a != nums[a]: temp = nums[a] nums[a] = a a = temp return a <|end_body_0|> <|body_start_1|> ans = 1 l, r = (1, len(nums) - 1) while l <= r: m = (l + r) // 2 n_smaller = sum((1 f...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findDuplicate(self, nums: List[int]) -> int: """In-place O(N) / O(1)""" <|body_0|> def findDuplicate(self, nums: List[int]) -> int: """특정 숫자 m보다 작은 원소의 갯수가 m개 이상이면 그보다 작은 숫자에 겹치는 숫자가 있다는 뜻. (m-1개 이하이면 그와 같거나 큰 숫자에 정답이 있다) Binary Search로 해결. 미친 솔루션. 이렇게 ...
stack_v2_sparse_classes_36k_train_024044
1,969
no_license
[ { "docstring": "In-place O(N) / O(1)", "name": "findDuplicate", "signature": "def findDuplicate(self, nums: List[int]) -> int" }, { "docstring": "특정 숫자 m보다 작은 원소의 갯수가 m개 이상이면 그보다 작은 숫자에 겹치는 숫자가 있다는 뜻. (m-1개 이하이면 그와 같거나 큰 숫자에 정답이 있다) Binary Search로 해결. 미친 솔루션. 이렇게 정답 자체를 가정하고, 범위를 줄여가면서 푸는 테크닉을 알...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate(self, nums: List[int]) -> int: In-place O(N) / O(1) - def findDuplicate(self, nums: List[int]) -> int: 특정 숫자 m보다 작은 원소의 갯수가 m개 이상이면 그보다 작은 숫자에 겹치는 숫자가 있다는 뜻. (m...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate(self, nums: List[int]) -> int: In-place O(N) / O(1) - def findDuplicate(self, nums: List[int]) -> int: 특정 숫자 m보다 작은 원소의 갯수가 m개 이상이면 그보다 작은 숫자에 겹치는 숫자가 있다는 뜻. (m...
c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1
<|skeleton|> class Solution: def findDuplicate(self, nums: List[int]) -> int: """In-place O(N) / O(1)""" <|body_0|> def findDuplicate(self, nums: List[int]) -> int: """특정 숫자 m보다 작은 원소의 갯수가 m개 이상이면 그보다 작은 숫자에 겹치는 숫자가 있다는 뜻. (m-1개 이하이면 그와 같거나 큰 숫자에 정답이 있다) Binary Search로 해결. 미친 솔루션. 이렇게 ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findDuplicate(self, nums: List[int]) -> int: """In-place O(N) / O(1)""" a = nums[0] while a != nums[a]: temp = nums[a] nums[a] = a a = temp return a def findDuplicate(self, nums: List[int]) -> int: """특정 숫자 m보다 작은 원...
the_stack_v2_python_sparse
Leetcode/287.py
hanwgyu/algorithm_problem_solving
train
5
8d46ebc4d5c8160b8f352f3d26cd960d0422e4fe
[ "if file_resources is None:\n file_resources = {}\n file_resources['alldata.txt'] = 'alldata.txt'\nsuper().__init__(path, file_resources, col_rename=col_rename, **kwargs)", "df = pd.read_csv(file_resources['alldata.txt'], sep='\\t', encoding='unicode_escape')\ndf['disease'] = df['disease'].str.lower()\nretu...
<|body_start_0|> if file_resources is None: file_resources = {} file_resources['alldata.txt'] = 'alldata.txt' super().__init__(path, file_resources, col_rename=col_rename, **kwargs) <|end_body_0|> <|body_start_1|> df = pd.read_csv(file_resources['alldata.txt'], sep='\t',...
Loads the HMDD database from "http://www.cuilab.cn/static/hmdd3" . Default path: "http://www.cuilab.cn/static/hmdd3/data/" . Default file_resources: { "alldata.txt": "alldata.txt", }
HMDD
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HMDD: """Loads the HMDD database from "http://www.cuilab.cn/static/hmdd3" . Default path: "http://www.cuilab.cn/static/hmdd3/data/" . Default file_resources: { "alldata.txt": "alldata.txt", }""" def __init__(self, path='http://www.cuilab.cn/static/hmdd3/data/', file_resources=None, col_renam...
stack_v2_sparse_classes_36k_train_024045
6,117
permissive
[ { "docstring": "Args: path: file_resources: col_rename: **kwargs:", "name": "__init__", "signature": "def __init__(self, path='http://www.cuilab.cn/static/hmdd3/data/', file_resources=None, col_rename=COLUMNS_RENAME_DICT, **kwargs)" }, { "docstring": "Args: file_resources: blocksize:", "name...
2
stack_v2_sparse_classes_30k_train_020732
Implement the Python class `HMDD` described below. Class description: Loads the HMDD database from "http://www.cuilab.cn/static/hmdd3" . Default path: "http://www.cuilab.cn/static/hmdd3/data/" . Default file_resources: { "alldata.txt": "alldata.txt", } Method signatures and docstrings: - def __init__(self, path='http...
Implement the Python class `HMDD` described below. Class description: Loads the HMDD database from "http://www.cuilab.cn/static/hmdd3" . Default path: "http://www.cuilab.cn/static/hmdd3/data/" . Default file_resources: { "alldata.txt": "alldata.txt", } Method signatures and docstrings: - def __init__(self, path='http...
35a0e00964c9b308f831263936f9507a69f52613
<|skeleton|> class HMDD: """Loads the HMDD database from "http://www.cuilab.cn/static/hmdd3" . Default path: "http://www.cuilab.cn/static/hmdd3/data/" . Default file_resources: { "alldata.txt": "alldata.txt", }""" def __init__(self, path='http://www.cuilab.cn/static/hmdd3/data/', file_resources=None, col_renam...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HMDD: """Loads the HMDD database from "http://www.cuilab.cn/static/hmdd3" . Default path: "http://www.cuilab.cn/static/hmdd3/data/" . Default file_resources: { "alldata.txt": "alldata.txt", }""" def __init__(self, path='http://www.cuilab.cn/static/hmdd3/data/', file_resources=None, col_rename=COLUMNS_REN...
the_stack_v2_python_sparse
openomics/database/disease.py
JonnyTran/OpenOmics
train
8
a91fa25daa5f1a1027838972c8a29d383aaf128c
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('raykatz_nedg_gaudiosi', 'raykatz_nedg_gaudiosi')\nrepo.dropCollection('housing_percentages')\nrepo.createCollection('housing_percentages')\nrepo.raykatz_nedg_gaudiosi.housing.aggregate([{'$project': {'zi...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('raykatz_nedg_gaudiosi', 'raykatz_nedg_gaudiosi') repo.dropCollection('housing_percentages') repo.createCollection('housing_percentages') r...
housing_percentages
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class housing_percentages: def execute(trial=False): """Merge zipcode info""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything happening in this script. Each run of the script wi...
stack_v2_sparse_classes_36k_train_024046
4,085
no_license
[ { "docstring": "Merge zipcode info", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing that invocation event.", "name": "p...
2
null
Implement the Python class `housing_percentages` described below. Class description: Implement the housing_percentages class. Method signatures and docstrings: - def execute(trial=False): Merge zipcode info - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create the provenance document d...
Implement the Python class `housing_percentages` described below. Class description: Implement the housing_percentages class. Method signatures and docstrings: - def execute(trial=False): Merge zipcode info - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create the provenance document d...
97e72731ffadbeae57d7a332decd58706e7c08de
<|skeleton|> class housing_percentages: def execute(trial=False): """Merge zipcode info""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything happening in this script. Each run of the script wi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class housing_percentages: def execute(trial=False): """Merge zipcode info""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('raykatz_nedg_gaudiosi', 'raykatz_nedg_gaudiosi') repo.dropCollection('housing_per...
the_stack_v2_python_sparse
raykatz_nedg_gaudiosi/housing_percentages.py
ROODAY/course-2017-fal-proj
train
3
ccafca77f3de5fa63479aa6a1f9b9bbbdabfc0a1
[ "if not request.user.is_authenticated:\n return redirect('Plein:plein')\naccount = request.user\ngast = account.gastregistratie_set.first()\nif not gast:\n return redirect('Plein:plein')\nif gast.fase == REGISTRATIE_FASE_COMPLEET:\n return redirect('Plein:plein')\nreturn super().dispatch(request, *args, **...
<|body_start_0|> if not request.user.is_authenticated: return redirect('Plein:plein') account = request.user gast = account.gastregistratie_set.first() if not gast: return redirect('Plein:plein') if gast.fase == REGISTRATIE_FASE_COMPLEET: retur...
Deze view geeft de landing page om de gebruiker het proces uit te leggen.
RegistreerGastVervolgView
[ "BSD-3-Clause-Clear" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegistreerGastVervolgView: """Deze view geeft de landing page om de gebruiker het proces uit te leggen.""" def dispatch(self, request, *args, **kwargs): """wegsturen als het we geen vragen meer hebben + bij oneigenlijk gebruik""" <|body_0|> def get_context_data(self, **k...
stack_v2_sparse_classes_36k_train_024047
28,294
permissive
[ { "docstring": "wegsturen als het we geen vragen meer hebben + bij oneigenlijk gebruik", "name": "dispatch", "signature": "def dispatch(self, request, *args, **kwargs)" }, { "docstring": "called by the template system to get the context data for the template", "name": "get_context_data", ...
2
null
Implement the Python class `RegistreerGastVervolgView` described below. Class description: Deze view geeft de landing page om de gebruiker het proces uit te leggen. Method signatures and docstrings: - def dispatch(self, request, *args, **kwargs): wegsturen als het we geen vragen meer hebben + bij oneigenlijk gebruik ...
Implement the Python class `RegistreerGastVervolgView` described below. Class description: Deze view geeft de landing page om de gebruiker het proces uit te leggen. Method signatures and docstrings: - def dispatch(self, request, *args, **kwargs): wegsturen als het we geen vragen meer hebben + bij oneigenlijk gebruik ...
5ed38165a231f0caa56f67e8faf2dd074916e500
<|skeleton|> class RegistreerGastVervolgView: """Deze view geeft de landing page om de gebruiker het proces uit te leggen.""" def dispatch(self, request, *args, **kwargs): """wegsturen als het we geen vragen meer hebben + bij oneigenlijk gebruik""" <|body_0|> def get_context_data(self, **k...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RegistreerGastVervolgView: """Deze view geeft de landing page om de gebruiker het proces uit te leggen.""" def dispatch(self, request, *args, **kwargs): """wegsturen als het we geen vragen meer hebben + bij oneigenlijk gebruik""" if not request.user.is_authenticated: return re...
the_stack_v2_python_sparse
Registreer/view_registreer_gast.py
RamonvdW/nhb-apps
train
2
22bebda96d1e9f13f29b160954692e61e8739e44
[ "if not root or (root.left == None and root.right == None):\n if not root:\n pass\n else:\n pass\n return root\nleft = self.flatten(root.left)\nright = self.flatten(root.right)\nroot.left = None\nif left:\n root.right = left\n while left.right:\n left = left.right\n left.right...
<|body_start_0|> if not root or (root.left == None and root.right == None): if not root: pass else: pass return root left = self.flatten(root.left) right = self.flatten(root.right) root.left = None if left: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def flatten_fail(self, root): """:type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.""" <|body_0|> def flatten_myself(self, root): """:type root: TreeNode :rtype: void Do not return anything, modify root in-place instead....
stack_v2_sparse_classes_36k_train_024048
3,580
no_license
[ { "docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.", "name": "flatten_fail", "signature": "def flatten_fail(self, root)" }, { "docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.", "name": "...
2
stack_v2_sparse_classes_30k_train_018584
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def flatten_fail(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. - def flatten_myself(self, root): :type root: TreeNode :rtyp...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def flatten_fail(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. - def flatten_myself(self, root): :type root: TreeNode :rtyp...
93266095329e2e8e949a72371b88b07382a60e0d
<|skeleton|> class Solution: def flatten_fail(self, root): """:type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.""" <|body_0|> def flatten_myself(self, root): """:type root: TreeNode :rtype: void Do not return anything, modify root in-place instead....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def flatten_fail(self, root): """:type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.""" if not root or (root.left == None and root.right == None): if not root: pass else: pass retu...
the_stack_v2_python_sparse
flatten_114.py
shivangi-prog/leetcode
train
0
062cb0a03e9e0d28a433e76ce216ab3434960fbf
[ "if n == 1:\n return x\nif n == 0:\n return 1\nflag = 1 if n > 0 else -1\nn = abs(n)\nresult = x\ni = 1\nwhile 2 * i <= n:\n result *= result\n i *= 2\nif i < n:\n result = result * self.myPow(x, n - i)\nreturn result if flag == 1 else 1 / result", "if x == 0:\n return 0\nif n == 0:\n return ...
<|body_start_0|> if n == 1: return x if n == 0: return 1 flag = 1 if n > 0 else -1 n = abs(n) result = x i = 1 while 2 * i <= n: result *= result i *= 2 if i < n: result = result * self.myPow(x, n...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def myPow(self, x, n): """:type x: float :type n: int :rtype: float""" <|body_0|> def myPow1(self, x, n): """:type x: float :type n: int :rtype: float""" <|body_1|> <|end_skeleton|> <|body_start_0|> if n == 1: return x ...
stack_v2_sparse_classes_36k_train_024049
1,123
no_license
[ { "docstring": ":type x: float :type n: int :rtype: float", "name": "myPow", "signature": "def myPow(self, x, n)" }, { "docstring": ":type x: float :type n: int :rtype: float", "name": "myPow1", "signature": "def myPow1(self, x, n)" } ]
2
stack_v2_sparse_classes_30k_train_006544
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def myPow(self, x, n): :type x: float :type n: int :rtype: float - def myPow1(self, x, n): :type x: float :type n: int :rtype: float
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def myPow(self, x, n): :type x: float :type n: int :rtype: float - def myPow1(self, x, n): :type x: float :type n: int :rtype: float <|skeleton|> class Solution: def myPow(...
707829268535a80cfe0ffa1dc0623520c3fcbecf
<|skeleton|> class Solution: def myPow(self, x, n): """:type x: float :type n: int :rtype: float""" <|body_0|> def myPow1(self, x, n): """:type x: float :type n: int :rtype: float""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def myPow(self, x, n): """:type x: float :type n: int :rtype: float""" if n == 1: return x if n == 0: return 1 flag = 1 if n > 0 else -1 n = abs(n) result = x i = 1 while 2 * i <= n: result *= result ...
the_stack_v2_python_sparse
leetcode/1-50/_50_my_pow.py
blackwings001/algorithm
train
0
fe30943439ddec83a9abea1d44706cc765f750df
[ "try:\n self._stas\nexcept AttributeError:\n self._stas = []\nif experiment == None:\n experiment = self.sort.r.e[0]\nelif type(experiment) == int:\n experiment = self.sort.r.e[experiment]\nsta = STA(neuron=self, experiment=experiment, **kwargs)\nfor _sta in self._stas:\n if _sta == sta:\n if ...
<|body_start_0|> try: self._stas except AttributeError: self._stas = [] if experiment == None: experiment = self.sort.r.e[0] elif type(experiment) == int: experiment = self.sort.r.e[experiment] sta = STA(neuron=self, experiment=expe...
Mix-in class that defines the reverse correlation related Neuron methods
NeuronRevCorr
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NeuronRevCorr: """Mix-in class that defines the reverse correlation related Neuron methods""" def sta(self, experiment=None, **kwargs): """Returns an existing STA RevCorr object, or creates a new one if necessary""" <|body_0|> def stc(self, experiment=None, **kwargs): ...
stack_v2_sparse_classes_36k_train_024050
44,171
permissive
[ { "docstring": "Returns an existing STA RevCorr object, or creates a new one if necessary", "name": "sta", "signature": "def sta(self, experiment=None, **kwargs)" }, { "docstring": "Returns an existing STC RevCorr object, or creates a new one if necessary", "name": "stc", "signature": "d...
2
stack_v2_sparse_classes_30k_train_014067
Implement the Python class `NeuronRevCorr` described below. Class description: Mix-in class that defines the reverse correlation related Neuron methods Method signatures and docstrings: - def sta(self, experiment=None, **kwargs): Returns an existing STA RevCorr object, or creates a new one if necessary - def stc(self...
Implement the Python class `NeuronRevCorr` described below. Class description: Mix-in class that defines the reverse correlation related Neuron methods Method signatures and docstrings: - def sta(self, experiment=None, **kwargs): Returns an existing STA RevCorr object, or creates a new one if necessary - def stc(self...
ab576a41ec00e3c126bca45c2504dd61bd1cda56
<|skeleton|> class NeuronRevCorr: """Mix-in class that defines the reverse correlation related Neuron methods""" def sta(self, experiment=None, **kwargs): """Returns an existing STA RevCorr object, or creates a new one if necessary""" <|body_0|> def stc(self, experiment=None, **kwargs): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NeuronRevCorr: """Mix-in class that defines the reverse correlation related Neuron methods""" def sta(self, experiment=None, **kwargs): """Returns an existing STA RevCorr object, or creates a new one if necessary""" try: self._stas except AttributeError: se...
the_stack_v2_python_sparse
neuropy/neuron.py
node2319/neuropy-1
train
0
f47292324269e352c52288ae770524fa16e7b536
[ "labels = []\nlabel_ids = []\nscores = []\ndisplay_names = []\nrelative_keypoints = []\nfor category in self.categories:\n scores.append(category.score)\n if category.index:\n label_ids.append(category.index)\n if category.category_name:\n labels.append(category.category_name)\n if categor...
<|body_start_0|> labels = [] label_ids = [] scores = [] display_names = [] relative_keypoints = [] for category in self.categories: scores.append(category.score) if category.index: label_ids.append(category.index) if cat...
Represents one detected object in the object detector's results. Attributes: bounding_box: A BoundingBox object. categories: A list of Category objects. keypoints: A list of NormalizedKeypoint objects.
Detection
[ "Apache-2.0", "dtoa" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Detection: """Represents one detected object in the object detector's results. Attributes: bounding_box: A BoundingBox object. categories: A list of Category objects. keypoints: A list of NormalizedKeypoint objects.""" def to_pb2(self) -> _DetectionProto: """Generates a Detection pro...
stack_v2_sparse_classes_36k_train_024051
5,843
permissive
[ { "docstring": "Generates a Detection protobuf object.", "name": "to_pb2", "signature": "def to_pb2(self) -> _DetectionProto" }, { "docstring": "Creates a `Detection` object from the given protobuf object.", "name": "create_from_pb2", "signature": "def create_from_pb2(cls, pb2_obj: _Dete...
3
stack_v2_sparse_classes_30k_train_012551
Implement the Python class `Detection` described below. Class description: Represents one detected object in the object detector's results. Attributes: bounding_box: A BoundingBox object. categories: A list of Category objects. keypoints: A list of NormalizedKeypoint objects. Method signatures and docstrings: - def t...
Implement the Python class `Detection` described below. Class description: Represents one detected object in the object detector's results. Attributes: bounding_box: A BoundingBox object. categories: A list of Category objects. keypoints: A list of NormalizedKeypoint objects. Method signatures and docstrings: - def t...
007824594bf1d07c7c1467df03a43886f8a4b3ad
<|skeleton|> class Detection: """Represents one detected object in the object detector's results. Attributes: bounding_box: A BoundingBox object. categories: A list of Category objects. keypoints: A list of NormalizedKeypoint objects.""" def to_pb2(self) -> _DetectionProto: """Generates a Detection pro...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Detection: """Represents one detected object in the object detector's results. Attributes: bounding_box: A BoundingBox object. categories: A list of Category objects. keypoints: A list of NormalizedKeypoint objects.""" def to_pb2(self) -> _DetectionProto: """Generates a Detection protobuf object....
the_stack_v2_python_sparse
mediapipe/tasks/python/components/containers/detections.py
google/mediapipe
train
23,940
0f3523e36b486756b67e717e0ca05968a884befe
[ "logger.info(command)\nfrom subprocess import Popen, PIPE\nprocess = Popen(command, stdout=PIPE, stderr=PIPE, shell=True)\noutput, error = process.communicate()\nret = process.wait()\nif output:\n logger.info(output)\nif error:\n if ret == 0:\n logger.info(error)\n else:\n logger.error(error)...
<|body_start_0|> logger.info(command) from subprocess import Popen, PIPE process = Popen(command, stdout=PIPE, stderr=PIPE, shell=True) output, error = process.communicate() ret = process.wait() if output: logger.info(output) if error: if r...
a collection of os utilities
OSUtilities
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OSUtilities: """a collection of os utilities""" def RunCommandAndLogStdOutStdErr(command, logger): """Use this function to capture the output from a command Capture both the output and the errors Send output/errors to the console and log file""" <|body_0|> def GetNullRed...
stack_v2_sparse_classes_36k_train_024052
1,408
no_license
[ { "docstring": "Use this function to capture the output from a command Capture both the output and the errors Send output/errors to the console and log file", "name": "RunCommandAndLogStdOutStdErr", "signature": "def RunCommandAndLogStdOutStdErr(command, logger)" }, { "docstring": "Return NULL r...
2
stack_v2_sparse_classes_30k_train_019899
Implement the Python class `OSUtilities` described below. Class description: a collection of os utilities Method signatures and docstrings: - def RunCommandAndLogStdOutStdErr(command, logger): Use this function to capture the output from a command Capture both the output and the errors Send output/errors to the conso...
Implement the Python class `OSUtilities` described below. Class description: a collection of os utilities Method signatures and docstrings: - def RunCommandAndLogStdOutStdErr(command, logger): Use this function to capture the output from a command Capture both the output and the errors Send output/errors to the conso...
9ff48f61cfd4e0c5994ad3dabab3987255cea953
<|skeleton|> class OSUtilities: """a collection of os utilities""" def RunCommandAndLogStdOutStdErr(command, logger): """Use this function to capture the output from a command Capture both the output and the errors Send output/errors to the console and log file""" <|body_0|> def GetNullRed...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OSUtilities: """a collection of os utilities""" def RunCommandAndLogStdOutStdErr(command, logger): """Use this function to capture the output from a command Capture both the output and the errors Send output/errors to the console and log file""" logger.info(command) from subproces...
the_stack_v2_python_sparse
EAA_Dataloader/src/AACloudTools/OSUtilities.py
eulertech/backup
train
0
b2335e57994164743df1ac49174db7bd7d9e9c54
[ "SeleniumService.__init__(self)\nself.engine = 'google'\nself.URLBASE = 'http://google.com/search?'", "combined_divs = list(zip(titles, urls, snippets))\nresults = list(map(lambda x: {'query': query, 'engine': self.engine, 'title': x[0].text, 'url': x[1], 'snippet': x[2].text}, combined_divs))\nreturn results", ...
<|body_start_0|> SeleniumService.__init__(self) self.engine = 'google' self.URLBASE = 'http://google.com/search?' <|end_body_0|> <|body_start_1|> combined_divs = list(zip(titles, urls, snippets)) results = list(map(lambda x: {'query': query, 'engine': self.engine, 'title': x[0]....
Specialized service for scraping bing.com search engine
GoogleService
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GoogleService: """Specialized service for scraping bing.com search engine""" def __init__(self): """Initialize virtual browser and set correct url base""" <|body_0|> def combine_processed_tags(self, query, titles, urls, snippets): """Combine all scraped tags into...
stack_v2_sparse_classes_36k_train_024053
8,761
permissive
[ { "docstring": "Initialize virtual browser and set correct url base", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Combine all scraped tags into one container. Resulting object is a list of dicts. Arguments: query -- query that generated results titles -- tags with ti...
3
stack_v2_sparse_classes_30k_train_003524
Implement the Python class `GoogleService` described below. Class description: Specialized service for scraping bing.com search engine Method signatures and docstrings: - def __init__(self): Initialize virtual browser and set correct url base - def combine_processed_tags(self, query, titles, urls, snippets): Combine ...
Implement the Python class `GoogleService` described below. Class description: Specialized service for scraping bing.com search engine Method signatures and docstrings: - def __init__(self): Initialize virtual browser and set correct url base - def combine_processed_tags(self, query, titles, urls, snippets): Combine ...
af03252e19075feec3fa478fa271ea3ae8cf8d11
<|skeleton|> class GoogleService: """Specialized service for scraping bing.com search engine""" def __init__(self): """Initialize virtual browser and set correct url base""" <|body_0|> def combine_processed_tags(self, query, titles, urls, snippets): """Combine all scraped tags into...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GoogleService: """Specialized service for scraping bing.com search engine""" def __init__(self): """Initialize virtual browser and set correct url base""" SeleniumService.__init__(self) self.engine = 'google' self.URLBASE = 'http://google.com/search?' def combine_proc...
the_stack_v2_python_sparse
services/SeleniumServices.py
kubasikora/WEDT-Projekt
train
0
69999a306e94579cff7357c9b3a6b767d7589861
[ "nasa0 = NASA(coeffs=[11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0], Tmin=(300.0, 'K'), Tmax=(1000.0, 'K'), comment='This data is completely made up and unphysical')\nnasa1 = NASA(coeffs=[21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0], Tmin=(1000.0, 'K'), Tmax=(6000.0, 'K'), comment='This data is also completely made up and...
<|body_start_0|> nasa0 = NASA(coeffs=[11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0], Tmin=(300.0, 'K'), Tmax=(1000.0, 'K'), comment='This data is completely made up and unphysical') nasa1 = NASA(coeffs=[21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0], Tmin=(1000.0, 'K'), Tmax=(6000.0, 'K'), comment='This data is ...
Contains unit tests of the MultiNASA class.
TestMultiNASA
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestMultiNASA: """Contains unit tests of the MultiNASA class.""" def setUp(self): """A function run before each unit test in this class.""" <|body_0|> def testPickle(self): """Test that a MultiNASA object can be successfully pickled and unpickled with no loss of ...
stack_v2_sparse_classes_36k_train_024054
32,390
permissive
[ { "docstring": "A function run before each unit test in this class.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test that a MultiNASA object can be successfully pickled and unpickled with no loss of information.", "name": "testPickle", "signature": "def testPickl...
3
stack_v2_sparse_classes_30k_train_020411
Implement the Python class `TestMultiNASA` described below. Class description: Contains unit tests of the MultiNASA class. Method signatures and docstrings: - def setUp(self): A function run before each unit test in this class. - def testPickle(self): Test that a MultiNASA object can be successfully pickled and unpic...
Implement the Python class `TestMultiNASA` described below. Class description: Contains unit tests of the MultiNASA class. Method signatures and docstrings: - def setUp(self): A function run before each unit test in this class. - def testPickle(self): Test that a MultiNASA object can be successfully pickled and unpic...
7cc7c3bfb330786526c56113d98c785bcaaa161a
<|skeleton|> class TestMultiNASA: """Contains unit tests of the MultiNASA class.""" def setUp(self): """A function run before each unit test in this class.""" <|body_0|> def testPickle(self): """Test that a MultiNASA object can be successfully pickled and unpickled with no loss of ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestMultiNASA: """Contains unit tests of the MultiNASA class.""" def setUp(self): """A function run before each unit test in this class.""" nasa0 = NASA(coeffs=[11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0], Tmin=(300.0, 'K'), Tmax=(1000.0, 'K'), comment='This data is completely made up and u...
the_stack_v2_python_sparse
unittest/thermoTest.py
sean-v8/RMG-Py
train
0
bee8b7adcc79cf39b34c919a72bac265edde28ff
[ "self.values = values\nself.duration = duration\nself.delay = delay", "new_values = list(self.values)\nnew_values.reverse()\nreturn Lineal(new_values, self.duration, self.delay)", "import pilas\nstep = self.duration / float(len(self.values))\nstep *= 1000.0\ngetter = function.replace('set_', 'get_')\nfunction_t...
<|body_start_0|> self.values = values self.duration = duration self.delay = delay <|end_body_0|> <|body_start_1|> new_values = list(self.values) new_values.reverse() return Lineal(new_values, self.duration, self.delay) <|end_body_1|> <|body_start_2|> import pila...
Representa una interpolación lineal.
Lineal
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Lineal: """Representa una interpolación lineal.""" def __init__(self, values, duration, delay): """Inicializa la interpolación. ``values`` tiene que ser una lista con todos los puntos por los que se quiere adoptar valores y ``duration`` es la cantidad de segundos que deben tomarse pa...
stack_v2_sparse_classes_36k_train_024055
2,982
no_license
[ { "docstring": "Inicializa la interpolación. ``values`` tiene que ser una lista con todos los puntos por los que se quiere adoptar valores y ``duration`` es la cantidad de segundos que deben tomarse para realizar la interpolación.", "name": "__init__", "signature": "def __init__(self, values, duration, ...
3
null
Implement the Python class `Lineal` described below. Class description: Representa una interpolación lineal. Method signatures and docstrings: - def __init__(self, values, duration, delay): Inicializa la interpolación. ``values`` tiene que ser una lista con todos los puntos por los que se quiere adoptar valores y ``d...
Implement the Python class `Lineal` described below. Class description: Representa una interpolación lineal. Method signatures and docstrings: - def __init__(self, values, duration, delay): Inicializa la interpolación. ``values`` tiene que ser una lista con todos los puntos por los que se quiere adoptar valores y ``d...
ce0197ecdb88b9e5a9b21dd6cb361ea6d971a572
<|skeleton|> class Lineal: """Representa una interpolación lineal.""" def __init__(self, values, duration, delay): """Inicializa la interpolación. ``values`` tiene que ser una lista con todos los puntos por los que se quiere adoptar valores y ``duration`` es la cantidad de segundos que deben tomarse pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Lineal: """Representa una interpolación lineal.""" def __init__(self, values, duration, delay): """Inicializa la interpolación. ``values`` tiene que ser una lista con todos los puntos por los que se quiere adoptar valores y ``duration`` es la cantidad de segundos que deben tomarse para realizar l...
the_stack_v2_python_sparse
pilas/interpolaciones.py
rarmas/elbasurero
train
0
33fd58517873b1c9b2a7c957a36f7401a18e1b93
[ "self.hass = hass\nself.devices = devices\nself.bt_device_id = bt_device_id\n\ndef callback(bt_addr, _, packet, additional_info):\n \"\"\"Handle new packets.\"\"\"\n self.process_packet(additional_info['namespace'], additional_info['instance'], packet.temperature)\ndevice_filters = [EddystoneFilter(d.namespac...
<|body_start_0|> self.hass = hass self.devices = devices self.bt_device_id = bt_device_id def callback(bt_addr, _, packet, additional_info): """Handle new packets.""" self.process_packet(additional_info['namespace'], additional_info['instance'], packet.temperatur...
Continuously scan for BLE advertisements.
Monitor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Monitor: """Continuously scan for BLE advertisements.""" def __init__(self, hass: HomeAssistant, devices: list[EddystoneTemp], bt_device_id: int) -> None: """Construct interface object.""" <|body_0|> def start(self) -> None: """Continuously scan for BLE advertise...
stack_v2_sparse_classes_36k_train_024056
6,045
permissive
[ { "docstring": "Construct interface object.", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant, devices: list[EddystoneTemp], bt_device_id: int) -> None" }, { "docstring": "Continuously scan for BLE advertisements.", "name": "start", "signature": "def start(self) ...
4
stack_v2_sparse_classes_30k_train_008902
Implement the Python class `Monitor` described below. Class description: Continuously scan for BLE advertisements. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, devices: list[EddystoneTemp], bt_device_id: int) -> None: Construct interface object. - def start(self) -> None: Continuously s...
Implement the Python class `Monitor` described below. Class description: Continuously scan for BLE advertisements. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, devices: list[EddystoneTemp], bt_device_id: int) -> None: Construct interface object. - def start(self) -> None: Continuously s...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class Monitor: """Continuously scan for BLE advertisements.""" def __init__(self, hass: HomeAssistant, devices: list[EddystoneTemp], bt_device_id: int) -> None: """Construct interface object.""" <|body_0|> def start(self) -> None: """Continuously scan for BLE advertise...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Monitor: """Continuously scan for BLE advertisements.""" def __init__(self, hass: HomeAssistant, devices: list[EddystoneTemp], bt_device_id: int) -> None: """Construct interface object.""" self.hass = hass self.devices = devices self.bt_device_id = bt_device_id de...
the_stack_v2_python_sparse
homeassistant/components/eddystone_temperature/sensor.py
home-assistant/core
train
35,501
49b7968075c6f8eeada698694c87f3d1f64e4d29
[ "modify = True\nif modify and kwargs is not None:\n for key, value in kwargs.iteritems():\n log('%s == %s' % (key, value))\nif modify:\n config = kwargs['config']\n inputdict = kwargs['inputdict']\n inputkeydict = kwargs['inputkeydict']\nentity = 'cpe_primary_triple'\nint_name = None\nif isinstan...
<|body_start_0|> modify = True if modify and kwargs is not None: for key, value in kwargs.iteritems(): log('%s == %s' % (key, value)) if modify: config = kwargs['config'] inputdict = kwargs['inputdict'] inputkeydict = kwargs['inputk...
ServiceDataCustomization
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServiceDataCustomization: def process_service_create_data(smodelctx, sdata, dev, **kwargs): """Custom API to modify the inputs""" <|body_0|> def process_service_device_bindings(smodelctx, sdata, dev, **kwargs): """Custom API to modify the device bindings or Call the ...
stack_v2_sparse_classes_36k_train_024057
4,970
no_license
[ { "docstring": "Custom API to modify the inputs", "name": "process_service_create_data", "signature": "def process_service_create_data(smodelctx, sdata, dev, **kwargs)" }, { "docstring": "Custom API to modify the device bindings or Call the Business Login Handlers", "name": "process_service_...
4
stack_v2_sparse_classes_30k_train_019540
Implement the Python class `ServiceDataCustomization` described below. Class description: Implement the ServiceDataCustomization class. Method signatures and docstrings: - def process_service_create_data(smodelctx, sdata, dev, **kwargs): Custom API to modify the inputs - def process_service_device_bindings(smodelctx,...
Implement the Python class `ServiceDataCustomization` described below. Class description: Implement the ServiceDataCustomization class. Method signatures and docstrings: - def process_service_create_data(smodelctx, sdata, dev, **kwargs): Custom API to modify the inputs - def process_service_device_bindings(smodelctx,...
96de3a4fd4adbbc0d443620f0c53f397823a1cad
<|skeleton|> class ServiceDataCustomization: def process_service_create_data(smodelctx, sdata, dev, **kwargs): """Custom API to modify the inputs""" <|body_0|> def process_service_device_bindings(smodelctx, sdata, dev, **kwargs): """Custom API to modify the device bindings or Call the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ServiceDataCustomization: def process_service_create_data(smodelctx, sdata, dev, **kwargs): """Custom API to modify the inputs""" modify = True if modify and kwargs is not None: for key, value in kwargs.iteritems(): log('%s == %s' % (key, value)) if ...
the_stack_v2_python_sparse
scripts/managed_cpe_services/customer/triple_cpe_site/triple_cpe_site_services/cpe_primary/route_maps/route_map/service_customization.py
lucabrasi83/anutacpedeployment
train
0
d3d037f30156363b4a825630c03acb6a86580be1
[ "if not digits:\n return []\nres = []\nself.dfs(digits, 0, '', res)\nreturn res", "if index == len(digits):\n return res.append(s)\nfor ch in MAPPING[digits[index]]:\n self.dfs(digits, index + 1, s + ch, res)" ]
<|body_start_0|> if not digits: return [] res = [] self.dfs(digits, 0, '', res) return res <|end_body_0|> <|body_start_1|> if index == len(digits): return res.append(s) for ch in MAPPING[digits[index]]: self.dfs(digits, index + 1, s + ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def letterCombinations(self, digits): """:type digits: str :rtype: List[str]""" <|body_0|> def dfs(self, digits, index, s, res): """index keeps tracking the current position s is the substring recursively add qualified substring to res""" <|body_1|>...
stack_v2_sparse_classes_36k_train_024058
952
no_license
[ { "docstring": ":type digits: str :rtype: List[str]", "name": "letterCombinations", "signature": "def letterCombinations(self, digits)" }, { "docstring": "index keeps tracking the current position s is the substring recursively add qualified substring to res", "name": "dfs", "signature":...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def letterCombinations(self, digits): :type digits: str :rtype: List[str] - def dfs(self, digits, index, s, res): index keeps tracking the current position s is the substring rec...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def letterCombinations(self, digits): :type digits: str :rtype: List[str] - def dfs(self, digits, index, s, res): index keeps tracking the current position s is the substring rec...
90c000c3be70727cde4f7494fbbb1c425bfd3da4
<|skeleton|> class Solution: def letterCombinations(self, digits): """:type digits: str :rtype: List[str]""" <|body_0|> def dfs(self, digits, index, s, res): """index keeps tracking the current position s is the substring recursively add qualified substring to res""" <|body_1|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def letterCombinations(self, digits): """:type digits: str :rtype: List[str]""" if not digits: return [] res = [] self.dfs(digits, 0, '', res) return res def dfs(self, digits, index, s, res): """index keeps tracking the current positio...
the_stack_v2_python_sparse
categories/dfs-bfs/17.letter-combinations-of-a-phone-number.py
chenjienan/python-leetcode
train
16
b2bce8850af308399e2bfc2b39316ef40cae35c0
[ "super().__init__()\nself.precisions: Optional[str] = None\nif data.get('precisions'):\n self.set_precisions(data.get('precisions'))\nself.op_wise = None\nif isinstance(data.get('op_wise'), dict):\n self.op_wise = data.get('op_wise', {})", "if isinstance(precisions, str):\n self.precisions = precisions.r...
<|body_start_0|> super().__init__() self.precisions: Optional[str] = None if data.get('precisions'): self.set_precisions(data.get('precisions')) self.op_wise = None if isinstance(data.get('op_wise'), dict): self.op_wise = data.get('op_wise', {}) <|end_body...
Configuration Graph Optimization class.
GraphOptimization
[ "MIT", "Intel", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GraphOptimization: """Configuration Graph Optimization class.""" def __init__(self, data: Dict[str, Any]={}) -> None: """Initialize Configuration Graph Optimization class.""" <|body_0|> def set_precisions(self, precisions: Union[str, List[str]]) -> None: """Updat...
stack_v2_sparse_classes_36k_train_024059
1,934
permissive
[ { "docstring": "Initialize Configuration Graph Optimization class.", "name": "__init__", "signature": "def __init__(self, data: Dict[str, Any]={}) -> None" }, { "docstring": "Update graph_optimization precisions in config.", "name": "set_precisions", "signature": "def set_precisions(self...
2
null
Implement the Python class `GraphOptimization` described below. Class description: Configuration Graph Optimization class. Method signatures and docstrings: - def __init__(self, data: Dict[str, Any]={}) -> None: Initialize Configuration Graph Optimization class. - def set_precisions(self, precisions: Union[str, List[...
Implement the Python class `GraphOptimization` described below. Class description: Configuration Graph Optimization class. Method signatures and docstrings: - def __init__(self, data: Dict[str, Any]={}) -> None: Initialize Configuration Graph Optimization class. - def set_precisions(self, precisions: Union[str, List[...
3976edc4215398e69ce0213f87ec295f5dc96e0e
<|skeleton|> class GraphOptimization: """Configuration Graph Optimization class.""" def __init__(self, data: Dict[str, Any]={}) -> None: """Initialize Configuration Graph Optimization class.""" <|body_0|> def set_precisions(self, precisions: Union[str, List[str]]) -> None: """Updat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GraphOptimization: """Configuration Graph Optimization class.""" def __init__(self, data: Dict[str, Any]={}) -> None: """Initialize Configuration Graph Optimization class.""" super().__init__() self.precisions: Optional[str] = None if data.get('precisions'): se...
the_stack_v2_python_sparse
neural_compressor/ux/utils/workload/graph_optimization.py
Skp80/neural-compressor
train
0
de956771add227788c6e5eff5476de0205b34ed4
[ "n = filenames.__len__()\nresult = np.array([])\nprint('开始将图片转为数组')\nfor i in range(n):\n image = Image.open(self.image_base_path + filenames[i])\n r, g, b = image.split()\n r_arr = np.array(r).reshape(1024)\n g_arr = np.array(g).reshape(1024)\n b_arr = np.array(b).reshape(1024)\n image_arr = np.c...
<|body_start_0|> n = filenames.__len__() result = np.array([]) print('开始将图片转为数组') for i in range(n): image = Image.open(self.image_base_path + filenames[i]) r, g, b = image.split() r_arr = np.array(r).reshape(1024) g_arr = np.array(g).resha...
Operation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Operation: def image_to_array(self, filenames): """图片转化为数组并存为二进制文件; :param filenames:文件列表 :return:""" <|body_0|> def array_to_image(self, filename): """从二进制文件中读取数据并重新恢复为图片 :param filename: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> n =...
stack_v2_sparse_classes_36k_train_024060
2,873
no_license
[ { "docstring": "图片转化为数组并存为二进制文件; :param filenames:文件列表 :return:", "name": "image_to_array", "signature": "def image_to_array(self, filenames)" }, { "docstring": "从二进制文件中读取数据并重新恢复为图片 :param filename: :return:", "name": "array_to_image", "signature": "def array_to_image(self, filename)" ...
2
stack_v2_sparse_classes_30k_train_014203
Implement the Python class `Operation` described below. Class description: Implement the Operation class. Method signatures and docstrings: - def image_to_array(self, filenames): 图片转化为数组并存为二进制文件; :param filenames:文件列表 :return: - def array_to_image(self, filename): 从二进制文件中读取数据并重新恢复为图片 :param filename: :return:
Implement the Python class `Operation` described below. Class description: Implement the Operation class. Method signatures and docstrings: - def image_to_array(self, filenames): 图片转化为数组并存为二进制文件; :param filenames:文件列表 :return: - def array_to_image(self, filename): 从二进制文件中读取数据并重新恢复为图片 :param filename: :return: <|skel...
713071a9fbabfabcbc3c16ce58d1382c410a7ea3
<|skeleton|> class Operation: def image_to_array(self, filenames): """图片转化为数组并存为二进制文件; :param filenames:文件列表 :return:""" <|body_0|> def array_to_image(self, filename): """从二进制文件中读取数据并重新恢复为图片 :param filename: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Operation: def image_to_array(self, filenames): """图片转化为数组并存为二进制文件; :param filenames:文件列表 :return:""" n = filenames.__len__() result = np.array([]) print('开始将图片转为数组') for i in range(n): image = Image.open(self.image_base_path + filenames[i]) r, g...
the_stack_v2_python_sparse
ascii_to_str_python/rgb_to_image.py
yangkang411/python_tool
train
0
6df66ae40131c1cedd570c1a85e6a6e44b6e5d1f
[ "result = []\nfor index in range(0, len(T)):\n location = 0\n for compare_index in range(index + 1, len(T)):\n if T[compare_index] > T[index]:\n location = compare_index - index\n break\n result.append(location)\nreturn result", "T = T[::-1]\nmax_num = T[0]\nresult = [0]\nfor...
<|body_start_0|> result = [] for index in range(0, len(T)): location = 0 for compare_index in range(index + 1, len(T)): if T[compare_index] > T[index]: location = compare_index - index break result.append(locatio...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def dailyTemperatures_1(self, T): """这种最简单的策略 肯定是会超时的..人家可是个medium题 :type T: List[int] :rtype: List[int]""" <|body_0|> def dailyTemperatures_3(self, T): """策略2: 还是超时的 从后往前,同时记录最大的元素 如果后面存在比当前大的,则向后找,如果没有就置为0 :param T: :return:""" <|body_1|> def...
stack_v2_sparse_classes_36k_train_024061
2,119
no_license
[ { "docstring": "这种最简单的策略 肯定是会超时的..人家可是个medium题 :type T: List[int] :rtype: List[int]", "name": "dailyTemperatures_1", "signature": "def dailyTemperatures_1(self, T)" }, { "docstring": "策略2: 还是超时的 从后往前,同时记录最大的元素 如果后面存在比当前大的,则向后找,如果没有就置为0 :param T: :return:", "name": "dailyTemperatures_3", ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def dailyTemperatures_1(self, T): 这种最简单的策略 肯定是会超时的..人家可是个medium题 :type T: List[int] :rtype: List[int] - def dailyTemperatures_3(self, T): 策略2: 还是超时的 从后往前,同时记录最大的元素 如果后面存在比当前大的,则向...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def dailyTemperatures_1(self, T): 这种最简单的策略 肯定是会超时的..人家可是个medium题 :type T: List[int] :rtype: List[int] - def dailyTemperatures_3(self, T): 策略2: 还是超时的 从后往前,同时记录最大的元素 如果后面存在比当前大的,则向...
163b376acab84e28c74cb784d10fe39f11510921
<|skeleton|> class Solution: def dailyTemperatures_1(self, T): """这种最简单的策略 肯定是会超时的..人家可是个medium题 :type T: List[int] :rtype: List[int]""" <|body_0|> def dailyTemperatures_3(self, T): """策略2: 还是超时的 从后往前,同时记录最大的元素 如果后面存在比当前大的,则向后找,如果没有就置为0 :param T: :return:""" <|body_1|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def dailyTemperatures_1(self, T): """这种最简单的策略 肯定是会超时的..人家可是个medium题 :type T: List[int] :rtype: List[int]""" result = [] for index in range(0, len(T)): location = 0 for compare_index in range(index + 1, len(T)): if T[compare_index] > T[i...
the_stack_v2_python_sparse
code/739. Daily Temperatures.py
cathyxingchang/leetcode
train
2
40b3ebab8881ad314c844d4c2eb010042b255045
[ "try:\n pecan.request.db_api.delete_domain(uuid=uuid)\nexcept exception.DomainNotFound as e:\n raise wsme.exc.ClientSideError(e.message, status_code=e.code)", "project_id = pecan.request.headers.get('X-Tenant-Id')\nres = pecan.request.db_api.list_domains(project_id=project_id)\nreturn res", "try:\n res...
<|body_start_0|> try: pecan.request.db_api.delete_domain(uuid=uuid) except exception.DomainNotFound as e: raise wsme.exc.ClientSideError(e.message, status_code=e.code) <|end_body_0|> <|body_start_1|> project_id = pecan.request.headers.get('X-Tenant-Id') res = pec...
REST Controller for Domain.
DomainsController
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DomainsController: """REST Controller for Domain.""" def delete(self, uuid): """Delete a domain.""" <|body_0|> def get_all(self): """Retrieve a list of domains.""" <|body_1|> def get_one(self, uuid): """Retrieve information about the given do...
stack_v2_sparse_classes_36k_train_024062
3,577
permissive
[ { "docstring": "Delete a domain.", "name": "delete", "signature": "def delete(self, uuid)" }, { "docstring": "Retrieve a list of domains.", "name": "get_all", "signature": "def get_all(self)" }, { "docstring": "Retrieve information about the given domain.", "name": "get_one",...
5
stack_v2_sparse_classes_30k_test_000766
Implement the Python class `DomainsController` described below. Class description: REST Controller for Domain. Method signatures and docstrings: - def delete(self, uuid): Delete a domain. - def get_all(self): Retrieve a list of domains. - def get_one(self, uuid): Retrieve information about the given domain. - def pos...
Implement the Python class `DomainsController` described below. Class description: REST Controller for Domain. Method signatures and docstrings: - def delete(self, uuid): Delete a domain. - def get_all(self): Retrieve a list of domains. - def get_one(self, uuid): Retrieve information about the given domain. - def pos...
6a9a59df834f08dad001a8439447ed4b699639ed
<|skeleton|> class DomainsController: """REST Controller for Domain.""" def delete(self, uuid): """Delete a domain.""" <|body_0|> def get_all(self): """Retrieve a list of domains.""" <|body_1|> def get_one(self, uuid): """Retrieve information about the given do...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DomainsController: """REST Controller for Domain.""" def delete(self, uuid): """Delete a domain.""" try: pecan.request.db_api.delete_domain(uuid=uuid) except exception.DomainNotFound as e: raise wsme.exc.ClientSideError(e.message, status_code=e.code) d...
the_stack_v2_python_sparse
ripcord/api/controllers/v1/domain.py
kickstandproject/ripcord
train
1
af1db39ad5e3c4a7c4d276843f3793c122dd402b
[ "if len(group) > 3:\n raise AssertionError(\"group '%s' is too long\" % repr(group))\nelif len(group) == 3:\n cols = 'one-third'\n offset_classes = ['', ' offset-by-one-third', ' offset-by-two-thirds']\nelif len(group) == 2:\n cols = 'one-half'\n offset_classes = ['', ' offset-by-one-half']\nelse:\n ...
<|body_start_0|> if len(group) > 3: raise AssertionError("group '%s' is too long" % repr(group)) elif len(group) == 3: cols = 'one-third' offset_classes = ['', ' offset-by-one-third', ' offset-by-two-thirds'] elif len(group) == 2: cols = 'one-half'...
Mixin that provides functions for rendering light-compatible html
BaseFormRenderer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseFormRenderer: """Mixin that provides functions for rendering light-compatible html""" def _render_group(self, group): """Render several fields at the same line Responsive grid is used.""" <|body_0|> def _render_field(self, field): """Render a <section> with a...
stack_v2_sparse_classes_36k_train_024063
4,797
permissive
[ { "docstring": "Render several fields at the same line Responsive grid is used.", "name": "_render_group", "signature": "def _render_group(self, group)" }, { "docstring": "Render a <section> with a single field", "name": "_render_field", "signature": "def _render_field(self, field)" },...
3
null
Implement the Python class `BaseFormRenderer` described below. Class description: Mixin that provides functions for rendering light-compatible html Method signatures and docstrings: - def _render_group(self, group): Render several fields at the same line Responsive grid is used. - def _render_field(self, field): Rend...
Implement the Python class `BaseFormRenderer` described below. Class description: Mixin that provides functions for rendering light-compatible html Method signatures and docstrings: - def _render_group(self, group): Render several fields at the same line Responsive grid is used. - def _render_field(self, field): Rend...
9bf040faac43feae08b33900e30bf7d17b817ae4
<|skeleton|> class BaseFormRenderer: """Mixin that provides functions for rendering light-compatible html""" def _render_group(self, group): """Render several fields at the same line Responsive grid is used.""" <|body_0|> def _render_field(self, field): """Render a <section> with a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseFormRenderer: """Mixin that provides functions for rendering light-compatible html""" def _render_group(self, group): """Render several fields at the same line Responsive grid is used.""" if len(group) > 3: raise AssertionError("group '%s' is too long" % repr(group)) ...
the_stack_v2_python_sparse
s_appearance/forms.py
AmatanHead/collective-blog
train
0
d2cc412e30fb8ab6432776ebfa83e70e630a5bec
[ "super().__init__(cv)\nself.cid = cv.create_polygon(x - 12, 530, x + 12, 530, x, 500, fill='red')\nself.x = x\nself.pps = pps\nself.colors = colors\nself._tospawn = 0", "super().update(dt)\nself._tospawn += self.pps * dt\ncolor = self.colors[int(self.age / 3) % len(self.colors)]\nfor i in range(int(self._tospawn)...
<|body_start_0|> super().__init__(cv) self.cid = cv.create_polygon(x - 12, 530, x + 12, 530, x, 500, fill='red') self.x = x self.pps = pps self.colors = colors self._tospawn = 0 <|end_body_0|> <|body_start_1|> super().update(dt) self._tospawn += self.pps ...
A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn.
Volcano
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Volcano: """A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn.""" def __init__(self, cv, x, pps, colors): """...
stack_v2_sparse_classes_36k_train_024064
16,427
permissive
[ { "docstring": "Init Volcano objects. Args: cv (Tk.canvas): the canvas in which the particle is drawn. x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn.", "name": "__init__", "signature": "def ...
2
stack_v2_sparse_classes_30k_train_005428
Implement the Python class `Volcano` described below. Class description: A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn. Method signatures a...
Implement the Python class `Volcano` described below. Class description: A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn. Method signatures a...
c6b6d80e9d59f5d115ca8b8fc020fcd6cb030af8
<|skeleton|> class Volcano: """A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn.""" def __init__(self, cv, x, pps, colors): """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Volcano: """A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn.""" def __init__(self, cv, x, pps, colors): """Init Volcano ...
the_stack_v2_python_sparse
scripts/sheet9/9.2.py
LennartElbe/PythOnline
train
0
d01e533c15be3ffa5d7717e6909ec649a258309c
[ "self.__ops = ops\nself.__nops = len(ops)\nfor iop in range(self.__nops):\n if not isinstance(self.__ops[iop], operator):\n raise Exception('Elements of ops list must be of type operator')\nif self.__nops != len(dims):\n raise Exception('Number of dimensions (%d) must equal number of operators (%d)' % ...
<|body_start_0|> self.__ops = ops self.__nops = len(ops) for iop in range(self.__nops): if not isinstance(self.__ops[iop], operator): raise Exception('Elements of ops list must be of type operator') if self.__nops != len(dims): raise Exception('Num...
Column operator
colop
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class colop: """Column operator""" def __init__(self, ops, dims, epss): """colop constructor Parameters: ops - a list of operators used to form the column operator dims - a list of dictionaries that contain the dimensions of the inputs and outputs of the arrays For example dims = [{'nrows'...
stack_v2_sparse_classes_36k_train_024065
13,837
no_license
[ { "docstring": "colop constructor Parameters: ops - a list of operators used to form the column operator dims - a list of dictionaries that contain the dimensions of the inputs and outputs of the arrays For example dims = [{'nrows': 10, 'ncols': 10},...] epss - a list of scalar values to be applied to the outpu...
4
stack_v2_sparse_classes_30k_train_010210
Implement the Python class `colop` described below. Class description: Column operator Method signatures and docstrings: - def __init__(self, ops, dims, epss): colop constructor Parameters: ops - a list of operators used to form the column operator dims - a list of dictionaries that contain the dimensions of the inpu...
Implement the Python class `colop` described below. Class description: Column operator Method signatures and docstrings: - def __init__(self, ops, dims, epss): colop constructor Parameters: ops - a list of operators used to form the column operator dims - a list of dictionaries that contain the dimensions of the inpu...
32a303eddd13385d8778b8bb3b4fbbfbe78bea51
<|skeleton|> class colop: """Column operator""" def __init__(self, ops, dims, epss): """colop constructor Parameters: ops - a list of operators used to form the column operator dims - a list of dictionaries that contain the dimensions of the inputs and outputs of the arrays For example dims = [{'nrows'...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class colop: """Column operator""" def __init__(self, ops, dims, epss): """colop constructor Parameters: ops - a list of operators used to form the column operator dims - a list of dictionaries that contain the dimensions of the inputs and outputs of the arrays For example dims = [{'nrows': 10, 'ncols'...
the_stack_v2_python_sparse
opt/linopt/combops.py
ke0m/scaas
train
2
3f926c15183ada0cfe4715addd104d03e55d0818
[ "res = []\nstack = []\nwhile root or stack:\n if root:\n res.append(root.val)\n stack.append(root)\n root = root.left\n else:\n temp = stack.pop()\n root = temp.right\nreturn res", "res = []\nif root:\n res.append(root.val)\n res += self.preorderTraversal(root.left)\...
<|body_start_0|> res = [] stack = [] while root or stack: if root: res.append(root.val) stack.append(root) root = root.left else: temp = stack.pop() root = temp.right return res <|end_...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def preorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_0|> def preorderTraversal2(self, root): """递归解法""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = [] stack = [] while root or stack:...
stack_v2_sparse_classes_36k_train_024066
2,272
no_license
[ { "docstring": ":type root: TreeNode :rtype: List[int]", "name": "preorderTraversal", "signature": "def preorderTraversal(self, root)" }, { "docstring": "递归解法", "name": "preorderTraversal2", "signature": "def preorderTraversal2(self, root)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int] - def preorderTraversal2(self, root): 递归解法
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int] - def preorderTraversal2(self, root): 递归解法 <|skeleton|> class Solution: def preorderTraversal(self...
f022677c042db3598003df1a320a70f0edc4f870
<|skeleton|> class Solution: def preorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_0|> def preorderTraversal2(self, root): """递归解法""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def preorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" res = [] stack = [] while root or stack: if root: res.append(root.val) stack.append(root) root = root.left else: ...
the_stack_v2_python_sparse
BinaryTree/qianxubianli.py
daisyzl/program-exercise-python
train
0
929febb627596ee916e71c996dce8f0a5bd5749c
[ "self.school_name = school_name\nself.city_name = city_name\nself.teachers = teachers\nself.courses = courses\nself.students = students\nself.grades = grades", "attr_list = ['courses', 'teachers', 'students', 'grades']\n\ndef show_attr_value(attr):\n attr_value = getattr(self, attr)\n attr_value_list = attr...
<|body_start_0|> self.school_name = school_name self.city_name = city_name self.teachers = teachers self.courses = courses self.students = students self.grades = grades <|end_body_0|> <|body_start_1|> attr_list = ['courses', 'teachers', 'students', 'grades'] ...
学校类
School
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class School: """学校类""" def __init__(self, school_name, city_name, teachers=None, courses=None, students=None, grades=None): """定义学校属性 :param school_name: 学校名,字符类型 :param city_name: 城市名,字符类型 :param teachers: 讲师,字典类型,eg:{"teacher": []} :param courses: 课程,字典类型,eg:{"courses": []} :param stude...
stack_v2_sparse_classes_36k_train_024067
2,046
no_license
[ { "docstring": "定义学校属性 :param school_name: 学校名,字符类型 :param city_name: 城市名,字符类型 :param teachers: 讲师,字典类型,eg:{\"teacher\": []} :param courses: 课程,字典类型,eg:{\"courses\": []} :param students: 学员,字典类型,eg:{\"students\": []} :param grades: 班级,字典类型,eg:{\"grades\": []}", "name": "__init__", "signature": "def __in...
3
null
Implement the Python class `School` described below. Class description: 学校类 Method signatures and docstrings: - def __init__(self, school_name, city_name, teachers=None, courses=None, students=None, grades=None): 定义学校属性 :param school_name: 学校名,字符类型 :param city_name: 城市名,字符类型 :param teachers: 讲师,字典类型,eg:{"teacher": []...
Implement the Python class `School` described below. Class description: 学校类 Method signatures and docstrings: - def __init__(self, school_name, city_name, teachers=None, courses=None, students=None, grades=None): 定义学校属性 :param school_name: 学校名,字符类型 :param city_name: 城市名,字符类型 :param teachers: 讲师,字典类型,eg:{"teacher": []...
8e304b8ee0680555f328270845ba9a4b5c25f393
<|skeleton|> class School: """学校类""" def __init__(self, school_name, city_name, teachers=None, courses=None, students=None, grades=None): """定义学校属性 :param school_name: 学校名,字符类型 :param city_name: 城市名,字符类型 :param teachers: 讲师,字典类型,eg:{"teacher": []} :param courses: 课程,字典类型,eg:{"courses": []} :param stude...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class School: """学校类""" def __init__(self, school_name, city_name, teachers=None, courses=None, students=None, grades=None): """定义学校属性 :param school_name: 学校名,字符类型 :param city_name: 城市名,字符类型 :param teachers: 讲师,字典类型,eg:{"teacher": []} :param courses: 课程,字典类型,eg:{"courses": []} :param students: 学员,字典类型,...
the_stack_v2_python_sparse
Course_selection_system/course_selection_system/lib/school.py
sdxy0506/pystudy
train
0
e05e0fe9ec1047a1ba206a3e120e6b817c8998df
[ "super().__init__(name, **kwargs)\nself.website_id = 'gsmhosting'\nself.website_type = 'complaint'\nself.forum_list_xpath = '/html/body/div/div[1]/div/table[5]/tbody'\nself.forum_url_xpath = './tr/td/table/tr/td[3]/div/a/@href'\nself.post_list_xpath = '//*[@id=\"threadslist\"]/tbody[2]/tr'\nself.post_url_xpath = '....
<|body_start_0|> super().__init__(name, **kwargs) self.website_id = 'gsmhosting' self.website_type = 'complaint' self.forum_list_xpath = '/html/body/div/div[1]/div/table[5]/tbody' self.forum_url_xpath = './tr/td/table/tr/td[3]/div/a/@href' self.post_list_xpath = '//*[@id=...
解析数据和爬虫逻辑类
MySpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MySpider: """解析数据和爬虫逻辑类""" def __init__(self, name=None, **kwargs): """完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None""" <|body_0|> def parse(self, response): """构造帖子页请求...
stack_v2_sparse_classes_36k_train_024068
4,938
no_license
[ { "docstring": "完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None", "name": "__init__", "signature": "def __init__(self, name=None, **kwargs)" }, { "docstring": "构造帖子页请求", "name": "parse", "signatu...
4
null
Implement the Python class `MySpider` described below. Class description: 解析数据和爬虫逻辑类 Method signatures and docstrings: - def __init__(self, name=None, **kwargs): 完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None - def parse(sel...
Implement the Python class `MySpider` described below. Class description: 解析数据和爬虫逻辑类 Method signatures and docstrings: - def __init__(self, name=None, **kwargs): 完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None - def parse(sel...
1b42878b694fabc65a02228662ffdf819e5dcc71
<|skeleton|> class MySpider: """解析数据和爬虫逻辑类""" def __init__(self, name=None, **kwargs): """完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None""" <|body_0|> def parse(self, response): """构造帖子页请求...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MySpider: """解析数据和爬虫逻辑类""" def __init__(self, name=None, **kwargs): """完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None""" super().__init__(name, **kwargs) self.website_id = 'gsmhosting' ...
the_stack_v2_python_sparse
wujian/gsmhosting/gsmhosting/spiders/gsmhosting.py
wangsanshi123/spiders
train
0
7d84024d66d83e60f89d929e8b891effb923f7a8
[ "test_report_url = URL(f'{urls[0]}/lastSuccessfulBuild/testReport/api/json')\njob_url = URL(f'{urls[0]}/lastSuccessfulBuild/api/json')\nreturn await super()._get_source_responses(test_report_url, job_url)", "timestamps = [suite.get('timestamp') for suite in (await responses[0].json()).get('suites', []) if suite.g...
<|body_start_0|> test_report_url = URL(f'{urls[0]}/lastSuccessfulBuild/testReport/api/json') job_url = URL(f'{urls[0]}/lastSuccessfulBuild/api/json') return await super()._get_source_responses(test_report_url, job_url) <|end_body_0|> <|body_start_1|> timestamps = [suite.get('timestamp')...
Collector to get the age of the Jenkins test report.
JenkinsTestReportSourceUpToDateness
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JenkinsTestReportSourceUpToDateness: """Collector to get the age of the Jenkins test report.""" async def _get_source_responses(self, *urls: URL) -> SourceResponses: """Extend to get both the test report and the job that created it, so we can use either one to get a date.""" ...
stack_v2_sparse_classes_36k_train_024069
1,391
permissive
[ { "docstring": "Extend to get both the test report and the job that created it, so we can use either one to get a date.", "name": "_get_source_responses", "signature": "async def _get_source_responses(self, *urls: URL) -> SourceResponses" }, { "docstring": "Override to parse the timestamp from e...
2
null
Implement the Python class `JenkinsTestReportSourceUpToDateness` described below. Class description: Collector to get the age of the Jenkins test report. Method signatures and docstrings: - async def _get_source_responses(self, *urls: URL) -> SourceResponses: Extend to get both the test report and the job that create...
Implement the Python class `JenkinsTestReportSourceUpToDateness` described below. Class description: Collector to get the age of the Jenkins test report. Method signatures and docstrings: - async def _get_source_responses(self, *urls: URL) -> SourceResponses: Extend to get both the test report and the job that create...
5d9952bf0bd47895824fa78428d3e4f4d6b5d9b3
<|skeleton|> class JenkinsTestReportSourceUpToDateness: """Collector to get the age of the Jenkins test report.""" async def _get_source_responses(self, *urls: URL) -> SourceResponses: """Extend to get both the test report and the job that created it, so we can use either one to get a date.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JenkinsTestReportSourceUpToDateness: """Collector to get the age of the Jenkins test report.""" async def _get_source_responses(self, *urls: URL) -> SourceResponses: """Extend to get both the test report and the job that created it, so we can use either one to get a date.""" test_report_u...
the_stack_v2_python_sparse
components/collector/src/source_collectors/jenkins_test_report/source_up_to_dateness.py
ICTU/quality-time
train
43
f1bbda7ddd2306db1412e9be4e0b784f9a65e5bd
[ "def _val_check(val, name):\n if val < 0 or val > 255:\n raise ValueError(f'Invalid {name} value. Should be 0~255. ({val})')\n_val_check(red, 'RED')\n_val_check(green, 'GREEN')\n_val_check(blue, 'BLUE')\nreturn Color(red * 65536 + green * 256 + blue)", "if not re.match('#?[0-9A-Fa-f]{6}', hex_str):\n ...
<|body_start_0|> def _val_check(val, name): if val < 0 or val > 255: raise ValueError(f'Invalid {name} value. Should be 0~255. ({val})') _val_check(red, 'RED') _val_check(green, 'GREEN') _val_check(blue, 'BLUE') return Color(red * 65536 + green * 256 +...
Factory class to generate :class:`Color`.
ColorFactory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ColorFactory: """Factory class to generate :class:`Color`.""" def from_rgb(red: int, green: int, blue: int) -> Color: """Generate a :class:`Color` from RGB. :return: a `Color` with using the provided RGB values :raises ValueError: any of `red`, `green` or `blue` is invalid""" ...
stack_v2_sparse_classes_36k_train_024070
4,009
permissive
[ { "docstring": "Generate a :class:`Color` from RGB. :return: a `Color` with using the provided RGB values :raises ValueError: any of `red`, `green` or `blue` is invalid", "name": "from_rgb", "signature": "def from_rgb(red: int, green: int, blue: int) -> Color" }, { "docstring": "Generate a :clas...
2
stack_v2_sparse_classes_30k_train_009210
Implement the Python class `ColorFactory` described below. Class description: Factory class to generate :class:`Color`. Method signatures and docstrings: - def from_rgb(red: int, green: int, blue: int) -> Color: Generate a :class:`Color` from RGB. :return: a `Color` with using the provided RGB values :raises ValueErr...
Implement the Python class `ColorFactory` described below. Class description: Factory class to generate :class:`Color`. Method signatures and docstrings: - def from_rgb(red: int, green: int, blue: int) -> Color: Generate a :class:`Color` from RGB. :return: a `Color` with using the provided RGB values :raises ValueErr...
c7da1e91783dce3a2b71b955b3a22b68db9056cf
<|skeleton|> class ColorFactory: """Factory class to generate :class:`Color`.""" def from_rgb(red: int, green: int, blue: int) -> Color: """Generate a :class:`Color` from RGB. :return: a `Color` with using the provided RGB values :raises ValueError: any of `red`, `green` or `blue` is invalid""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ColorFactory: """Factory class to generate :class:`Color`.""" def from_rgb(red: int, green: int, blue: int) -> Color: """Generate a :class:`Color` from RGB. :return: a `Color` with using the provided RGB values :raises ValueError: any of `red`, `green` or `blue` is invalid""" def _val_che...
the_stack_v2_python_sparse
extutils/color.py
RxJellyBot/Jelly-Bot
train
5
932e17161b7d8c2dc80357df9436978e8db852ab
[ "super().__init__()\nself._solution_dim = solution_dim\nself._population_size = population_size\nself._upper_bound = upper_bound\nself._lower_bound = lower_bound", "init_obs = time_step.observation\nbatch_size = init_obs.shape[0]\nsolutions = tf.random.uniform([batch_size, self._population_size, self._solution_di...
<|body_start_0|> super().__init__() self._solution_dim = solution_dim self._population_size = population_size self._upper_bound = upper_bound self._lower_bound = lower_bound <|end_body_0|> <|body_start_1|> init_obs = time_step.observation batch_size = init_obs.sh...
RandomOptimizer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomOptimizer: def __init__(self, solution_dim, population_size, upper_bound=None, lower_bound=None): """Creates a Random Optimizer Args: solution_dim (int): The dimensionality of the problem space population_size (int): The number of candidate solutions to be sampled at every iteratio...
stack_v2_sparse_classes_36k_train_024071
2,535
permissive
[ { "docstring": "Creates a Random Optimizer Args: solution_dim (int): The dimensionality of the problem space population_size (int): The number of candidate solutions to be sampled at every iteration upper_bound (int|tf.Tensor): upper bounds for elements in solution lower_bound (int|tf.Tensor): lower bounds for ...
2
null
Implement the Python class `RandomOptimizer` described below. Class description: Implement the RandomOptimizer class. Method signatures and docstrings: - def __init__(self, solution_dim, population_size, upper_bound=None, lower_bound=None): Creates a Random Optimizer Args: solution_dim (int): The dimensionality of th...
Implement the Python class `RandomOptimizer` described below. Class description: Implement the RandomOptimizer class. Method signatures and docstrings: - def __init__(self, solution_dim, population_size, upper_bound=None, lower_bound=None): Creates a Random Optimizer Args: solution_dim (int): The dimensionality of th...
38a3621337a030f74bb3944d7695e7642e777e10
<|skeleton|> class RandomOptimizer: def __init__(self, solution_dim, population_size, upper_bound=None, lower_bound=None): """Creates a Random Optimizer Args: solution_dim (int): The dimensionality of the problem space population_size (int): The number of candidate solutions to be sampled at every iteratio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomOptimizer: def __init__(self, solution_dim, population_size, upper_bound=None, lower_bound=None): """Creates a Random Optimizer Args: solution_dim (int): The dimensionality of the problem space population_size (int): The number of candidate solutions to be sampled at every iteration upper_bound ...
the_stack_v2_python_sparse
alf/optimizers/random.py
Haichao-Zhang/alf
train
1
790d03b54f8aeffadcf587f0f79de7a2b2e9b81e
[ "parser.display_info.AddFormat(vmware_constants.VMWARE_CLUSTERS_FORMAT)\nflags.AddClusterResourceArg(parser, 'to update', True)\nbase.ASYNC_FLAG.AddToParser(parser)\nflags.AddValidationOnly(parser)\nflags.AddAllowMissingUpdateCluster(parser)\nflags.AddDescription(parser)\nflags.AddVersion(parser)\nflags.AddVmwareCo...
<|body_start_0|> parser.display_info.AddFormat(vmware_constants.VMWARE_CLUSTERS_FORMAT) flags.AddClusterResourceArg(parser, 'to update', True) base.ASYNC_FLAG.AddToParser(parser) flags.AddValidationOnly(parser) flags.AddAllowMissingUpdateCluster(parser) flags.AddDescripti...
Update an Anthos cluster on VMware.
UpdateAlpha
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpdateAlpha: """Update an Anthos cluster on VMware.""" def Args(parser: parser_arguments.ArgumentInterceptor): """Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to.""" <|body_0|> def Run(self, args): """Ru...
stack_v2_sparse_classes_36k_train_024072
6,033
permissive
[ { "docstring": "Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to.", "name": "Args", "signature": "def Args(parser: parser_arguments.ArgumentInterceptor)" }, { "docstring": "Runs the update command. Args: args: The arguments received from...
2
null
Implement the Python class `UpdateAlpha` described below. Class description: Update an Anthos cluster on VMware. Method signatures and docstrings: - def Args(parser: parser_arguments.ArgumentInterceptor): Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to. - de...
Implement the Python class `UpdateAlpha` described below. Class description: Update an Anthos cluster on VMware. Method signatures and docstrings: - def Args(parser: parser_arguments.ArgumentInterceptor): Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to. - de...
392abf004b16203030e6efd2f0af24db7c8d669e
<|skeleton|> class UpdateAlpha: """Update an Anthos cluster on VMware.""" def Args(parser: parser_arguments.ArgumentInterceptor): """Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to.""" <|body_0|> def Run(self, args): """Ru...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UpdateAlpha: """Update an Anthos cluster on VMware.""" def Args(parser: parser_arguments.ArgumentInterceptor): """Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to.""" parser.display_info.AddFormat(vmware_constants.VMWARE_CLUSTERS_...
the_stack_v2_python_sparse
lib/surface/container/vmware/clusters/update.py
google-cloud-sdk-unofficial/google-cloud-sdk
train
9
df991fae2ebcdfcd7c77d4bb3823460efc2827d6
[ "self.max_length = max_length\nself.coder = coder\nself.base_pos = base_pos\nself.pos = base_pos\nself.end_pos = end_pos or os.path.getsize(textfile)\nif base_pos >= self.end_pos:\n raise Exception('base position should come before end position')\nself.textfile = textfile", "line_id, line, looped = self.read_l...
<|body_start_0|> self.max_length = max_length self.coder = coder self.base_pos = base_pos self.pos = base_pos self.end_pos = end_pos or os.path.getsize(textfile) if base_pos >= self.end_pos: raise Exception('base position should come before end position') ...
reads text from disk
TextReader
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextReader: """reads text from disk""" def __init__(self, textfile, max_length, coder, base_pos=0, end_pos=None): """TextReader constructor Args: textfile: the path to the file containing the text max_length: the maximal length of a line coder: a TargetCoder object base_pos: the base...
stack_v2_sparse_classes_36k_train_024073
3,606
permissive
[ { "docstring": "TextReader constructor Args: textfile: the path to the file containing the text max_length: the maximal length of a line coder: a TargetCoder object base_pos: the base postion where to start reading in the file end_pos: optional maximal position in the file", "name": "__init__", "signatu...
5
stack_v2_sparse_classes_30k_train_006484
Implement the Python class `TextReader` described below. Class description: reads text from disk Method signatures and docstrings: - def __init__(self, textfile, max_length, coder, base_pos=0, end_pos=None): TextReader constructor Args: textfile: the path to the file containing the text max_length: the maximal length...
Implement the Python class `TextReader` described below. Class description: reads text from disk Method signatures and docstrings: - def __init__(self, textfile, max_length, coder, base_pos=0, end_pos=None): TextReader constructor Args: textfile: the path to the file containing the text max_length: the maximal length...
fb530cf617ff86fe8a249d4582dfe90a303da295
<|skeleton|> class TextReader: """reads text from disk""" def __init__(self, textfile, max_length, coder, base_pos=0, end_pos=None): """TextReader constructor Args: textfile: the path to the file containing the text max_length: the maximal length of a line coder: a TargetCoder object base_pos: the base...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TextReader: """reads text from disk""" def __init__(self, textfile, max_length, coder, base_pos=0, end_pos=None): """TextReader constructor Args: textfile: the path to the file containing the text max_length: the maximal length of a line coder: a TargetCoder object base_pos: the base postion wher...
the_stack_v2_python_sparse
nabu/processing/text_reader.py
DavidKarlas/nabu
train
1
760b969fe36b47e6d3ed46d2248849b5cf74baaf
[ "with sqlite3.connect('example.db') as conn:\n c = conn.cursor()\n try:\n c.execute('create table stocks\\n (date text, trans text, symbol text, qty real, price real)')\n except sqlite3.OperationalError:\n pass\n timestamp = time()\n date = datetime.fromtimestamp(timestamp).str...
<|body_start_0|> with sqlite3.connect('example.db') as conn: c = conn.cursor() try: c.execute('create table stocks\n (date text, trans text, symbol text, qty real, price real)') except sqlite3.OperationalError: pass timesta...
A simplified class to buy stock in Amazon
Amazon
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Amazon: """A simplified class to buy stock in Amazon""" def buy_amazon(self, quantity, purchase_price): """Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to purchase purchase_price -- (real) The price at which the s...
stack_v2_sparse_classes_36k_train_024074
2,429
no_license
[ { "docstring": "Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to purchase purchase_price -- (real) The price at which the stocks were purchased", "name": "buy_amazon", "signature": "def buy_amazon(self, quantity, purchase_price)" },...
4
stack_v2_sparse_classes_30k_train_005667
Implement the Python class `Amazon` described below. Class description: A simplified class to buy stock in Amazon Method signatures and docstrings: - def buy_amazon(self, quantity, purchase_price): Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to p...
Implement the Python class `Amazon` described below. Class description: A simplified class to buy stock in Amazon Method signatures and docstrings: - def buy_amazon(self, quantity, purchase_price): Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to p...
fb2d1a903fd287e0dbc963963f322eccdc1546bb
<|skeleton|> class Amazon: """A simplified class to buy stock in Amazon""" def buy_amazon(self, quantity, purchase_price): """Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to purchase purchase_price -- (real) The price at which the s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Amazon: """A simplified class to buy stock in Amazon""" def buy_amazon(self, quantity, purchase_price): """Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to purchase purchase_price -- (real) The price at which the stocks were pu...
the_stack_v2_python_sparse
NSS/practice/python_and_sql/amazon.py
megducharme/Python_Exercises
train
0
cc38e48cb8b5603abdfca0d2efe7236cc18a449c
[ "msg.bold('pyro ...')\nif solver_name not in valid_solvers:\n msg.fail(f'ERROR: {solver_name} is not a valid solver')\nself.pyro_home = os.path.dirname(os.path.realpath(__file__)) + '/'\nif not solver_name.startswith('pyro.'):\n solver_import = 'pyro.' + solver_name\nelse:\n solver_import = solver_name\nse...
<|body_start_0|> msg.bold('pyro ...') if solver_name not in valid_solvers: msg.fail(f'ERROR: {solver_name} is not a valid solver') self.pyro_home = os.path.dirname(os.path.realpath(__file__)) + '/' if not solver_name.startswith('pyro.'): solver_import = 'pyro.' + ...
The main driver to run pyro.
Pyro
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Pyro: """The main driver to run pyro.""" def __init__(self, solver_name): """Constructor Parameters ---------- solver_name : str Name of solver to use""" <|body_0|> def initialize_problem(self, problem_name, inputs_file=None, inputs_dict=None, other_commands=None): ...
stack_v2_sparse_classes_36k_train_024075
11,814
permissive
[ { "docstring": "Constructor Parameters ---------- solver_name : str Name of solver to use", "name": "__init__", "signature": "def __init__(self, solver_name)" }, { "docstring": "Initialize the specific problem Parameters ---------- problem_name : str Name of the problem inputs_file : str Filenam...
6
stack_v2_sparse_classes_30k_train_008195
Implement the Python class `Pyro` described below. Class description: The main driver to run pyro. Method signatures and docstrings: - def __init__(self, solver_name): Constructor Parameters ---------- solver_name : str Name of solver to use - def initialize_problem(self, problem_name, inputs_file=None, inputs_dict=N...
Implement the Python class `Pyro` described below. Class description: The main driver to run pyro. Method signatures and docstrings: - def __init__(self, solver_name): Constructor Parameters ---------- solver_name : str Name of solver to use - def initialize_problem(self, problem_name, inputs_file=None, inputs_dict=N...
f91789a319caa98dfbc3f496e9953756e6ee3ca9
<|skeleton|> class Pyro: """The main driver to run pyro.""" def __init__(self, solver_name): """Constructor Parameters ---------- solver_name : str Name of solver to use""" <|body_0|> def initialize_problem(self, problem_name, inputs_file=None, inputs_dict=None, other_commands=None): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Pyro: """The main driver to run pyro.""" def __init__(self, solver_name): """Constructor Parameters ---------- solver_name : str Name of solver to use""" msg.bold('pyro ...') if solver_name not in valid_solvers: msg.fail(f'ERROR: {solver_name} is not a valid solver') ...
the_stack_v2_python_sparse
pyro/pyro_sim.py
python-hydro/pyro2
train
202
d4ec8f8729eecd0b281f940eee5246c88529ae16
[ "def dfs(root, ret):\n if root is None:\n ret.append('#')\n return\n ret.append(str(root.val) + ',' + str(len(root.children)))\n for each in root.children:\n dfs(each, ret)\nret = []\ndfs(root, ret)\nreturn ' '.join(ret)", "def dfs(vals):\n val = next(vals).split(',')\n if val[...
<|body_start_0|> def dfs(root, ret): if root is None: ret.append('#') return ret.append(str(root.val) + ',' + str(len(root.children))) for each in root.children: dfs(each, ret) ret = [] dfs(root, ret) ret...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_36k_train_024076
4,629
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: Node :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node", "name": "deserialize", "signature": "def deserialize(self, ...
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: Node :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod...
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: Node :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod...
9190d3d178f1733aa226973757ee7e045b7bab00
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|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: Node :rtype: str""" def dfs(root, ret): if root is None: ret.append('#') return ret.append(str(root.val) + ',' + str(len(root.children))) for ...
the_stack_v2_python_sparse
SerializeAndDeserializeN-aryTree.py
ellinx/LC-python
train
1
0eff3812df4e997b06ddb7419f2a895f1b87c0ac
[ "super().__init__(coordinator)\nself.entity_description: AsusWrtSensorEntityDescription = description\nself._attr_name = f'{router.name} {description.name}'\nif router.unique_id:\n self._attr_unique_id = f'{DOMAIN} {router.unique_id} {description.name}'\nelse:\n self._attr_unique_id = f'{DOMAIN} {self.name}'\...
<|body_start_0|> super().__init__(coordinator) self.entity_description: AsusWrtSensorEntityDescription = description self._attr_name = f'{router.name} {description.name}' if router.unique_id: self._attr_unique_id = f'{DOMAIN} {router.unique_id} {description.name}' els...
Representation of a AsusWrt sensor.
AsusWrtSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AsusWrtSensor: """Representation of a AsusWrt sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, router: AsusWrtRouter, description: AsusWrtSensorEntityDescription) -> None: """Initialize a AsusWrt sensor.""" <|body_0|> def native_value(self) -> float | in...
stack_v2_sparse_classes_36k_train_024077
7,109
permissive
[ { "docstring": "Initialize a AsusWrt sensor.", "name": "__init__", "signature": "def __init__(self, coordinator: DataUpdateCoordinator, router: AsusWrtRouter, description: AsusWrtSensorEntityDescription) -> None" }, { "docstring": "Return current state.", "name": "native_value", "signatu...
2
stack_v2_sparse_classes_30k_train_013105
Implement the Python class `AsusWrtSensor` described below. Class description: Representation of a AsusWrt sensor. Method signatures and docstrings: - def __init__(self, coordinator: DataUpdateCoordinator, router: AsusWrtRouter, description: AsusWrtSensorEntityDescription) -> None: Initialize a AsusWrt sensor. - def ...
Implement the Python class `AsusWrtSensor` described below. Class description: Representation of a AsusWrt sensor. Method signatures and docstrings: - def __init__(self, coordinator: DataUpdateCoordinator, router: AsusWrtRouter, description: AsusWrtSensorEntityDescription) -> None: Initialize a AsusWrt sensor. - def ...
2e65b77b2b5c17919939481f327963abdfdc53f0
<|skeleton|> class AsusWrtSensor: """Representation of a AsusWrt sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, router: AsusWrtRouter, description: AsusWrtSensorEntityDescription) -> None: """Initialize a AsusWrt sensor.""" <|body_0|> def native_value(self) -> float | in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AsusWrtSensor: """Representation of a AsusWrt sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, router: AsusWrtRouter, description: AsusWrtSensorEntityDescription) -> None: """Initialize a AsusWrt sensor.""" super().__init__(coordinator) self.entity_description: As...
the_stack_v2_python_sparse
homeassistant/components/asuswrt/sensor.py
konnected-io/home-assistant
train
24
bfc0bc30d3e6fb089895488b1055641d177977e2
[ "self.coresys: CoreSys = coresys\nself.repositories: dict[str, Any] = {}\nself.addons: dict[str, Any] = {}", "self.repositories.clear()\nself.addons.clear()\nawait self._read_addons_folder(self.sys_config.path_addons_core, REPOSITORY_CORE)\nawait self._read_addons_folder(self.sys_config.path_addons_local, REPOSIT...
<|body_start_0|> self.coresys: CoreSys = coresys self.repositories: dict[str, Any] = {} self.addons: dict[str, Any] = {} <|end_body_0|> <|body_start_1|> self.repositories.clear() self.addons.clear() await self._read_addons_folder(self.sys_config.path_addons_core, REPOSIT...
Hold data for Add-ons inside Supervisor.
StoreData
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StoreData: """Hold data for Add-ons inside Supervisor.""" def __init__(self, coresys: CoreSys): """Initialize data holder.""" <|body_0|> async def update(self) -> None: """Read data from add-on repository.""" <|body_1|> async def _find_addons(self, p...
stack_v2_sparse_classes_36k_train_024078
7,731
permissive
[ { "docstring": "Initialize data holder.", "name": "__init__", "signature": "def __init__(self, coresys: CoreSys)" }, { "docstring": "Read data from add-on repository.", "name": "update", "signature": "async def update(self) -> None" }, { "docstring": "Find add-ons in the path.", ...
5
null
Implement the Python class `StoreData` described below. Class description: Hold data for Add-ons inside Supervisor. Method signatures and docstrings: - def __init__(self, coresys: CoreSys): Initialize data holder. - async def update(self) -> None: Read data from add-on repository. - async def _find_addons(self, path:...
Implement the Python class `StoreData` described below. Class description: Hold data for Add-ons inside Supervisor. Method signatures and docstrings: - def __init__(self, coresys: CoreSys): Initialize data holder. - async def update(self) -> None: Read data from add-on repository. - async def _find_addons(self, path:...
4838b280adafed0997f32e021274b531178386cd
<|skeleton|> class StoreData: """Hold data for Add-ons inside Supervisor.""" def __init__(self, coresys: CoreSys): """Initialize data holder.""" <|body_0|> async def update(self) -> None: """Read data from add-on repository.""" <|body_1|> async def _find_addons(self, p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StoreData: """Hold data for Add-ons inside Supervisor.""" def __init__(self, coresys: CoreSys): """Initialize data holder.""" self.coresys: CoreSys = coresys self.repositories: dict[str, Any] = {} self.addons: dict[str, Any] = {} async def update(self) -> None: ...
the_stack_v2_python_sparse
supervisor/store/data.py
home-assistant/supervisor
train
928
3b0500c0808a64fbd32ddcf5d89f352865a7267d
[ "if request.user != self.get_object().owner:\n raise Http404\nreturn super().dispatch(request, *args, **kwargs)", "context = super().get_context_data(**kwargs)\ncontext['description'] = self.get_object().description\nreturn context" ]
<|body_start_0|> if request.user != self.get_object().owner: raise Http404 return super().dispatch(request, *args, **kwargs) <|end_body_0|> <|body_start_1|> context = super().get_context_data(**kwargs) context['description'] = self.get_object().description return con...
Actualizar una alerta.
AlertUpdateView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlertUpdateView: """Actualizar una alerta.""" def dispatch(self, request, *args, **kwargs): """Comprueba que el usuario es el owner de la alerta.""" <|body_0|> def get_context_data(self, **kwargs): """Añadir al contexto la descripción de la alerta.""" <|b...
stack_v2_sparse_classes_36k_train_024079
4,726
no_license
[ { "docstring": "Comprueba que el usuario es el owner de la alerta.", "name": "dispatch", "signature": "def dispatch(self, request, *args, **kwargs)" }, { "docstring": "Añadir al contexto la descripción de la alerta.", "name": "get_context_data", "signature": "def get_context_data(self, *...
2
null
Implement the Python class `AlertUpdateView` described below. Class description: Actualizar una alerta. Method signatures and docstrings: - def dispatch(self, request, *args, **kwargs): Comprueba que el usuario es el owner de la alerta. - def get_context_data(self, **kwargs): Añadir al contexto la descripción de la a...
Implement the Python class `AlertUpdateView` described below. Class description: Actualizar una alerta. Method signatures and docstrings: - def dispatch(self, request, *args, **kwargs): Comprueba que el usuario es el owner de la alerta. - def get_context_data(self, **kwargs): Añadir al contexto la descripción de la a...
44b8d2934105ccbf02ff6c20896aa8c2b1746eaa
<|skeleton|> class AlertUpdateView: """Actualizar una alerta.""" def dispatch(self, request, *args, **kwargs): """Comprueba que el usuario es el owner de la alerta.""" <|body_0|> def get_context_data(self, **kwargs): """Añadir al contexto la descripción de la alerta.""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AlertUpdateView: """Actualizar una alerta.""" def dispatch(self, request, *args, **kwargs): """Comprueba que el usuario es el owner de la alerta.""" if request.user != self.get_object().owner: raise Http404 return super().dispatch(request, *args, **kwargs) def get...
the_stack_v2_python_sparse
src/apps/alerts/views.py
snicoper/ofervivienda
train
1
d1a28dc686d3a0f30cf5064f07db446b4cb7c7d5
[ "if data is None:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\n self.lambtha = lambtha\nelse:\n if type(data) is not list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple values')\n self.lam...
<|body_start_0|> if data is None: if lambtha <= 0: raise ValueError('lambtha must be a positive value') self.lambtha = lambtha else: if type(data) is not list: raise TypeError('data must be a list') if len(data) < 2: ...
Poisson distribution class
Poisson
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Poisson: """Poisson distribution class""" def __init__(self, data=None, lambtha=1.0): """Poisson intialization""" <|body_0|> def pmf(self, k): """calculates value of PMF for given number of successes Args: k (int): the number of “successes” Returns: (int) the PMF...
stack_v2_sparse_classes_36k_train_024080
1,611
no_license
[ { "docstring": "Poisson intialization", "name": "__init__", "signature": "def __init__(self, data=None, lambtha=1.0)" }, { "docstring": "calculates value of PMF for given number of successes Args: k (int): the number of “successes” Returns: (int) the PMF value for k", "name": "pmf", "sig...
3
null
Implement the Python class `Poisson` described below. Class description: Poisson distribution class Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): Poisson intialization - def pmf(self, k): calculates value of PMF for given number of successes Args: k (int): the number of “successes” R...
Implement the Python class `Poisson` described below. Class description: Poisson distribution class Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): Poisson intialization - def pmf(self, k): calculates value of PMF for given number of successes Args: k (int): the number of “successes” R...
2eb7965900fd018f4092d2fb1e2055d35ba4899e
<|skeleton|> class Poisson: """Poisson distribution class""" def __init__(self, data=None, lambtha=1.0): """Poisson intialization""" <|body_0|> def pmf(self, k): """calculates value of PMF for given number of successes Args: k (int): the number of “successes” Returns: (int) the PMF...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Poisson: """Poisson distribution class""" def __init__(self, data=None, lambtha=1.0): """Poisson intialization""" if data is None: if lambtha <= 0: raise ValueError('lambtha must be a positive value') self.lambtha = lambtha else: ...
the_stack_v2_python_sparse
math/0x03-probability/poisson.py
s0m35h1t/holbertonschool-machine_learning
train
0
5493ad710279bda247a961503a88a92787165840
[ "parser.add_argument('usernames', metavar='USERNAME', nargs='*', help=_('Specific GitHub account users to reset. If not provided, all users will be reset.'))\nparser.add_argument('--yes', action='store_true', default=False, dest='force_yes', help=_('Answer yes to all questions'))\nparser.add_argument('--local-sites...
<|body_start_0|> parser.add_argument('usernames', metavar='USERNAME', nargs='*', help=_('Specific GitHub account users to reset. If not provided, all users will be reset.')) parser.add_argument('--yes', action='store_true', default=False, dest='force_yes', help=_('Answer yes to all questions')) ...
Management command for resetting GitHub auth tokens.
Command
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Command: """Management command for resetting GitHub auth tokens.""" def add_arguments(self, parser): """Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command.""" <|body_0|> def handle(self, *usernames, **options): ...
stack_v2_sparse_classes_36k_train_024081
4,284
permissive
[ { "docstring": "Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command.", "name": "add_arguments", "signature": "def add_arguments(self, parser)" }, { "docstring": "Handle the command. Args: *usernames (tuple): A list of usernames containing tok...
3
stack_v2_sparse_classes_30k_train_015304
Implement the Python class `Command` described below. Class description: Management command for resetting GitHub auth tokens. Method signatures and docstrings: - def add_arguments(self, parser): Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command. - def handle(sel...
Implement the Python class `Command` described below. Class description: Management command for resetting GitHub auth tokens. Method signatures and docstrings: - def add_arguments(self, parser): Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command. - def handle(sel...
563c1e8d4dfd860f372281dc0f380a0809f6ae15
<|skeleton|> class Command: """Management command for resetting GitHub auth tokens.""" def add_arguments(self, parser): """Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command.""" <|body_0|> def handle(self, *usernames, **options): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Command: """Management command for resetting GitHub auth tokens.""" def add_arguments(self, parser): """Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command.""" parser.add_argument('usernames', metavar='USERNAME', nargs='*', help=_('Spe...
the_stack_v2_python_sparse
reviewboard/hostingsvcs/management/commands/reset-github-tokens.py
LloydFinch/reviewboard
train
2
e915bde217967d7190e4f2c7576370f4806ebffa
[ "try:\n with open(self.file_name, mode) as file:\n file.write(data)\nexcept FileNotFoundError:\n with open(self.file_name, 'wb') as file:\n file.write(data)\nexcept EOFError:\n with open(self.file_name, 'wb') as file:\n file.write(data)", "try:\n with open(self.file_name, mode) as...
<|body_start_0|> try: with open(self.file_name, mode) as file: file.write(data) except FileNotFoundError: with open(self.file_name, 'wb') as file: file.write(data) except EOFError: with open(self.file_name, 'wb') as file: ...
Use read-write mode process files.
ReadWriteFileProcess
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReadWriteFileProcess: """Use read-write mode process files.""" def write(self, data, mode): """Write file.""" <|body_0|> def writelines(self, data, mode): """Write file in lines.""" <|body_1|> def read(self, mode, return_form='str'): """Read ...
stack_v2_sparse_classes_36k_train_024082
2,057
no_license
[ { "docstring": "Write file.", "name": "write", "signature": "def write(self, data, mode)" }, { "docstring": "Write file in lines.", "name": "writelines", "signature": "def writelines(self, data, mode)" }, { "docstring": "Read file.", "name": "read", "signature": "def read...
3
stack_v2_sparse_classes_30k_train_009644
Implement the Python class `ReadWriteFileProcess` described below. Class description: Use read-write mode process files. Method signatures and docstrings: - def write(self, data, mode): Write file. - def writelines(self, data, mode): Write file in lines. - def read(self, mode, return_form='str'): Read file.
Implement the Python class `ReadWriteFileProcess` described below. Class description: Use read-write mode process files. Method signatures and docstrings: - def write(self, data, mode): Write file. - def writelines(self, data, mode): Write file in lines. - def read(self, mode, return_form='str'): Read file. <|skelet...
1e8340303809d8c7c3af3201084b158c1784f22e
<|skeleton|> class ReadWriteFileProcess: """Use read-write mode process files.""" def write(self, data, mode): """Write file.""" <|body_0|> def writelines(self, data, mode): """Write file in lines.""" <|body_1|> def read(self, mode, return_form='str'): """Read ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReadWriteFileProcess: """Use read-write mode process files.""" def write(self, data, mode): """Write file.""" try: with open(self.file_name, mode) as file: file.write(data) except FileNotFoundError: with open(self.file_name, 'wb') as file: ...
the_stack_v2_python_sparse
python_project/project/auto_reply_robot/utility/files_helper.py
skymoonfp/python_learning
train
0
24c91ec11dd69fd6b36d2253ceaeabeaf9123db4
[ "self.db_UF = db_UF\nself.db_OF = db_OF\nself.k_UF = k_UF\nself.k_OF = k_OF\nself.P_avl = P_avl\nself.P_min = P_min\nself.P_pre = P_pre", "if f < 60 - self.db_UF:\n P = min(self.P_pre + (60 - self.db_UF - f) / (60 * self.k_UF), self.P_avl)\nelif f > 60 + self.db_OF:\n P = max(self.P_pre - (f - (60 + self.db...
<|body_start_0|> self.db_UF = db_UF self.db_OF = db_OF self.k_UF = k_UF self.k_OF = k_OF self.P_avl = P_avl self.P_min = P_min self.P_pre = P_pre <|end_body_0|> <|body_start_1|> if f < 60 - self.db_UF: P = min(self.P_pre + (60 - self.db_UF - f...
This class describes Frequency-Droop operation of device fleet
FrequencyDroop
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FrequencyDroop: """This class describes Frequency-Droop operation of device fleet""" def __init__(self, db_UF, db_OF, k_UF, k_OF, P_avl, P_min, P_pre): """initiating variables to evaluate the Frequency-Droop function parameters defining curve: db_UF,db_OF,k_UF,k_OF State variable: P_...
stack_v2_sparse_classes_36k_train_024083
2,094
permissive
[ { "docstring": "initiating variables to evaluate the Frequency-Droop function parameters defining curve: db_UF,db_OF,k_UF,k_OF State variable: P_avl,P_min,P_pre State variables will be updated by the fleet whenever the state of the fleet changes parameters will be updated by the high level controller whenever a...
2
stack_v2_sparse_classes_30k_train_021362
Implement the Python class `FrequencyDroop` described below. Class description: This class describes Frequency-Droop operation of device fleet Method signatures and docstrings: - def __init__(self, db_UF, db_OF, k_UF, k_OF, P_avl, P_min, P_pre): initiating variables to evaluate the Frequency-Droop function parameters...
Implement the Python class `FrequencyDroop` described below. Class description: This class describes Frequency-Droop operation of device fleet Method signatures and docstrings: - def __init__(self, db_UF, db_OF, k_UF, k_OF, P_avl, P_min, P_pre): initiating variables to evaluate the Frequency-Droop function parameters...
07ff5c6505aa6ab0a7c0ee144da20303c60baad4
<|skeleton|> class FrequencyDroop: """This class describes Frequency-Droop operation of device fleet""" def __init__(self, db_UF, db_OF, k_UF, k_OF, P_avl, P_min, P_pre): """initiating variables to evaluate the Frequency-Droop function parameters defining curve: db_UF,db_OF,k_UF,k_OF State variable: P_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FrequencyDroop: """This class describes Frequency-Droop operation of device fleet""" def __init__(self, db_UF, db_OF, k_UF, k_OF, P_avl, P_min, P_pre): """initiating variables to evaluate the Frequency-Droop function parameters defining curve: db_UF,db_OF,k_UF,k_OF State variable: P_avl,P_min,P_p...
the_stack_v2_python_sparse
src/frequency_droop.py
GMLC-1-4-2/battery_interface
train
2
cf9b6aa84a82511f7e578b22594ab8d20ddf34ef
[ "if 'result' in response_json:\n return SuccessResponse.from_json(response_json)\nelif 'error' in response_json:\n return ErrorResponse.from_json(response_json)\nelse:\n raise InvalidRequestError('Either `result` or `error` must be presented in JSON-RPC ' + f'responses. Got {response_json}.')", "try:\n ...
<|body_start_0|> if 'result' in response_json: return SuccessResponse.from_json(response_json) elif 'error' in response_json: return ErrorResponse.from_json(response_json) else: raise InvalidRequestError('Either `result` or `error` must be presented in JSON-RP...
Response
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Response: def from_json(response_json: JSON) -> 'Response': """Parse a given JSON into a JSON-RPC response. Raises `InvalidRequestError` if the JSON body is malformed.""" <|body_0|> def from_string(response_string: str) -> 'Response': """Parse a given string into a J...
stack_v2_sparse_classes_36k_train_024084
11,537
permissive
[ { "docstring": "Parse a given JSON into a JSON-RPC response. Raises `InvalidRequestError` if the JSON body is malformed.", "name": "from_json", "signature": "def from_json(response_json: JSON) -> 'Response'" }, { "docstring": "Parse a given string into a JSON-RPC response. Raises `ParseError` if...
2
null
Implement the Python class `Response` described below. Class description: Implement the Response class. Method signatures and docstrings: - def from_json(response_json: JSON) -> 'Response': Parse a given JSON into a JSON-RPC response. Raises `InvalidRequestError` if the JSON body is malformed. - def from_string(respo...
Implement the Python class `Response` described below. Class description: Implement the Response class. Method signatures and docstrings: - def from_json(response_json: JSON) -> 'Response': Parse a given JSON into a JSON-RPC response. Raises `InvalidRequestError` if the JSON body is malformed. - def from_string(respo...
fe8ccedc572cc1faa1fd01e9138f65e982875002
<|skeleton|> class Response: def from_json(response_json: JSON) -> 'Response': """Parse a given JSON into a JSON-RPC response. Raises `InvalidRequestError` if the JSON body is malformed.""" <|body_0|> def from_string(response_string: str) -> 'Response': """Parse a given string into a J...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Response: def from_json(response_json: JSON) -> 'Response': """Parse a given JSON into a JSON-RPC response. Raises `InvalidRequestError` if the JSON body is malformed.""" if 'result' in response_json: return SuccessResponse.from_json(response_json) elif 'error' in response_...
the_stack_v2_python_sparse
client/json_rpc.py
facebook/pyre-check
train
6,703
1b3b8aef461926e771e8748320838a3fa9e19765
[ "class NavigationCls(NavigationMixin, InvenTreePlugin):\n NAVIGATION = [{'name': 'aa', 'link': 'plugin:test:test_view'}]\n NAVIGATION_TAB_NAME = 'abcd1'\nself.mixin = NavigationCls()\n\nclass NothingNavigationCls(NavigationMixin, InvenTreePlugin):\n pass\nself.nothing_mixin = NothingNavigationCls()", "se...
<|body_start_0|> class NavigationCls(NavigationMixin, InvenTreePlugin): NAVIGATION = [{'name': 'aa', 'link': 'plugin:test:test_view'}] NAVIGATION_TAB_NAME = 'abcd1' self.mixin = NavigationCls() class NothingNavigationCls(NavigationMixin, InvenTreePlugin): pas...
Tests for NavigationMixin.
NavigationMixinTest
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NavigationMixinTest: """Tests for NavigationMixin.""" def setUp(self): """Setup for all tests.""" <|body_0|> def test_function(self): """Test that a correct configuration functions.""" <|body_1|> def test_fail(self): """Test that wrong links ...
stack_v2_sparse_classes_36k_train_024085
14,946
permissive
[ { "docstring": "Setup for all tests.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test that a correct configuration functions.", "name": "test_function", "signature": "def test_function(self)" }, { "docstring": "Test that wrong links fail.", "name": "t...
3
null
Implement the Python class `NavigationMixinTest` described below. Class description: Tests for NavigationMixin. Method signatures and docstrings: - def setUp(self): Setup for all tests. - def test_function(self): Test that a correct configuration functions. - def test_fail(self): Test that wrong links fail.
Implement the Python class `NavigationMixinTest` described below. Class description: Tests for NavigationMixin. Method signatures and docstrings: - def setUp(self): Setup for all tests. - def test_function(self): Test that a correct configuration functions. - def test_fail(self): Test that wrong links fail. <|skelet...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class NavigationMixinTest: """Tests for NavigationMixin.""" def setUp(self): """Setup for all tests.""" <|body_0|> def test_function(self): """Test that a correct configuration functions.""" <|body_1|> def test_fail(self): """Test that wrong links ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NavigationMixinTest: """Tests for NavigationMixin.""" def setUp(self): """Setup for all tests.""" class NavigationCls(NavigationMixin, InvenTreePlugin): NAVIGATION = [{'name': 'aa', 'link': 'plugin:test:test_view'}] NAVIGATION_TAB_NAME = 'abcd1' self.mixin ...
the_stack_v2_python_sparse
InvenTree/plugin/base/integration/test_mixins.py
inventree/InvenTree
train
3,077
a0123f76b9e5d5ea2c6c6d4de5954d068b697cd5
[ "frame = Frame(user=user or g.current_user)\nframe.from_dict(data)\nreturn frame", "for key in list(data.keys()):\n try:\n setattr(self, key, data[key])\n except KeyError:\n print(f'Key {key} not valid.')" ]
<|body_start_0|> frame = Frame(user=user or g.current_user) frame.from_dict(data) return frame <|end_body_0|> <|body_start_1|> for key in list(data.keys()): try: setattr(self, key, data[key]) except KeyError: print(f'Key {key} not ...
The Frames model Attributes: __tablename__ (str): Table name for user model in database instance (SQLAlchemy table column, str): Unique ID for processed frame date (SQLAlchemy table column, datetime): Date that frame is processed session_id (SQLAlchemy table column, int): User's login count frame_count (SQLAlchemy tabl...
Frame
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Frame: """The Frames model Attributes: __tablename__ (str): Table name for user model in database instance (SQLAlchemy table column, str): Unique ID for processed frame date (SQLAlchemy table column, datetime): Date that frame is processed session_id (SQLAlchemy table column, int): User's login c...
stack_v2_sparse_classes_36k_train_024086
7,286
permissive
[ { "docstring": "Create a new frame. The user is obtained from the context unless provided explicitly. Args: data (dict): Dictionary containing values for some or all class attributes listed above Returns: frame (object): Newly generated frame", "name": "create", "signature": "def create(data, user=None)...
2
stack_v2_sparse_classes_30k_train_011421
Implement the Python class `Frame` described below. Class description: The Frames model Attributes: __tablename__ (str): Table name for user model in database instance (SQLAlchemy table column, str): Unique ID for processed frame date (SQLAlchemy table column, datetime): Date that frame is processed session_id (SQLAlc...
Implement the Python class `Frame` described below. Class description: The Frames model Attributes: __tablename__ (str): Table name for user model in database instance (SQLAlchemy table column, str): Unique ID for processed frame date (SQLAlchemy table column, datetime): Date that frame is processed session_id (SQLAlc...
d1ddc6d086bf93b36a430fbcae0af14b9c584e92
<|skeleton|> class Frame: """The Frames model Attributes: __tablename__ (str): Table name for user model in database instance (SQLAlchemy table column, str): Unique ID for processed frame date (SQLAlchemy table column, datetime): Date that frame is processed session_id (SQLAlchemy table column, int): User's login c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Frame: """The Frames model Attributes: __tablename__ (str): Table name for user model in database instance (SQLAlchemy table column, str): Unique ID for processed frame date (SQLAlchemy table column, datetime): Date that frame is processed session_id (SQLAlchemy table column, int): User's login count frame_co...
the_stack_v2_python_sparse
gesture_recognition/models.py
JoshBClemons/gesture_recognition
train
0
db177f577738333fb0193637b54f2bd17b2fe4df
[ "super(StandardPointHead, self).__init__()\nnum_classes = num_classes\nfc_dim = 256\nnum_fc = 3\ncls_agnostic_mask = False\nself.coarse_pred_each_layer = True\ninput_channels = input_channels\nself.cat = ops.Concat(1)\nself.relu = ops.ReLU()\nfc_dim_in = input_channels + num_classes\nfc_layers = []\nfor _ in range(...
<|body_start_0|> super(StandardPointHead, self).__init__() num_classes = num_classes fc_dim = 256 num_fc = 3 cls_agnostic_mask = False self.coarse_pred_each_layer = True input_channels = input_channels self.cat = ops.Concat(1) self.relu = ops.ReLU(...
A point head multi-layer perceptron which we model with conv1d layers with kernel 1. The head takes both fine-grained and coarse prediction features as its input.
StandardPointHead
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StandardPointHead: """A point head multi-layer perceptron which we model with conv1d layers with kernel 1. The head takes both fine-grained and coarse prediction features as its input.""" def __init__(self, input_channels, num_classes): """The following attributes are parsed from con...
stack_v2_sparse_classes_36k_train_024087
5,823
permissive
[ { "docstring": "The following attributes are parsed from config: fc_dim: the output dimension of each FC layers num_fc: the number of FC layers coarse_pred_each_layer: if True, coarse prediction features are concatenated to each layer's input", "name": "__init__", "signature": "def __init__(self, input_...
2
null
Implement the Python class `StandardPointHead` described below. Class description: A point head multi-layer perceptron which we model with conv1d layers with kernel 1. The head takes both fine-grained and coarse prediction features as its input. Method signatures and docstrings: - def __init__(self, input_channels, n...
Implement the Python class `StandardPointHead` described below. Class description: A point head multi-layer perceptron which we model with conv1d layers with kernel 1. The head takes both fine-grained and coarse prediction features as its input. Method signatures and docstrings: - def __init__(self, input_channels, n...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class StandardPointHead: """A point head multi-layer perceptron which we model with conv1d layers with kernel 1. The head takes both fine-grained and coarse prediction features as its input.""" def __init__(self, input_channels, num_classes): """The following attributes are parsed from con...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StandardPointHead: """A point head multi-layer perceptron which we model with conv1d layers with kernel 1. The head takes both fine-grained and coarse prediction features as its input.""" def __init__(self, input_channels, num_classes): """The following attributes are parsed from config: fc_dim: ...
the_stack_v2_python_sparse
community/cv/pointrend/maskrcnn_pointrend/src/point_rend/point_head.py
mindspore-ai/models
train
301
5a31de627698e051b0644b1688aee3c1a6968d32
[ "self.mean = mean\nself.phi = phi\nself.tau = tau\nself.sigma = np.sqrt(phi ** 2 + tau ** 2)", "mean = np.full_like(dists.rjb, self.mean)\nstddevs = []\nfor stddev_type in stddev_types:\n if stddev_type == const.StdDev.TOTAL:\n stddevs.append(np.full_like(dists.rjb, np.sqrt(self.phi ** 2 + self.tau ** 2...
<|body_start_0|> self.mean = mean self.phi = phi self.tau = tau self.sigma = np.sqrt(phi ** 2 + tau ** 2) <|end_body_0|> <|body_start_1|> mean = np.full_like(dists.rjb, self.mean) stddevs = [] for stddev_type in stddev_types: if stddev_type == const.S...
This is a GMPE for testing. It returns the mean and stddevs specified in the constructor.
NullGMPE
[ "LicenseRef-scancode-warranty-disclaimer", "CC0-1.0", "Python-2.0", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NullGMPE: """This is a GMPE for testing. It returns the mean and stddevs specified in the constructor.""" def __init__(self, mean=0, phi=0.8, tau=0.6): """The default constructor takes three named arguments: Args: mean (float): the mean value returned by the GMPE (default=0). This va...
stack_v2_sparse_classes_36k_train_024088
3,044
permissive
[ { "docstring": "The default constructor takes three named arguments: Args: mean (float): the mean value returned by the GMPE (default=0). This value is returned for all locations, regardles of the IMT or the contents of sites, rupture and distance contexts. phi (float): the within-event standard deviation retur...
2
stack_v2_sparse_classes_30k_train_006528
Implement the Python class `NullGMPE` described below. Class description: This is a GMPE for testing. It returns the mean and stddevs specified in the constructor. Method signatures and docstrings: - def __init__(self, mean=0, phi=0.8, tau=0.6): The default constructor takes three named arguments: Args: mean (float):...
Implement the Python class `NullGMPE` described below. Class description: This is a GMPE for testing. It returns the mean and stddevs specified in the constructor. Method signatures and docstrings: - def __init__(self, mean=0, phi=0.8, tau=0.6): The default constructor takes three named arguments: Args: mean (float):...
8094736e43cc8043044344116b064917d5560c5a
<|skeleton|> class NullGMPE: """This is a GMPE for testing. It returns the mean and stddevs specified in the constructor.""" def __init__(self, mean=0, phi=0.8, tau=0.6): """The default constructor takes three named arguments: Args: mean (float): the mean value returned by the GMPE (default=0). This va...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NullGMPE: """This is a GMPE for testing. It returns the mean and stddevs specified in the constructor.""" def __init__(self, mean=0, phi=0.8, tau=0.6): """The default constructor takes three named arguments: Args: mean (float): the mean value returned by the GMPE (default=0). This value is return...
the_stack_v2_python_sparse
shakelib/gmpe/nullgmpe.py
GeoscienceAustralia/shakemap
train
1
4cc00b180ef784feec4d828709a1edb70d420f51
[ "assert isinstance(context, np.ndarray)\nassert len(np.shape(context)) == 2 or len(np.shape(context)) == 3\nif len(np.shape(context)) == 2:\n self.context = np.array([context.copy()])\nelse:\n self.context = context.copy()\nself.cnum, self.n, self.d = np.shape(self.context)\nself.A = np.eye(self.d, self.d)\ns...
<|body_start_0|> assert isinstance(context, np.ndarray) assert len(np.shape(context)) == 2 or len(np.shape(context)) == 3 if len(np.shape(context)) == 2: self.context = np.array([context.copy()]) else: self.context = context.copy() self.cnum, self.n, self....
SemiparaContextBandit
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SemiparaContextBandit: def __init__(self, context, sigma1=0.3, sigma2=0.01, sigma3=0.3): """Initialize the agent.""" <|body_0|> def update_observation(self, observation, action, reward): """Add an observation to the records.""" <|body_1|> def pick_action...
stack_v2_sparse_classes_36k_train_024089
6,668
permissive
[ { "docstring": "Initialize the agent.", "name": "__init__", "signature": "def __init__(self, context, sigma1=0.3, sigma2=0.01, sigma3=0.3)" }, { "docstring": "Add an observation to the records.", "name": "update_observation", "signature": "def update_observation(self, observation, action...
3
stack_v2_sparse_classes_30k_train_015780
Implement the Python class `SemiparaContextBandit` described below. Class description: Implement the SemiparaContextBandit class. Method signatures and docstrings: - def __init__(self, context, sigma1=0.3, sigma2=0.01, sigma3=0.3): Initialize the agent. - def update_observation(self, observation, action, reward): Add...
Implement the Python class `SemiparaContextBandit` described below. Class description: Implement the SemiparaContextBandit class. Method signatures and docstrings: - def __init__(self, context, sigma1=0.3, sigma2=0.01, sigma3=0.3): Initialize the agent. - def update_observation(self, observation, action, reward): Add...
6e33ba3343fcc013ad4639993c39fe425e28634e
<|skeleton|> class SemiparaContextBandit: def __init__(self, context, sigma1=0.3, sigma2=0.01, sigma3=0.3): """Initialize the agent.""" <|body_0|> def update_observation(self, observation, action, reward): """Add an observation to the records.""" <|body_1|> def pick_action...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SemiparaContextBandit: def __init__(self, context, sigma1=0.3, sigma2=0.01, sigma3=0.3): """Initialize the agent.""" assert isinstance(context, np.ndarray) assert len(np.shape(context)) == 2 or len(np.shape(context)) == 3 if len(np.shape(context)) == 2: self.context...
the_stack_v2_python_sparse
context/agent_semipara.py
anon-usr/INLUCB
train
0
2f3cfdb42e8b799e315dd81404ce551af905f8a8
[ "for i in range(len(haystack) - len(needle) + 1):\n if haystack[i:i + len(needle)] == needle:\n return i\nreturn -1", "if not needle:\n return 0\nif len(haystack) < len(needle):\n return -1\nfor i in range(len(haystack) - len(needle) + 1):\n if haystack[i:i + len(needle)] == needle:\n re...
<|body_start_0|> for i in range(len(haystack) - len(needle) + 1): if haystack[i:i + len(needle)] == needle: return i return -1 <|end_body_0|> <|body_start_1|> if not needle: return 0 if len(haystack) < len(needle): return -1 fo...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def strStr(self, haystack: str, needle: str) -> int: """查找第一次出现needle的位置""" <|body_0|> def strStr2(self, haystack: str, needle: str) -> int: """查找第一次出现needle的位置""" <|body_1|> <|end_skeleton|> <|body_start_0|> for i in range(len(haystack) -...
stack_v2_sparse_classes_36k_train_024090
2,130
no_license
[ { "docstring": "查找第一次出现needle的位置", "name": "strStr", "signature": "def strStr(self, haystack: str, needle: str) -> int" }, { "docstring": "查找第一次出现needle的位置", "name": "strStr2", "signature": "def strStr2(self, haystack: str, needle: str) -> int" } ]
2
stack_v2_sparse_classes_30k_train_008967
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def strStr(self, haystack: str, needle: str) -> int: 查找第一次出现needle的位置 - def strStr2(self, haystack: str, needle: str) -> int: 查找第一次出现needle的位置
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def strStr(self, haystack: str, needle: str) -> int: 查找第一次出现needle的位置 - def strStr2(self, haystack: str, needle: str) -> int: 查找第一次出现needle的位置 <|skeleton|> class Solution: ...
7f8145f0c7ffdf18c557f01d221087b10443156e
<|skeleton|> class Solution: def strStr(self, haystack: str, needle: str) -> int: """查找第一次出现needle的位置""" <|body_0|> def strStr2(self, haystack: str, needle: str) -> int: """查找第一次出现needle的位置""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def strStr(self, haystack: str, needle: str) -> int: """查找第一次出现needle的位置""" for i in range(len(haystack) - len(needle) + 1): if haystack[i:i + len(needle)] == needle: return i return -1 def strStr2(self, haystack: str, needle: str) -> int: ...
the_stack_v2_python_sparse
str/028 Implement strStr().py
mofei952/leetcode_python
train
0
0036aeff62e3ce5b030996a48cdfa1a47ea847af
[ "self.color = Joueur.color[Joueur.index]\nJoueur.index += 1\nself.adversaire = adversaire\nself.score = 0\nself.carte_wagon = [pioche_wagon.pick() for i in range(4)]\nself.carte_destination = [pioche_destination.pick() for j in range(1)]\nself.reserve_de_wagon = [Wagon(self.color) for i in range(45)]", "score = 0...
<|body_start_0|> self.color = Joueur.color[Joueur.index] Joueur.index += 1 self.adversaire = adversaire self.score = 0 self.carte_wagon = [pioche_wagon.pick() for i in range(4)] self.carte_destination = [pioche_destination.pick() for j in range(1)] self.reserve_de...
defini les attributs d'un joueur
Joueur
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Joueur: """defini les attributs d'un joueur""" def __init__(self, pioche_wagon, pioche_destination, adversaire=None): """crée le joueur""" <|body_0|> def calculate_final_score(self, plateau): """permet de connaitre le score final du joueur""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_024091
1,414
no_license
[ { "docstring": "crée le joueur", "name": "__init__", "signature": "def __init__(self, pioche_wagon, pioche_destination, adversaire=None)" }, { "docstring": "permet de connaitre le score final du joueur", "name": "calculate_final_score", "signature": "def calculate_final_score(self, plate...
2
null
Implement the Python class `Joueur` described below. Class description: defini les attributs d'un joueur Method signatures and docstrings: - def __init__(self, pioche_wagon, pioche_destination, adversaire=None): crée le joueur - def calculate_final_score(self, plateau): permet de connaitre le score final du joueur
Implement the Python class `Joueur` described below. Class description: defini les attributs d'un joueur Method signatures and docstrings: - def __init__(self, pioche_wagon, pioche_destination, adversaire=None): crée le joueur - def calculate_final_score(self, plateau): permet de connaitre le score final du joueur <...
147773cc8871d74f1ec1d6bd03e3cce95e9490d1
<|skeleton|> class Joueur: """defini les attributs d'un joueur""" def __init__(self, pioche_wagon, pioche_destination, adversaire=None): """crée le joueur""" <|body_0|> def calculate_final_score(self, plateau): """permet de connaitre le score final du joueur""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Joueur: """defini les attributs d'un joueur""" def __init__(self, pioche_wagon, pioche_destination, adversaire=None): """crée le joueur""" self.color = Joueur.color[Joueur.index] Joueur.index += 1 self.adversaire = adversaire self.score = 0 self.carte_wagon...
the_stack_v2_python_sparse
theorie_des_graphes/Aventurier_du_rail/Joueur.py
porigonop/code_v2
train
0
337eddbef26f1ccbfe0db7343b8bfe540a7d8811
[ "c, h = carry\nhidden_features = h.shape[-1]\ndense_h = linear.Dense.partial(inputs=h, features=hidden_features, bias=True, kernel_init=recurrent_kernel_init, bias_init=bias_init)\ndense_i = linear.Dense.partial(inputs=inputs, features=hidden_features, bias=False, kernel_init=kernel_init)\ni = gate_fn(dense_i(name=...
<|body_start_0|> c, h = carry hidden_features = h.shape[-1] dense_h = linear.Dense.partial(inputs=h, features=hidden_features, bias=True, kernel_init=recurrent_kernel_init, bias_init=bias_init) dense_i = linear.Dense.partial(inputs=inputs, features=hidden_features, bias=False, kernel_ini...
DEPRECATION WARNING: The `flax.nn` module is Deprecated, use `flax.linen` instead. Learn more and find an upgrade guide at https://github.com/google/flax/blob/master/flax/linen/README.md" LSTM cell.
LSTMCell
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LSTMCell: """DEPRECATION WARNING: The `flax.nn` module is Deprecated, use `flax.linen` instead. Learn more and find an upgrade guide at https://github.com/google/flax/blob/master/flax/linen/README.md" LSTM cell.""" def apply(self, carry, inputs, gate_fn=activation.sigmoid, activation_fn=acti...
stack_v2_sparse_classes_36k_train_024092
16,408
permissive
[ { "docstring": "A long short-term memory (LSTM) cell. the mathematical definition of the cell is as follows .. math:: \\\\begin{array}{ll} i = \\\\sigma(W_{ii} x + W_{hi} h + b_{hi}) \\\\\\\\ f = \\\\sigma(W_{if} x + W_{hf} h + b_{hf}) \\\\\\\\ g = \\\\tanh(W_{ig} x + W_{hg} h + b_{hg}) \\\\\\\\ o = \\\\sigma(W...
2
stack_v2_sparse_classes_30k_train_004147
Implement the Python class `LSTMCell` described below. Class description: DEPRECATION WARNING: The `flax.nn` module is Deprecated, use `flax.linen` instead. Learn more and find an upgrade guide at https://github.com/google/flax/blob/master/flax/linen/README.md" LSTM cell. Method signatures and docstrings: - def apply...
Implement the Python class `LSTMCell` described below. Class description: DEPRECATION WARNING: The `flax.nn` module is Deprecated, use `flax.linen` instead. Learn more and find an upgrade guide at https://github.com/google/flax/blob/master/flax/linen/README.md" LSTM cell. Method signatures and docstrings: - def apply...
87a483b2b93fa1dd7934da520348e6ce8d7851b4
<|skeleton|> class LSTMCell: """DEPRECATION WARNING: The `flax.nn` module is Deprecated, use `flax.linen` instead. Learn more and find an upgrade guide at https://github.com/google/flax/blob/master/flax/linen/README.md" LSTM cell.""" def apply(self, carry, inputs, gate_fn=activation.sigmoid, activation_fn=acti...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LSTMCell: """DEPRECATION WARNING: The `flax.nn` module is Deprecated, use `flax.linen` instead. Learn more and find an upgrade guide at https://github.com/google/flax/blob/master/flax/linen/README.md" LSTM cell.""" def apply(self, carry, inputs, gate_fn=activation.sigmoid, activation_fn=activation.tanh, ...
the_stack_v2_python_sparse
flax/nn/recurrent.py
marcvanzee/flax
train
3
0cf4d6fac4082cf456afc78b9cb480aa948d7f9b
[ "args = self.args\nif len(args.rsplit()) != 2:\n self.statname = None\n self.statvalue = None\n return\nstatname = args.rsplit()[0]\nstatvalue = args.rsplit()[1]\nself.statname = statname\nself.statvalue = statvalue", "allowed_statnames = self.caller.db.stats.keys()\nerrmsg1 = 'You must supply a stat ( %...
<|body_start_0|> args = self.args if len(args.rsplit()) != 2: self.statname = None self.statvalue = None return statname = args.rsplit()[0] statvalue = args.rsplit()[1] self.statname = statname self.statvalue = statvalue <|end_body_0|> ...
set a stat of a character Usage: +setstat (stat) (1-200) This sets the power of the current character. This can only be used during character generation.
CmdSetStat
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CmdSetStat: """set a stat of a character Usage: +setstat (stat) (1-200) This sets the power of the current character. This can only be used during character generation.""" def parse(self): """This parses the arguments""" <|body_0|> def func(self): """This perform...
stack_v2_sparse_classes_36k_train_024093
19,545
no_license
[ { "docstring": "This parses the arguments", "name": "parse", "signature": "def parse(self)" }, { "docstring": "This performs the actual command", "name": "func", "signature": "def func(self)" } ]
2
stack_v2_sparse_classes_30k_val_000973
Implement the Python class `CmdSetStat` described below. Class description: set a stat of a character Usage: +setstat (stat) (1-200) This sets the power of the current character. This can only be used during character generation. Method signatures and docstrings: - def parse(self): This parses the arguments - def fun...
Implement the Python class `CmdSetStat` described below. Class description: set a stat of a character Usage: +setstat (stat) (1-200) This sets the power of the current character. This can only be used during character generation. Method signatures and docstrings: - def parse(self): This parses the arguments - def fun...
66e9c2ab1570bc8f439cf6ccde872534eecb0d62
<|skeleton|> class CmdSetStat: """set a stat of a character Usage: +setstat (stat) (1-200) This sets the power of the current character. This can only be used during character generation.""" def parse(self): """This parses the arguments""" <|body_0|> def func(self): """This perform...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CmdSetStat: """set a stat of a character Usage: +setstat (stat) (1-200) This sets the power of the current character. This can only be used during character generation.""" def parse(self): """This parses the arguments""" args = self.args if len(args.rsplit()) != 2: sel...
the_stack_v2_python_sparse
commands/command.py
Cidusii/Kyatsu
train
0
5185bb801ee338a913931878bdc5638913f4f7d3
[ "data = np.zeros((100, 60, 9))\ndata_1 = np.zeros((50, 30, 5))\ndata_2 = np.zeros((25, 15, 3))\nres = downsample_raw(data, numlevels=2)\nmatch = np.array_equal(data_1, res[0])\nself.assertTrue(match)\nmatch = np.array_equal(data_2, res[1])\nself.assertTrue(match)", "founderror = False\ntry:\n data2d = np.zeros...
<|body_start_0|> data = np.zeros((100, 60, 9)) data_1 = np.zeros((50, 30, 5)) data_2 = np.zeros((25, 15, 3)) res = downsample_raw(data, numlevels=2) match = np.array_equal(data_1, res[0]) self.assertTrue(match) match = np.array_equal(data_2, res[1]) self.a...
Tests array downsampling routines.
Testdownsample
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Testdownsample: """Tests array downsampling routines.""" def test_downsample_raw_blank(self): """Tests downsample_raw dimensions and pyramid creation.""" <|body_0|> def test_downsample_3Dlabels_bad(self): """Tests that illegal input gracefully fails in label down...
stack_v2_sparse_classes_36k_train_024094
5,391
permissive
[ { "docstring": "Tests downsample_raw dimensions and pyramid creation.", "name": "test_downsample_raw_blank", "signature": "def test_downsample_raw_blank(self)" }, { "docstring": "Tests that illegal input gracefully fails in label downsample.", "name": "test_downsample_3Dlabels_bad", "sig...
3
null
Implement the Python class `Testdownsample` described below. Class description: Tests array downsampling routines. Method signatures and docstrings: - def test_downsample_raw_blank(self): Tests downsample_raw dimensions and pyramid creation. - def test_downsample_3Dlabels_bad(self): Tests that illegal input gracefull...
Implement the Python class `Testdownsample` described below. Class description: Tests array downsampling routines. Method signatures and docstrings: - def test_downsample_raw_blank(self): Tests downsample_raw dimensions and pyramid creation. - def test_downsample_3Dlabels_bad(self): Tests that illegal input gracefull...
14b271b150508ad247347898c0b1ac7365931b05
<|skeleton|> class Testdownsample: """Tests array downsampling routines.""" def test_downsample_raw_blank(self): """Tests downsample_raw dimensions and pyramid creation.""" <|body_0|> def test_downsample_3Dlabels_bad(self): """Tests that illegal input gracefully fails in label down...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Testdownsample: """Tests array downsampling routines.""" def test_downsample_raw_blank(self): """Tests downsample_raw dimensions and pyramid creation.""" data = np.zeros((100, 60, 9)) data_1 = np.zeros((50, 30, 5)) data_2 = np.zeros((25, 15, 3)) res = downsample_ra...
the_stack_v2_python_sparse
obsolete/unit_tests/reconutils/unit_tests/test_downsample.py
janelia-flyem/flyemflows
train
1
d592c134d1f42716119ababe80909bd8d0ec0044
[ "self._entity_ids = entity_ids\nself._attr_name = name\nself._attr_extra_state_attributes = {ATTR_ENTITY_ID: entity_ids}\nself._attr_unique_id = unique_id\nself._attr_event_types = []", "@callback\ndef async_state_changed_listener(event: EventType[EventStateChangedData]) -> None:\n \"\"\"Handle child updates.\...
<|body_start_0|> self._entity_ids = entity_ids self._attr_name = name self._attr_extra_state_attributes = {ATTR_ENTITY_ID: entity_ids} self._attr_unique_id = unique_id self._attr_event_types = [] <|end_body_0|> <|body_start_1|> @callback def async_state_changed_l...
Representation of an event group.
EventGroup
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventGroup: """Representation of an event group.""" def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None: """Initialize an event group.""" <|body_0|> async def async_added_to_hass(self) -> None: """Register callbacks.""" <|b...
stack_v2_sparse_classes_36k_train_024095
5,729
permissive
[ { "docstring": "Initialize an event group.", "name": "__init__", "signature": "def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None" }, { "docstring": "Register callbacks.", "name": "async_added_to_hass", "signature": "async def async_added_to_hass(self) ->...
3
stack_v2_sparse_classes_30k_train_002734
Implement the Python class `EventGroup` described below. Class description: Representation of an event group. Method signatures and docstrings: - def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None: Initialize an event group. - async def async_added_to_hass(self) -> None: Register call...
Implement the Python class `EventGroup` described below. Class description: Representation of an event group. Method signatures and docstrings: - def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None: Initialize an event group. - async def async_added_to_hass(self) -> None: Register call...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class EventGroup: """Representation of an event group.""" def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None: """Initialize an event group.""" <|body_0|> async def async_added_to_hass(self) -> None: """Register callbacks.""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EventGroup: """Representation of an event group.""" def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None: """Initialize an event group.""" self._entity_ids = entity_ids self._attr_name = name self._attr_extra_state_attributes = {ATTR_ENTITY_I...
the_stack_v2_python_sparse
homeassistant/components/group/event.py
home-assistant/core
train
35,501
38ec1daf7d822c2cb3aa3b3a717ced0153c80ce1
[ "webapp_user = args['webapp_user']\nship_info_id = (int(args['ship_id']),)\nnew_ship_info = {'ship_name': args['ship_name'], 'ship_address': args['ship_address'], 'ship_tel': args['ship_tel'], 'area': args['area']}\narea = args['area']\nif False in map(lambda x: x.isdigit(), area.split('_')):\n webapp_user_id = ...
<|body_start_0|> webapp_user = args['webapp_user'] ship_info_id = (int(args['ship_id']),) new_ship_info = {'ship_name': args['ship_name'], 'ship_address': args['ship_address'], 'ship_tel': args['ship_tel'], 'area': args['area']} area = args['area'] if False in map(lambda x: x.isd...
收货地址
AShipInfo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AShipInfo: """收货地址""" def post(args): """@brief 修改收货地址 @param ship_id @param ship_name @param ship_address @param ship_tel @param area @return {result:True}""" <|body_0|> def put(args): """新建收货地址 @param ship_name @param ship_address @param ship_tel @param area @r...
stack_v2_sparse_classes_36k_train_024096
2,372
no_license
[ { "docstring": "@brief 修改收货地址 @param ship_id @param ship_name @param ship_address @param ship_tel @param area @return {result:True}", "name": "post", "signature": "def post(args)" }, { "docstring": "新建收货地址 @param ship_name @param ship_address @param ship_tel @param area @return {'ship_info_id': ...
3
stack_v2_sparse_classes_30k_train_007201
Implement the Python class `AShipInfo` described below. Class description: 收货地址 Method signatures and docstrings: - def post(args): @brief 修改收货地址 @param ship_id @param ship_name @param ship_address @param ship_tel @param area @return {result:True} - def put(args): 新建收货地址 @param ship_name @param ship_address @param sh...
Implement the Python class `AShipInfo` described below. Class description: 收货地址 Method signatures and docstrings: - def post(args): @brief 修改收货地址 @param ship_id @param ship_name @param ship_address @param ship_tel @param area @return {result:True} - def put(args): 新建收货地址 @param ship_name @param ship_address @param sh...
15621db1a64ffe199619924b75a5b5c5e6416bed
<|skeleton|> class AShipInfo: """收货地址""" def post(args): """@brief 修改收货地址 @param ship_id @param ship_name @param ship_address @param ship_tel @param area @return {result:True}""" <|body_0|> def put(args): """新建收货地址 @param ship_name @param ship_address @param ship_tel @param area @r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AShipInfo: """收货地址""" def post(args): """@brief 修改收货地址 @param ship_id @param ship_name @param ship_address @param ship_tel @param area @return {result:True}""" webapp_user = args['webapp_user'] ship_info_id = (int(args['ship_id']),) new_ship_info = {'ship_name': args['ship...
the_stack_v2_python_sparse
api/mall/a_ship_info.py
nuaays/apiserver
train
0
e00a52feb2616c75c3683be3cd45c1011ca82899
[ "facility_id = self.kwargs.get('fac_id')\nfac = Facility.objects.get(id=facility_id)\nif not check_permissions_from_request(request, fac, 'u'):\n return Response(status=status.HTTP_403_FORBIDDEN)\ncampus = self.get_object()\nif campus.org_id == fac.org_id:\n fac.campus_id = campus.id\n try:\n fac.sa...
<|body_start_0|> facility_id = self.kwargs.get('fac_id') fac = Facility.objects.get(id=facility_id) if not check_permissions_from_request(request, fac, 'u'): return Response(status=status.HTTP_403_FORBIDDEN) campus = self.get_object() if campus.org_id == fac.org_id: ...
Custom API endpoints for the campus-facility object, exposed to /api/campus/{campus_id}/add-facility/{fac_id} and /api/campus/{campus_id}/remove-facility/{fac_id}
CampusFacilityMixin
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CampusFacilityMixin: """Custom API endpoints for the campus-facility object, exposed to /api/campus/{campus_id}/add-facility/{fac_id} and /api/campus/{campus_id}/remove-facility/{fac_id}""" def add_facility(self, request, *args, **kwargs): """Allows the org to approve a campus listin...
stack_v2_sparse_classes_36k_train_024097
40,361
permissive
[ { "docstring": "Allows the org to approve a campus listing at their facility", "name": "add_facility", "signature": "def add_facility(self, request, *args, **kwargs)" }, { "docstring": "Allows the org to reject a campus listing at their facility", "name": "remove_facility", "signature": ...
2
null
Implement the Python class `CampusFacilityMixin` described below. Class description: Custom API endpoints for the campus-facility object, exposed to /api/campus/{campus_id}/add-facility/{fac_id} and /api/campus/{campus_id}/remove-facility/{fac_id} Method signatures and docstrings: - def add_facility(self, request, *a...
Implement the Python class `CampusFacilityMixin` described below. Class description: Custom API endpoints for the campus-facility object, exposed to /api/campus/{campus_id}/add-facility/{fac_id} and /api/campus/{campus_id}/remove-facility/{fac_id} Method signatures and docstrings: - def add_facility(self, request, *a...
3f62b2d97c78ccf151fb1a5761637e28463b9541
<|skeleton|> class CampusFacilityMixin: """Custom API endpoints for the campus-facility object, exposed to /api/campus/{campus_id}/add-facility/{fac_id} and /api/campus/{campus_id}/remove-facility/{fac_id}""" def add_facility(self, request, *args, **kwargs): """Allows the org to approve a campus listin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CampusFacilityMixin: """Custom API endpoints for the campus-facility object, exposed to /api/campus/{campus_id}/add-facility/{fac_id} and /api/campus/{campus_id}/remove-facility/{fac_id}""" def add_facility(self, request, *args, **kwargs): """Allows the org to approve a campus listing at their fa...
the_stack_v2_python_sparse
peeringdb_server/rest.py
peeringdb/peeringdb
train
311
f71ff580b56f02436867c3d84c2827331c1d4396
[ "super().__init__(input_dim, active_dims, name=name)\nself.v_b = gpflow.params.Parameter(v_b, transform=gpflow.transforms.positive)\nself.v_w = gpflow.params.Parameter(v_w, transform=gpflow.transforms.positive)\nself.depth = depth", "if not presliced:\n X, X2 = self._slice(X, X2)\nif X2 is None:\n X2 = X\nK...
<|body_start_0|> super().__init__(input_dim, active_dims, name=name) self.v_b = gpflow.params.Parameter(v_b, transform=gpflow.transforms.positive) self.v_w = gpflow.params.Parameter(v_w, transform=gpflow.transforms.positive) self.depth = depth <|end_body_0|> <|body_start_1|> if ...
Kernel of a fully connected NNGP. This class implements a GPFlow kernel that results from a deep NNGP architecture with relu activation.
NNGP
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NNGP: """Kernel of a fully connected NNGP. This class implements a GPFlow kernel that results from a deep NNGP architecture with relu activation.""" def __init__(self, input_dim, active_dims=None, name=None, v_w=1.0, v_b=1.0, depth=1): """Initializes the NNGP kernel. Parameters -----...
stack_v2_sparse_classes_36k_train_024098
6,194
no_license
[ { "docstring": "Initializes the NNGP kernel. Parameters ---------- input_dim : int Dimension of the input space. active_dims : None, optional This argument is necessary for a GPFlow kernel. Only use the default value for now. name : None, optional This argument is necessary for a GPFlow kernel. Only use the def...
3
null
Implement the Python class `NNGP` described below. Class description: Kernel of a fully connected NNGP. This class implements a GPFlow kernel that results from a deep NNGP architecture with relu activation. Method signatures and docstrings: - def __init__(self, input_dim, active_dims=None, name=None, v_w=1.0, v_b=1.0...
Implement the Python class `NNGP` described below. Class description: Kernel of a fully connected NNGP. This class implements a GPFlow kernel that results from a deep NNGP architecture with relu activation. Method signatures and docstrings: - def __init__(self, input_dim, active_dims=None, name=None, v_w=1.0, v_b=1.0...
9db3ab73f1812c5dea2f5ed4cdd4c2a72d52534f
<|skeleton|> class NNGP: """Kernel of a fully connected NNGP. This class implements a GPFlow kernel that results from a deep NNGP architecture with relu activation.""" def __init__(self, input_dim, active_dims=None, name=None, v_w=1.0, v_b=1.0, depth=1): """Initializes the NNGP kernel. Parameters -----...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NNGP: """Kernel of a fully connected NNGP. This class implements a GPFlow kernel that results from a deep NNGP architecture with relu activation.""" def __init__(self, input_dim, active_dims=None, name=None, v_w=1.0, v_b=1.0, depth=1): """Initializes the NNGP kernel. Parameters ---------- input_d...
the_stack_v2_python_sparse
final-dkl/my_dkl/kernels.py
dagrawa2/ece692_deep_learning
train
0
3e5f1255c2276781a1a4f553bef9fa53919a388e
[ "s, e, i, r = xs\nif isinstance(parameters, Parameters):\n beta = parameters['beta'].value\n gamma = parameters['gamma'].value\n sigma = parameters['sigma'].value\n N = parameters['N'].value\nelif isinstance(parameters, tuple):\n beta, gamma, sigma, N = parameters\nelse:\n raise ValueError('Cannot...
<|body_start_0|> s, e, i, r = xs if isinstance(parameters, Parameters): beta = parameters['beta'].value gamma = parameters['gamma'].value sigma = parameters['sigma'].value N = parameters['N'].value elif isinstance(parameters, tuple): be...
SEIR Model
SEIR
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SEIR: """SEIR Model""" def calibrate(cls, xs: tuple, t: float, parameters: Union[Parameters, tuple]) -> tuple: """SEIR model derivatives at t. :param xs: variables that we are solving for, i.e. [S]usceptible, [E]xposed, [I]nfected, [R]emoved :param t: time parameter, inactive for thi...
stack_v2_sparse_classes_36k_train_024099
29,649
permissive
[ { "docstring": "SEIR model derivatives at t. :param xs: variables that we are solving for, i.e. [S]usceptible, [E]xposed, [I]nfected, [R]emoved :param t: time parameter, inactive for this model :param parameters: parameters of the model (not including initial conditions), i.e. beta, gamma, sigma, N :return: tup...
2
null
Implement the Python class `SEIR` described below. Class description: SEIR Model Method signatures and docstrings: - def calibrate(cls, xs: tuple, t: float, parameters: Union[Parameters, tuple]) -> tuple: SEIR model derivatives at t. :param xs: variables that we are solving for, i.e. [S]usceptible, [E]xposed, [I]nfec...
Implement the Python class `SEIR` described below. Class description: SEIR Model Method signatures and docstrings: - def calibrate(cls, xs: tuple, t: float, parameters: Union[Parameters, tuple]) -> tuple: SEIR model derivatives at t. :param xs: variables that we are solving for, i.e. [S]usceptible, [E]xposed, [I]nfec...
4cf8ec75c4d85b16ec08371c46cc1a9ede9d72a2
<|skeleton|> class SEIR: """SEIR Model""" def calibrate(cls, xs: tuple, t: float, parameters: Union[Parameters, tuple]) -> tuple: """SEIR model derivatives at t. :param xs: variables that we are solving for, i.e. [S]usceptible, [E]xposed, [I]nfected, [R]emoved :param t: time parameter, inactive for thi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SEIR: """SEIR Model""" def calibrate(cls, xs: tuple, t: float, parameters: Union[Parameters, tuple]) -> tuple: """SEIR model derivatives at t. :param xs: variables that we are solving for, i.e. [S]usceptible, [E]xposed, [I]nfected, [R]emoved :param t: time parameter, inactive for this model :para...
the_stack_v2_python_sparse
gs_quant/models/epidemiology.py
goldmansachs/gs-quant
train
2,088