blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
7.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
378
8.64k
id
stringlengths
44
44
length_bytes
int64
505
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.88k
prompted_full_text
stringlengths
565
12.5k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
5.05k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
snapshot_total_rows
int64
75.8k
75.8k
solution
stringlengths
242
8.3k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
a7ff174b1476ef15f181bce08584237210d98705
[ "if not nums:\n return 0\nup, down = (1, 1)\nfor i in range(1, len(nums)):\n if nums[i] > nums[i - 1]:\n up = down + 1\n elif nums[i] < nums[i - 1]:\n down = up + 1\nreturn max(down, up)", "if not nums:\n return 0\ndp = [[0 for _ in range(2)] for _ in range(len(nums))]\ndp[0][0], dp[0][1...
<|body_start_0|> if not nums: return 0 up, down = (1, 1) for i in range(1, len(nums)): if nums[i] > nums[i - 1]: up = down + 1 elif nums[i] < nums[i - 1]: down = up + 1 return max(down, up) <|end_body_0|> <|body_start_1...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def wiggleMaxLength(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def wiggleMaxLengthDP(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not nums: return 0 ...
stack_v2_sparse_classes_75kplus_train_001300
2,738
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "wiggleMaxLength", "signature": "def wiggleMaxLength(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "wiggleMaxLengthDP", "signature": "def wiggleMaxLengthDP(self, nums)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def wiggleMaxLength(self, nums): :type nums: List[int] :rtype: int - def wiggleMaxLengthDP(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def wiggleMaxLength(self, nums): :type nums: List[int] :rtype: int - def wiggleMaxLengthDP(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def w...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def wiggleMaxLength(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def wiggleMaxLengthDP(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def wiggleMaxLength(self, nums): """:type nums: List[int] :rtype: int""" if not nums: return 0 up, down = (1, 1) for i in range(1, len(nums)): if nums[i] > nums[i - 1]: up = down + 1 elif nums[i] < nums[i - 1]: ...
the_stack_v2_python_sparse
W/WiggleSubsequence.py
bssrdf/pyleet
train
2
14f23095b12682aa883586e2f15f861ca93951d0
[ "tmp = [[] for i in range(len(matrix))]\nfor i in range(len(matrix)):\n for j in range(len(matrix)):\n tmp[i].insert(0, matrix[j][i])\nmatrix[:] = tmp[:]", "matrix.reverse()\nz = list(zip(*matrix))\nmatrix[:] = z[:]" ]
<|body_start_0|> tmp = [[] for i in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix)): tmp[i].insert(0, matrix[j][i]) matrix[:] = tmp[:] <|end_body_0|> <|body_start_1|> matrix.reverse() z = list(zip(*matrix)) matrix[...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rotate(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""" <|body_0|> def rotate2(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p...
stack_v2_sparse_classes_75kplus_train_001301
643
no_license
[ { "docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.", "name": "rotate", "signature": "def rotate(self, matrix)" }, { "docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.", ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. - def rotate2(self, matrix): :type matrix: List[List[...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. - def rotate2(self, matrix): :type matrix: List[List[...
624975f767f6efa1d7361cc077eaebc344d57210
<|skeleton|> class Solution: def rotate(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""" <|body_0|> def rotate2(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def rotate(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""" tmp = [[] for i in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix)): tmp[i].insert(0, mat...
the_stack_v2_python_sparse
48. 旋转图像.py
dx19910707/LeetCode
train
0
30e50150e559fb43385ca4055e24db681a72975d
[ "class MLStripper(HTMLParser):\n\n def __init__(self):\n super().__init__()\n self.reset()\n self.fed = []\n\n def handle_data(self, d):\n self.fed.append(d)\n\n def get_data(self):\n return ''.join(self.fed)\ns = MLStripper()\ns.feed(html)\nreturn s.get_data()", "logge...
<|body_start_0|> class MLStripper(HTMLParser): def __init__(self): super().__init__() self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(...
HTMLTagRemover
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HTMLTagRemover: def _tag_remover(self, html): """:param html: :return:""" <|body_0|> def transform(self, X): """`X` is expected to be a list of `str` instances.""" <|body_1|> <|end_skeleton|> <|body_start_0|> class MLStripper(HTMLParser): ...
stack_v2_sparse_classes_75kplus_train_001302
4,447
no_license
[ { "docstring": ":param html: :return:", "name": "_tag_remover", "signature": "def _tag_remover(self, html)" }, { "docstring": "`X` is expected to be a list of `str` instances.", "name": "transform", "signature": "def transform(self, X)" } ]
2
stack_v2_sparse_classes_30k_train_003959
Implement the Python class `HTMLTagRemover` described below. Class description: Implement the HTMLTagRemover class. Method signatures and docstrings: - def _tag_remover(self, html): :param html: :return: - def transform(self, X): `X` is expected to be a list of `str` instances.
Implement the Python class `HTMLTagRemover` described below. Class description: Implement the HTMLTagRemover class. Method signatures and docstrings: - def _tag_remover(self, html): :param html: :return: - def transform(self, X): `X` is expected to be a list of `str` instances. <|skeleton|> class HTMLTagRemover: ...
28c981560ff7e24513372f76c6cbe4b9facf6457
<|skeleton|> class HTMLTagRemover: def _tag_remover(self, html): """:param html: :return:""" <|body_0|> def transform(self, X): """`X` is expected to be a list of `str` instances.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HTMLTagRemover: def _tag_remover(self, html): """:param html: :return:""" class MLStripper(HTMLParser): def __init__(self): super().__init__() self.reset() self.fed = [] def handle_data(self, d): self.fed...
the_stack_v2_python_sparse
ice_commons/core/text.py
karansingla06/ICE-NER-NLP
train
1
2313cdc5d523b22f0ba4b68874225fe71c105f9a
[ "if len(self.args) != 1:\n raise ValueError('ArgRule only support ONE argument')\nsupported_arg_names = ('KeywordArg', 'ConceptArg')\narg_name = self.args[0].__class__.__name__\nif arg_name not in supported_arg_names:\n raise ValueError('ArgRule only support argument of types ({})'.format(', '.join(supported_...
<|body_start_0|> if len(self.args) != 1: raise ValueError('ArgRule only support ONE argument') supported_arg_names = ('KeywordArg', 'ConceptArg') arg_name = self.args[0].__class__.__name__ if arg_name not in supported_arg_names: raise ValueError('ArgRule only supp...
参数规则
ArgRule
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArgRule: """参数规则""" def validate(self): """参数的合法性检验, 不合法抛出异常. 1. 只支持一个参数 2. 参数只能是 关键词 (KeywordArg) 或 概念 (ConceptArg)""" <|body_0|> def match(self, text): """匹配对象进行文本的规则匹配 :param text: 待匹配的 Text 对象 :return: 返回查找到的 Results 对象, 如果不存在返回 None""" <|body_1|> <|...
stack_v2_sparse_classes_75kplus_train_001303
1,436
no_license
[ { "docstring": "参数的合法性检验, 不合法抛出异常. 1. 只支持一个参数 2. 参数只能是 关键词 (KeywordArg) 或 概念 (ConceptArg)", "name": "validate", "signature": "def validate(self)" }, { "docstring": "匹配对象进行文本的规则匹配 :param text: 待匹配的 Text 对象 :return: 返回查找到的 Results 对象, 如果不存在返回 None", "name": "match", "signature": "def match...
2
null
Implement the Python class `ArgRule` described below. Class description: 参数规则 Method signatures and docstrings: - def validate(self): 参数的合法性检验, 不合法抛出异常. 1. 只支持一个参数 2. 参数只能是 关键词 (KeywordArg) 或 概念 (ConceptArg) - def match(self, text): 匹配对象进行文本的规则匹配 :param text: 待匹配的 Text 对象 :return: 返回查找到的 Results 对象, 如果不存在返回 None
Implement the Python class `ArgRule` described below. Class description: 参数规则 Method signatures and docstrings: - def validate(self): 参数的合法性检验, 不合法抛出异常. 1. 只支持一个参数 2. 参数只能是 关键词 (KeywordArg) 或 概念 (ConceptArg) - def match(self, text): 匹配对象进行文本的规则匹配 :param text: 待匹配的 Text 对象 :return: 返回查找到的 Results 对象, 如果不存在返回 None <|s...
0d587707b0ecae5a321e8a394cc0cf96fcf58235
<|skeleton|> class ArgRule: """参数规则""" def validate(self): """参数的合法性检验, 不合法抛出异常. 1. 只支持一个参数 2. 参数只能是 关键词 (KeywordArg) 或 概念 (ConceptArg)""" <|body_0|> def match(self, text): """匹配对象进行文本的规则匹配 :param text: 待匹配的 Text 对象 :return: 返回查找到的 Results 对象, 如果不存在返回 None""" <|body_1|> <|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ArgRule: """参数规则""" def validate(self): """参数的合法性检验, 不合法抛出异常. 1. 只支持一个参数 2. 参数只能是 关键词 (KeywordArg) 或 概念 (ConceptArg)""" if len(self.args) != 1: raise ValueError('ArgRule only support ONE argument') supported_arg_names = ('KeywordArg', 'ConceptArg') arg_name = s...
the_stack_v2_python_sparse
report_code/code/kme/rule/arg_rule.py
Mi524/tools_copy
train
0
ad14551af5a156ae4c87b25bdcb75383ea771922
[ "digits_len = len(digits)\nif not self.increment_digit(digits, digits_len - 1, 1):\n return digits\nfor i in range(digits_len - 2, -1, -1):\n if not self.increment_digit(digits, i, 1):\n break\nreturn digits", "new_digit = digits[i] + carry\ndigits[i] = new_digit % 10\ncarry = new_digit // 10\nif i =...
<|body_start_0|> digits_len = len(digits) if not self.increment_digit(digits, digits_len - 1, 1): return digits for i in range(digits_len - 2, -1, -1): if not self.increment_digit(digits, i, 1): break return digits <|end_body_0|> <|body_start_1|> ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def plusOne(self, digits: List[int]) -> List[int]: """(Solution, list of int) -> list of int Return a list of digits representing a number that is one higher than the number represented by digits. >>> soln = Solution() >>> soln.plusOne([1, 2, 3]) [1, 2, 4] >>> soln.plusOne([4, ...
stack_v2_sparse_classes_75kplus_train_001304
2,409
no_license
[ { "docstring": "(Solution, list of int) -> list of int Return a list of digits representing a number that is one higher than the number represented by digits. >>> soln = Solution() >>> soln.plusOne([1, 2, 3]) [1, 2, 4] >>> soln.plusOne([4, 3, 2, 1]) [4, 3, 2, 2] >>> soln.plusOne([9]) [1, 0]", "name": "plusO...
2
stack_v2_sparse_classes_30k_train_019737
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def plusOne(self, digits: List[int]) -> List[int]: (Solution, list of int) -> list of int Return a list of digits representing a number that is one higher than the number represe...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def plusOne(self, digits: List[int]) -> List[int]: (Solution, list of int) -> list of int Return a list of digits representing a number that is one higher than the number represe...
6812253b90bdd5a35c6bfba8eac54da9be26d56c
<|skeleton|> class Solution: def plusOne(self, digits: List[int]) -> List[int]: """(Solution, list of int) -> list of int Return a list of digits representing a number that is one higher than the number represented by digits. >>> soln = Solution() >>> soln.plusOne([1, 2, 3]) [1, 2, 4] >>> soln.plusOne([4, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def plusOne(self, digits: List[int]) -> List[int]: """(Solution, list of int) -> list of int Return a list of digits representing a number that is one higher than the number represented by digits. >>> soln = Solution() >>> soln.plusOne([1, 2, 3]) [1, 2, 4] >>> soln.plusOne([4, 3, 2, 1]) [4, ...
the_stack_v2_python_sparse
python3/plusOne.py
yichuanma95/leetcode-solns
train
2
925c1ff84720a75dee80f58820382844fcb3c0d5
[ "logic = NoticeLogic(self.auth, sid, aid)\nparams = ParamsParser(request.GET)\nlimit = params.int('limit', desc='每页最大渲染数', require=False, default=10)\npage = params.int('page', desc='当前页数', require=False, default=1)\nnotice = AssociationNotice.objects.values('id', 'update_time').filter(association_id=aid).order_by(...
<|body_start_0|> logic = NoticeLogic(self.auth, sid, aid) params = ParamsParser(request.GET) limit = params.int('limit', desc='每页最大渲染数', require=False, default=10) page = params.int('page', desc='当前页数', require=False, default=1) notice = AssociationNotice.objects.values('id', 'up...
NoticeView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NoticeView: def get(self, request, sid, aid): """获取通知列表 :param request: :param sid: :param aid: :return:""" <|body_0|> def post(self, request, sid, aid): """批量获通知信息 :param request: :param sid: :param aid: :return:""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_75kplus_train_001305
7,116
no_license
[ { "docstring": "获取通知列表 :param request: :param sid: :param aid: :return:", "name": "get", "signature": "def get(self, request, sid, aid)" }, { "docstring": "批量获通知信息 :param request: :param sid: :param aid: :return:", "name": "post", "signature": "def post(self, request, sid, aid)" } ]
2
stack_v2_sparse_classes_30k_train_031730
Implement the Python class `NoticeView` described below. Class description: Implement the NoticeView class. Method signatures and docstrings: - def get(self, request, sid, aid): 获取通知列表 :param request: :param sid: :param aid: :return: - def post(self, request, sid, aid): 批量获通知信息 :param request: :param sid: :param aid:...
Implement the Python class `NoticeView` described below. Class description: Implement the NoticeView class. Method signatures and docstrings: - def get(self, request, sid, aid): 获取通知列表 :param request: :param sid: :param aid: :return: - def post(self, request, sid, aid): 批量获通知信息 :param request: :param sid: :param aid:...
a0553be3c259712de1fe5517b06317ad5756f79d
<|skeleton|> class NoticeView: def get(self, request, sid, aid): """获取通知列表 :param request: :param sid: :param aid: :return:""" <|body_0|> def post(self, request, sid, aid): """批量获通知信息 :param request: :param sid: :param aid: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NoticeView: def get(self, request, sid, aid): """获取通知列表 :param request: :param sid: :param aid: :return:""" logic = NoticeLogic(self.auth, sid, aid) params = ParamsParser(request.GET) limit = params.int('limit', desc='每页最大渲染数', require=False, default=10) page = params.i...
the_stack_v2_python_sparse
LittlePigHoHo/server/notice/views/info.py
shoogoome/hoho
train
1
0fc79e639a50c9f70cba34cc576489ee92a0b516
[ "if name == 'CSthreadName':\n return threading.current_thread().name\nif name == 'HostName':\n return hostname\nreturn self.__dict__.get(name, '?')", "keys = ['CSthreadName', 'HostName']\nkeys.extend(self.__dict__.keys())\nreturn keys.__iter__()" ]
<|body_start_0|> if name == 'CSthreadName': return threading.current_thread().name if name == 'HostName': return hostname return self.__dict__.get(name, '?') <|end_body_0|> <|body_start_1|> keys = ['CSthreadName', 'HostName'] keys.extend(self.__dict__.key...
according to a recipe from: http://docs.python.org/howto/logging-cookbook.html#adding-contextual-information-to-your-logging-output
ExtraInfo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExtraInfo: """according to a recipe from: http://docs.python.org/howto/logging-cookbook.html#adding-contextual-information-to-your-logging-output""" def __getitem__(self, name): """To allow this instance to look like a dict.""" <|body_0|> def __iter__(self): """T...
stack_v2_sparse_classes_75kplus_train_001306
2,766
no_license
[ { "docstring": "To allow this instance to look like a dict.", "name": "__getitem__", "signature": "def __getitem__(self, name)" }, { "docstring": "To allow iteration over keys, which will be merged into the LogRecord dict before formatting and output.", "name": "__iter__", "signature": "...
2
stack_v2_sparse_classes_30k_train_019977
Implement the Python class `ExtraInfo` described below. Class description: according to a recipe from: http://docs.python.org/howto/logging-cookbook.html#adding-contextual-information-to-your-logging-output Method signatures and docstrings: - def __getitem__(self, name): To allow this instance to look like a dict. - ...
Implement the Python class `ExtraInfo` described below. Class description: according to a recipe from: http://docs.python.org/howto/logging-cookbook.html#adding-contextual-information-to-your-logging-output Method signatures and docstrings: - def __getitem__(self, name): To allow this instance to look like a dict. - ...
b92d7338a420a4b437d24b0aa20408fcb4fa8ea0
<|skeleton|> class ExtraInfo: """according to a recipe from: http://docs.python.org/howto/logging-cookbook.html#adding-contextual-information-to-your-logging-output""" def __getitem__(self, name): """To allow this instance to look like a dict.""" <|body_0|> def __iter__(self): """T...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExtraInfo: """according to a recipe from: http://docs.python.org/howto/logging-cookbook.html#adding-contextual-information-to-your-logging-output""" def __getitem__(self, name): """To allow this instance to look like a dict.""" if name == 'CSthreadName': return threading.curre...
the_stack_v2_python_sparse
ao/log.py
idobarkan/my-code
train
0
5e94507328a67e6f8e9601795a1ad8698cfda9ff
[ "ans = []\nmax_len = 0\n\ndef min_nesting(i):\n s = set()\n while nums[i] not in s:\n s.add(nums[i])\n i = nums[i]\n ans.append(s)\nfor n in nums:\n min_nesting(n)\nfor s in ans:\n max_len = max(max_len, len(s))\nreturn max_len", "ans, step, n = (0, 0, len(nums))\nseen = [False] * n\n...
<|body_start_0|> ans = [] max_len = 0 def min_nesting(i): s = set() while nums[i] not in s: s.add(nums[i]) i = nums[i] ans.append(s) for n in nums: min_nesting(n) for s in ans: max_len = ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def arrayNesting(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def arrayNesting2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> def arrayNesting3(self, nums): """:type nums: List[int] :rtype: int""" ...
stack_v2_sparse_classes_75kplus_train_001307
2,672
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "arrayNesting", "signature": "def arrayNesting(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "arrayNesting2", "signature": "def arrayNesting2(self, nums)" }, { "docstring": ":type nums: List...
3
stack_v2_sparse_classes_30k_train_013589
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def arrayNesting(self, nums): :type nums: List[int] :rtype: int - def arrayNesting2(self, nums): :type nums: List[int] :rtype: int - def arrayNesting3(self, nums): :type nums: Li...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def arrayNesting(self, nums): :type nums: List[int] :rtype: int - def arrayNesting2(self, nums): :type nums: List[int] :rtype: int - def arrayNesting3(self, nums): :type nums: Li...
b925bb22d1daa4a56c5a238a5758a926905559b4
<|skeleton|> class Solution: def arrayNesting(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def arrayNesting2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> def arrayNesting3(self, nums): """:type nums: List[int] :rtype: int""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def arrayNesting(self, nums): """:type nums: List[int] :rtype: int""" ans = [] max_len = 0 def min_nesting(i): s = set() while nums[i] not in s: s.add(nums[i]) i = nums[i] ans.append(s) for n...
the_stack_v2_python_sparse
Arrays/565. Array Nesting.py
beninghton/notGivenUpToG
train
0
0cd01d4da8a9e28c5896a1e2b072fcace47bc687
[ "lst = []\nQ = [root] if root else []\nwhile len(Q) > 0:\n p = Q.pop()\n if not p:\n lst.append(None)\n continue\n Q.append(p.left)\n Q.append(p.right)\nwhile len(lst) > 0 and lst[-1] == None:\n lst.pop()\nreturn str(lst)", "data = data[1:-1]\nif len(data) == 0:\n return None\nlst ...
<|body_start_0|> lst = [] Q = [root] if root else [] while len(Q) > 0: p = Q.pop() if not p: lst.append(None) continue Q.append(p.left) Q.append(p.right) while len(lst) > 0 and lst[-1] == None: ls...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_75kplus_train_001308
1,480
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_020802
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
a95b871578aae0103066962c33b8c0f4ec22d0f2
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" lst = [] Q = [root] if root else [] while len(Q) > 0: p = Q.pop() if not p: lst.append(None) continue ...
the_stack_v2_python_sparse
Offer037.py
Jane11111/Leetcode2021
train
2
b8c586598f489e9ba8da712cab957bc3f96cfe35
[ "from SaasSecurityEventCollector import fetch_events_from_saas_security\nmocker.patch.object(Client, 'http_request', side_effect=queue)\nevents, _ = fetch_events_from_saas_security(client=mock_client, max_fetch=max_fetch)\nassert expected_events.get('events') == events", "import SaasSecurityEventCollector\nshould...
<|body_start_0|> from SaasSecurityEventCollector import fetch_events_from_saas_security mocker.patch.object(Client, 'http_request', side_effect=queue) events, _ = fetch_events_from_saas_security(client=mock_client, max_fetch=max_fetch) assert expected_events.get('events') == events <|end...
TestFetchEvents
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestFetchEvents: def test_fetch_events(self, mocker, mock_client, max_fetch, queue, expected_events): """Given - a queue of responses to fetch events. - max fetch limit When - fetching events. Then - make sure the correct events are fetched according to the queue and max fetch. - make su...
stack_v2_sparse_classes_75kplus_train_001309
19,402
permissive
[ { "docstring": "Given - a queue of responses to fetch events. - max fetch limit When - fetching events. Then - make sure the correct events are fetched according to the queue and max fetch. - make sure in case max fetch is None that all available events will be fetched.", "name": "test_fetch_events", "s...
5
stack_v2_sparse_classes_30k_train_030261
Implement the Python class `TestFetchEvents` described below. Class description: Implement the TestFetchEvents class. Method signatures and docstrings: - def test_fetch_events(self, mocker, mock_client, max_fetch, queue, expected_events): Given - a queue of responses to fetch events. - max fetch limit When - fetching...
Implement the Python class `TestFetchEvents` described below. Class description: Implement the TestFetchEvents class. Method signatures and docstrings: - def test_fetch_events(self, mocker, mock_client, max_fetch, queue, expected_events): Given - a queue of responses to fetch events. - max fetch limit When - fetching...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class TestFetchEvents: def test_fetch_events(self, mocker, mock_client, max_fetch, queue, expected_events): """Given - a queue of responses to fetch events. - max fetch limit When - fetching events. Then - make sure the correct events are fetched according to the queue and max fetch. - make su...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestFetchEvents: def test_fetch_events(self, mocker, mock_client, max_fetch, queue, expected_events): """Given - a queue of responses to fetch events. - max fetch limit When - fetching events. Then - make sure the correct events are fetched according to the queue and max fetch. - make sure in case max...
the_stack_v2_python_sparse
Packs/PrismaSaasSecurity/Integrations/SaasSecurityEventCollector/SaasSecurityEventCollector_test.py
demisto/content
train
1,023
709a6b612f025b370f68f56cff36fba06a5de452
[ "if 'path' in config:\n self.path = config['path']\nelse:\n raise Exception('Path must be specified')\nif 'format' in config:\n if config['format'] in ['json', 'yaml']:\n self.format = config['format']\n else:\n raise Exception('Format must be json or yaml')\nelse:\n self.format = 'json...
<|body_start_0|> if 'path' in config: self.path = config['path'] else: raise Exception('Path must be specified') if 'format' in config: if config['format'] in ['json', 'yaml']: self.format = config['format'] else: ra...
ConfigBackup Plugin
ConfigBackupPlugin
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigBackupPlugin: """ConfigBackup Plugin""" def __init__(self, config, registry): """Constructor""" <|body_0|> def onConfigUpdated(self, config): """Save the configuration to disk""" <|body_1|> <|end_skeleton|> <|body_start_0|> if 'path' in co...
stack_v2_sparse_classes_75kplus_train_001310
1,532
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, config, registry)" }, { "docstring": "Save the configuration to disk", "name": "onConfigUpdated", "signature": "def onConfigUpdated(self, config)" } ]
2
stack_v2_sparse_classes_30k_train_016285
Implement the Python class `ConfigBackupPlugin` described below. Class description: ConfigBackup Plugin Method signatures and docstrings: - def __init__(self, config, registry): Constructor - def onConfigUpdated(self, config): Save the configuration to disk
Implement the Python class `ConfigBackupPlugin` described below. Class description: ConfigBackup Plugin Method signatures and docstrings: - def __init__(self, config, registry): Constructor - def onConfigUpdated(self, config): Save the configuration to disk <|skeleton|> class ConfigBackupPlugin: """ConfigBackup ...
27b3c26d72ad943f14598d409e029e8dd9f9597b
<|skeleton|> class ConfigBackupPlugin: """ConfigBackup Plugin""" def __init__(self, config, registry): """Constructor""" <|body_0|> def onConfigUpdated(self, config): """Save the configuration to disk""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConfigBackupPlugin: """ConfigBackup Plugin""" def __init__(self, config, registry): """Constructor""" if 'path' in config: self.path = config['path'] else: raise Exception('Path must be specified') if 'format' in config: if config['forma...
the_stack_v2_python_sparse
plugins/configbackup.py
geneanet/moneta
train
6
f5a0fd43b0d104e3a05d49c794231261362352e3
[ "review: Review = self.get_object()\nreview.helpful.add(request.user)\nserializer: ReviewSerializer = self.get_serializer(review)\nreturn Response(data=serializer.data, status=status.HTTP_200_OK)", "review: Review = self.get_object()\nreview.helpful.remove(request.user)\nserializer: ReviewSerializer = self.get_se...
<|body_start_0|> review: Review = self.get_object() review.helpful.add(request.user) serializer: ReviewSerializer = self.get_serializer(review) return Response(data=serializer.data, status=status.HTTP_200_OK) <|end_body_0|> <|body_start_1|> review: Review = self.get_object() ...
Review helpful view.
ReviewHelpful
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReviewHelpful: """Review helpful view.""" def post(self, request: Request, *args: tuple, **kwargs: dict) -> Response: """Set the review as helpful. :param request: Request :return: Review""" <|body_0|> def delete(self, request: Request, *args: tuple, **kwargs: dict) -> R...
stack_v2_sparse_classes_75kplus_train_001311
5,590
no_license
[ { "docstring": "Set the review as helpful. :param request: Request :return: Review", "name": "post", "signature": "def post(self, request: Request, *args: tuple, **kwargs: dict) -> Response" }, { "docstring": "Unset the review as helpful. :param request: Request :return: Review", "name": "de...
2
stack_v2_sparse_classes_30k_train_003080
Implement the Python class `ReviewHelpful` described below. Class description: Review helpful view. Method signatures and docstrings: - def post(self, request: Request, *args: tuple, **kwargs: dict) -> Response: Set the review as helpful. :param request: Request :return: Review - def delete(self, request: Request, *a...
Implement the Python class `ReviewHelpful` described below. Class description: Review helpful view. Method signatures and docstrings: - def post(self, request: Request, *args: tuple, **kwargs: dict) -> Response: Set the review as helpful. :param request: Request :return: Review - def delete(self, request: Request, *a...
713b9d84ac70d964d46f189ab1f9c7b944b9684b
<|skeleton|> class ReviewHelpful: """Review helpful view.""" def post(self, request: Request, *args: tuple, **kwargs: dict) -> Response: """Set the review as helpful. :param request: Request :return: Review""" <|body_0|> def delete(self, request: Request, *args: tuple, **kwargs: dict) -> R...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ReviewHelpful: """Review helpful view.""" def post(self, request: Request, *args: tuple, **kwargs: dict) -> Response: """Set the review as helpful. :param request: Request :return: Review""" review: Review = self.get_object() review.helpful.add(request.user) serializer: Re...
the_stack_v2_python_sparse
jobadvisor/reviews/views/review.py
ewgen19892/jobadvisor
train
0
e5384eb43e13c957e1671e1a80f9f3d35df665c4
[ "if timezoneName is None:\n timezoneName = self.defaultTimezoneName\ndt = timeutil.now(timezoneName)\nsource.reply(timeutil.format(dt, self.timeFormat))", "if timezoneName is None:\n timezoneName = self.defaultTimezoneName\ndt = timeutil.convert(timeString, timezoneName, self.defaultTimezoneName)\nsource.re...
<|body_start_0|> if timezoneName is None: timezoneName = self.defaultTimezoneName dt = timeutil.now(timezoneName) source.reply(timeutil.format(dt, self.timeFormat)) <|end_body_0|> <|body_start_1|> if timezoneName is None: timezoneName = self.defaultTimezoneName ...
Time-related functions.
Time
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Time: """Time-related functions.""" def cmd_now(self, source, timezoneName=None): """Show the current time in the default timezone, or <timezoneName>.""" <|body_0|> def cmd_convert(self, source, timeString, timezoneName=None): """Convert <timeString> to the defau...
stack_v2_sparse_classes_75kplus_train_001312
1,669
permissive
[ { "docstring": "Show the current time in the default timezone, or <timezoneName>.", "name": "cmd_now", "signature": "def cmd_now(self, source, timezoneName=None)" }, { "docstring": "Convert <timeString> to the default timezone, or <timezoneName>. <timeString> should be a valid time string, the f...
2
stack_v2_sparse_classes_30k_train_032119
Implement the Python class `Time` described below. Class description: Time-related functions. Method signatures and docstrings: - def cmd_now(self, source, timezoneName=None): Show the current time in the default timezone, or <timezoneName>. - def cmd_convert(self, source, timeString, timezoneName=None): Convert <tim...
Implement the Python class `Time` described below. Class description: Time-related functions. Method signatures and docstrings: - def cmd_now(self, source, timezoneName=None): Show the current time in the default timezone, or <timezoneName>. - def cmd_convert(self, source, timeString, timezoneName=None): Convert <tim...
11c80c7024548ce7c41800b077d3d0a738a04875
<|skeleton|> class Time: """Time-related functions.""" def cmd_now(self, source, timezoneName=None): """Show the current time in the default timezone, or <timezoneName>.""" <|body_0|> def cmd_convert(self, source, timeString, timezoneName=None): """Convert <timeString> to the defau...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Time: """Time-related functions.""" def cmd_now(self, source, timezoneName=None): """Show the current time in the default timezone, or <timezoneName>.""" if timezoneName is None: timezoneName = self.defaultTimezoneName dt = timeutil.now(timezoneName) source.rep...
the_stack_v2_python_sparse
eridanusstd/plugindefs/time.py
mithrandi/eridanus
train
0
c416bb36fc141debebd4f63bd7372035523d5e34
[ "if request.user.is_authenticated:\n lists = ListsStream().get_list_stream(request.user)\nelse:\n lists = models.List.objects.filter(privacy='public')\npaginated = Paginator(lists, 12)\ndata = {'lists': paginated.get_page(request.GET.get('page')), 'list_form': forms.ListForm(), 'path': '/list'}\nreturn Templa...
<|body_start_0|> if request.user.is_authenticated: lists = ListsStream().get_list_stream(request.user) else: lists = models.List.objects.filter(privacy='public') paginated = Paginator(lists, 12) data = {'lists': paginated.get_page(request.GET.get('page')), 'list_f...
book list page
Lists
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Lists: """book list page""" def get(self, request): """display a book list""" <|body_0|> def post(self, request): """create a book_list""" <|body_1|> <|end_skeleton|> <|body_start_0|> if request.user.is_authenticated: lists = ListsSt...
stack_v2_sparse_classes_75kplus_train_001313
2,823
no_license
[ { "docstring": "display a book list", "name": "get", "signature": "def get(self, request)" }, { "docstring": "create a book_list", "name": "post", "signature": "def post(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_006861
Implement the Python class `Lists` described below. Class description: book list page Method signatures and docstrings: - def get(self, request): display a book list - def post(self, request): create a book_list
Implement the Python class `Lists` described below. Class description: book list page Method signatures and docstrings: - def get(self, request): display a book list - def post(self, request): create a book_list <|skeleton|> class Lists: """book list page""" def get(self, request): """display a book...
0f8da5b738047f3c34d60d93f59bdedd8f797224
<|skeleton|> class Lists: """book list page""" def get(self, request): """display a book list""" <|body_0|> def post(self, request): """create a book_list""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Lists: """book list page""" def get(self, request): """display a book list""" if request.user.is_authenticated: lists = ListsStream().get_list_stream(request.user) else: lists = models.List.objects.filter(privacy='public') paginated = Paginator(list...
the_stack_v2_python_sparse
bookwyrm/views/list/lists.py
bookwyrm-social/bookwyrm
train
1,398
ac7070f701a0cfa5199b92e0e333614fb76fcec2
[ "post_to_delete = self.post1\nresponse = self.client.delete('/1.0/posts/{0}/'.format(post_to_delete.id))\nself.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)", "self.client.login(username=self.user.username, password=self.user.raw_password)\npost_to_delete = self.post1\nresponse = self.client.delete...
<|body_start_0|> post_to_delete = self.post1 response = self.client.delete('/1.0/posts/{0}/'.format(post_to_delete.id)) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) <|end_body_0|> <|body_start_1|> self.client.login(username=self.user.username, password=self.user.raw...
PostDeleteAPITest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PostDeleteAPITest: def test_post_cannot_be_deleted_by_anonymous(self): """Ensures that a post cannot be deleted by anonymous user""" <|body_0|> def test_post_cannot_be_deleted_by_other(self): """Ensures that a post cannot be deleted by other""" <|body_1|> ...
stack_v2_sparse_classes_75kplus_train_001314
20,627
no_license
[ { "docstring": "Ensures that a post cannot be deleted by anonymous user", "name": "test_post_cannot_be_deleted_by_anonymous", "signature": "def test_post_cannot_be_deleted_by_anonymous(self)" }, { "docstring": "Ensures that a post cannot be deleted by other", "name": "test_post_cannot_be_del...
4
stack_v2_sparse_classes_30k_train_036853
Implement the Python class `PostDeleteAPITest` described below. Class description: Implement the PostDeleteAPITest class. Method signatures and docstrings: - def test_post_cannot_be_deleted_by_anonymous(self): Ensures that a post cannot be deleted by anonymous user - def test_post_cannot_be_deleted_by_other(self): En...
Implement the Python class `PostDeleteAPITest` described below. Class description: Implement the PostDeleteAPITest class. Method signatures and docstrings: - def test_post_cannot_be_deleted_by_anonymous(self): Ensures that a post cannot be deleted by anonymous user - def test_post_cannot_be_deleted_by_other(self): En...
56bfe19853bfec4581870a0075d0f21ee4d4bfda
<|skeleton|> class PostDeleteAPITest: def test_post_cannot_be_deleted_by_anonymous(self): """Ensures that a post cannot be deleted by anonymous user""" <|body_0|> def test_post_cannot_be_deleted_by_other(self): """Ensures that a post cannot be deleted by other""" <|body_1|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PostDeleteAPITest: def test_post_cannot_be_deleted_by_anonymous(self): """Ensures that a post cannot be deleted by anonymous user""" post_to_delete = self.post1 response = self.client.delete('/1.0/posts/{0}/'.format(post_to_delete.id)) self.assertEqual(response.status_code, sta...
the_stack_v2_python_sparse
blogs/tests.py
dmpinero/practica_Python_Django_Avanzado
train
0
d0a06143d180691c7d316339dcfeea61ae1a637c
[ "super().__init__()\nself.phoneme_predictor = Encoder(idim=-1, input_layer=None, attention_dim=attention_dim, attention_heads=attention_heads, linear_units=linear_units, num_blocks=blocks, dropout_rate=dropout_rate, positional_dropout_rate=positional_dropout_rate, attention_dropout_rate=attention_dropout_rate, norm...
<|body_start_0|> super().__init__() self.phoneme_predictor = Encoder(idim=-1, input_layer=None, attention_dim=attention_dim, attention_heads=attention_heads, linear_units=linear_units, num_blocks=blocks, dropout_rate=dropout_rate, positional_dropout_rate=positional_dropout_rate, attention_dropout_rate=a...
Phoneme Predictor module in VISinger.
PhonemePredictor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PhonemePredictor: """Phoneme Predictor module in VISinger.""" def __init__(self, vocabs: int, hidden_channels: int=192, attention_dim: int=192, attention_heads: int=2, linear_units: int=768, blocks: int=2, positionwise_layer_type: str='conv1d', positionwise_conv_kernel_size: int=3, positiona...
stack_v2_sparse_classes_75kplus_train_001315
4,212
permissive
[ { "docstring": "Initialize PhonemePredictor module. Args: vocabs (int): The number of vocabulary. hidden_channels (int): The number of hidden channels. attention_dim (int): The number of attention dimension. attention_heads (int): The number of attention heads. linear_units (int): The number of linear units. bl...
2
null
Implement the Python class `PhonemePredictor` described below. Class description: Phoneme Predictor module in VISinger. Method signatures and docstrings: - def __init__(self, vocabs: int, hidden_channels: int=192, attention_dim: int=192, attention_heads: int=2, linear_units: int=768, blocks: int=2, positionwise_layer...
Implement the Python class `PhonemePredictor` described below. Class description: Phoneme Predictor module in VISinger. Method signatures and docstrings: - def __init__(self, vocabs: int, hidden_channels: int=192, attention_dim: int=192, attention_heads: int=2, linear_units: int=768, blocks: int=2, positionwise_layer...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class PhonemePredictor: """Phoneme Predictor module in VISinger.""" def __init__(self, vocabs: int, hidden_channels: int=192, attention_dim: int=192, attention_heads: int=2, linear_units: int=768, blocks: int=2, positionwise_layer_type: str='conv1d', positionwise_conv_kernel_size: int=3, positiona...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PhonemePredictor: """Phoneme Predictor module in VISinger.""" def __init__(self, vocabs: int, hidden_channels: int=192, attention_dim: int=192, attention_heads: int=2, linear_units: int=768, blocks: int=2, positionwise_layer_type: str='conv1d', positionwise_conv_kernel_size: int=3, positional_encoding_la...
the_stack_v2_python_sparse
espnet2/gan_svs/vits/phoneme_predictor.py
espnet/espnet
train
7,242
da310b3991feb15ed362c955412aefb1f5b50f75
[ "for treasury in self:\n if treasury.date_from:\n self.env['payment.treasury'].compute_payments(treasury.id, treasury.date_from)\nreturn True", "for treasury in self:\n if treasury.date_from:\n self.env['sale.purchase.treasury'].compute_sale_purchase(treasury.id, treasury.date_from)\nreturn Tr...
<|body_start_0|> for treasury in self: if treasury.date_from: self.env['payment.treasury'].compute_payments(treasury.id, treasury.date_from) return True <|end_body_0|> <|body_start_1|> for treasury in self: if treasury.date_from: self.env[...
Object for the treasury
treasury
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class treasury: """Object for the treasury""" def compute_payment_list(self): """Fonction qui calcule les payments fait sur l'année sélectionnée""" <|body_0|> def compute_sale_purchase_list(self): """Fonction qui calcule le montant des ventes et achats en cours""" ...
stack_v2_sparse_classes_75kplus_train_001316
43,695
no_license
[ { "docstring": "Fonction qui calcule les payments fait sur l'année sélectionnée", "name": "compute_payment_list", "signature": "def compute_payment_list(self)" }, { "docstring": "Fonction qui calcule le montant des ventes et achats en cours", "name": "compute_sale_purchase_list", "signat...
4
stack_v2_sparse_classes_30k_train_048720
Implement the Python class `treasury` described below. Class description: Object for the treasury Method signatures and docstrings: - def compute_payment_list(self): Fonction qui calcule les payments fait sur l'année sélectionnée - def compute_sale_purchase_list(self): Fonction qui calcule le montant des ventes et ac...
Implement the Python class `treasury` described below. Class description: Object for the treasury Method signatures and docstrings: - def compute_payment_list(self): Fonction qui calcule les payments fait sur l'année sélectionnée - def compute_sale_purchase_list(self): Fonction qui calcule le montant des ventes et ac...
eb394e1f79ba1995da2dcd81adfdd511c22caff9
<|skeleton|> class treasury: """Object for the treasury""" def compute_payment_list(self): """Fonction qui calcule les payments fait sur l'année sélectionnée""" <|body_0|> def compute_sale_purchase_list(self): """Fonction qui calcule le montant des ventes et achats en cours""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class treasury: """Object for the treasury""" def compute_payment_list(self): """Fonction qui calcule les payments fait sur l'année sélectionnée""" for treasury in self: if treasury.date_from: self.env['payment.treasury'].compute_payments(treasury.id, treasury.date_f...
the_stack_v2_python_sparse
OpenPROD/openprod-addons/control_management/treasury.py
kazacube-mziouadi/ceci
train
0
1b777e3718fd08ed139698530a101d848cb29f8d
[ "super(LSTMEncoder, self).__init__(embed=L.EmbedID(in_size, embed_size), lstm=L.NStepLSTM(n_layers, embed_size, out_size, dropout))\nfor param in self.params():\n param.data[...] = np.random.uniform(-0.1, 0.1, param.data.shape)", "if len(xs) > 1:\n sections = np.cumsum(np.array([len(x) for x in xs[:-1]], dt...
<|body_start_0|> super(LSTMEncoder, self).__init__(embed=L.EmbedID(in_size, embed_size), lstm=L.NStepLSTM(n_layers, embed_size, out_size, dropout)) for param in self.params(): param.data[...] = np.random.uniform(-0.1, 0.1, param.data.shape) <|end_body_0|> <|body_start_1|> if len(xs)...
LSTMEncoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LSTMEncoder: def __init__(self, n_layers, in_size, out_size, embed_size, dropout=0.5): """Initialize encoder with structure parameters Args: n_layers (int): Number of layers. in_size (int): Dimensionality of input vectors. out_size (int) : Dimensionality of hidden vectors to be output. e...
stack_v2_sparse_classes_75kplus_train_001317
2,094
permissive
[ { "docstring": "Initialize encoder with structure parameters Args: n_layers (int): Number of layers. in_size (int): Dimensionality of input vectors. out_size (int) : Dimensionality of hidden vectors to be output. embed_size (int): Dimensionality of word embedding. dropout (float): Dropout ratio.", "name": "...
2
null
Implement the Python class `LSTMEncoder` described below. Class description: Implement the LSTMEncoder class. Method signatures and docstrings: - def __init__(self, n_layers, in_size, out_size, embed_size, dropout=0.5): Initialize encoder with structure parameters Args: n_layers (int): Number of layers. in_size (int)...
Implement the Python class `LSTMEncoder` described below. Class description: Implement the LSTMEncoder class. Method signatures and docstrings: - def __init__(self, n_layers, in_size, out_size, embed_size, dropout=0.5): Initialize encoder with structure parameters Args: n_layers (int): Number of layers. in_size (int)...
f142c3025e03adef99c0d97be663f0799adf5524
<|skeleton|> class LSTMEncoder: def __init__(self, n_layers, in_size, out_size, embed_size, dropout=0.5): """Initialize encoder with structure parameters Args: n_layers (int): Number of layers. in_size (int): Dimensionality of input vectors. out_size (int) : Dimensionality of hidden vectors to be output. e...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LSTMEncoder: def __init__(self, n_layers, in_size, out_size, embed_size, dropout=0.5): """Initialize encoder with structure parameters Args: n_layers (int): Number of layers. in_size (int): Dimensionality of input vectors. out_size (int) : Dimensionality of hidden vectors to be output. embed_size (int...
the_stack_v2_python_sparse
ChatbotBaseline/tools/lstm_encoder.py
katherinelyx/DSTC6-End-to-End-Conversation-Modeling
train
0
626a0df7be36587dd3ff4ba78ec3ef0915a117ee
[ "user = self.model(username=username, auth_groups=[], auth_roles=[], email=self.normalize_email(email))\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "user = self.create_user(username=username, email=self.normalize_email(email))\nuser.is_superuser = True\nuser.auth_groups = []\nuser.auth_...
<|body_start_0|> user = self.model(username=username, auth_groups=[], auth_roles=[], email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_start_1|> user = self.create_user(username=username, email=self.normali...
MyUserManager
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyUserManager: def create_user(self, username, email, password=None): """Creates and saves a User with the given email, date of birth and password.""" <|body_0|> def create_superuser(self, username, email, password): """Creates and saves a superuser with the given em...
stack_v2_sparse_classes_75kplus_train_001318
2,419
permissive
[ { "docstring": "Creates and saves a User with the given email, date of birth and password.", "name": "create_user", "signature": "def create_user(self, username, email, password=None)" }, { "docstring": "Creates and saves a superuser with the given email, date of birth and password.", "name"...
2
stack_v2_sparse_classes_30k_train_031469
Implement the Python class `MyUserManager` described below. Class description: Implement the MyUserManager class. Method signatures and docstrings: - def create_user(self, username, email, password=None): Creates and saves a User with the given email, date of birth and password. - def create_superuser(self, username,...
Implement the Python class `MyUserManager` described below. Class description: Implement the MyUserManager class. Method signatures and docstrings: - def create_user(self, username, email, password=None): Creates and saves a User with the given email, date of birth and password. - def create_superuser(self, username,...
52831b2de2e0ce734d567289f3b10d720bce8a9e
<|skeleton|> class MyUserManager: def create_user(self, username, email, password=None): """Creates and saves a User with the given email, date of birth and password.""" <|body_0|> def create_superuser(self, username, email, password): """Creates and saves a superuser with the given em...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyUserManager: def create_user(self, username, email, password=None): """Creates and saves a User with the given email, date of birth and password.""" user = self.model(username=username, auth_groups=[], auth_roles=[], email=self.normalize_email(email)) user.set_password(password) ...
the_stack_v2_python_sparse
coordinator/models.py
kids-first/kf-api-release-coordinator
train
2
93965f7990b3f3f128d051b99b6e550b136ab733
[ "if not (is_scalar(prior) or isinstance(prior, Beta) or is_any_numeric_map(prior) or is_any_beta_map(prior)):\n raise ValueError('wrong type for prior')\nif not (is_scalar(likelihood) or isinstance(likelihood, Beta) or is_any_numeric_map(likelihood) or is_any_beta_map(likelihood)):\n raise ValueError('wrong t...
<|body_start_0|> if not (is_scalar(prior) or isinstance(prior, Beta) or is_any_numeric_map(prior) or is_any_beta_map(prior)): raise ValueError('wrong type for prior') if not (is_scalar(likelihood) or isinstance(likelihood, Beta) or is_any_numeric_map(likelihood) or is_any_beta_map(likelihood...
Class for testing one or more binary hypotheses using Bayes Rule.
BinaryBayesRule
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinaryBayesRule: """Class for testing one or more binary hypotheses using Bayes Rule.""" def __init__(self, prior: Union[float, Beta, AnyFloatMap, AnyBetaMap], likelihood: Union[float, Beta, AnyFloatMap, AnyBetaMap]): """Create a new Bayes Rule object from: - the prior P(A) - the lik...
stack_v2_sparse_classes_75kplus_train_001319
2,366
permissive
[ { "docstring": "Create a new Bayes Rule object from: - the prior P(A) - the likelihood P(B|A) - the evidence P(B) :param prior: Single figure or Beta-distributed probability representing the hypothesis. :param likelihood: Series with values of Dirichlet likelihoods.", "name": "__init__", "signature": "d...
2
stack_v2_sparse_classes_30k_train_017060
Implement the Python class `BinaryBayesRule` described below. Class description: Class for testing one or more binary hypotheses using Bayes Rule. Method signatures and docstrings: - def __init__(self, prior: Union[float, Beta, AnyFloatMap, AnyBetaMap], likelihood: Union[float, Beta, AnyFloatMap, AnyBetaMap]): Create...
Implement the Python class `BinaryBayesRule` described below. Class description: Class for testing one or more binary hypotheses using Bayes Rule. Method signatures and docstrings: - def __init__(self, prior: Union[float, Beta, AnyFloatMap, AnyBetaMap], likelihood: Union[float, Beta, AnyFloatMap, AnyBetaMap]): Create...
ff3f5434d3da0d46b127b02cf733699e5a43c904
<|skeleton|> class BinaryBayesRule: """Class for testing one or more binary hypotheses using Bayes Rule.""" def __init__(self, prior: Union[float, Beta, AnyFloatMap, AnyBetaMap], likelihood: Union[float, Beta, AnyFloatMap, AnyBetaMap]): """Create a new Bayes Rule object from: - the prior P(A) - the lik...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BinaryBayesRule: """Class for testing one or more binary hypotheses using Bayes Rule.""" def __init__(self, prior: Union[float, Beta, AnyFloatMap, AnyBetaMap], likelihood: Union[float, Beta, AnyFloatMap, AnyBetaMap]): """Create a new Bayes Rule object from: - the prior P(A) - the likelihood P(B|A...
the_stack_v2_python_sparse
probability/calculations/bayes_rule/binary_bayes_rule.py
vahndi/probability
train
3
b62ec78cfa99f58b158cfb398dcf1567b56a68eb
[ "publications = []\njournals = []\nfor pub in pub_list:\n if drug_name in pub.title.upper():\n publications.append({'title': pub.title, 'publication_date': pub.pub_date})\n journals.append({'journal': pub.journal, 'publication_date': pub.pub_date})\nreturn (publications, journals)", "graph = {}\n...
<|body_start_0|> publications = [] journals = [] for pub in pub_list: if drug_name in pub.title.upper(): publications.append({'title': pub.title, 'publication_date': pub.pub_date}) journals.append({'journal': pub.journal, 'publication_date': pub.pub_da...
This class is responsible for generating a graph showing the relation between the drugs and medical publications, clinical trialas, and journals.
PublicationInfoService
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PublicationInfoService: """This class is responsible for generating a graph showing the relation between the drugs and medical publications, clinical trialas, and journals.""" def find_mentions(self, drug_name, pub_list): """Finds the list of medical publication or clinical trials in...
stack_v2_sparse_classes_75kplus_train_001320
2,518
no_license
[ { "docstring": "Finds the list of medical publication or clinical trials in which the drug is mentions. It also generates the list of journals mentioning the drug along with its publication date. :param drug_name: the name of the drug :param pub_list: the list of the Publications :return: a tuble containing fir...
2
stack_v2_sparse_classes_30k_train_020068
Implement the Python class `PublicationInfoService` described below. Class description: This class is responsible for generating a graph showing the relation between the drugs and medical publications, clinical trialas, and journals. Method signatures and docstrings: - def find_mentions(self, drug_name, pub_list): Fi...
Implement the Python class `PublicationInfoService` described below. Class description: This class is responsible for generating a graph showing the relation between the drugs and medical publications, clinical trialas, and journals. Method signatures and docstrings: - def find_mentions(self, drug_name, pub_list): Fi...
5a1375bced6ba27c1504faa198703f0ec3f2eccd
<|skeleton|> class PublicationInfoService: """This class is responsible for generating a graph showing the relation between the drugs and medical publications, clinical trialas, and journals.""" def find_mentions(self, drug_name, pub_list): """Finds the list of medical publication or clinical trials in...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PublicationInfoService: """This class is responsible for generating a graph showing the relation between the drugs and medical publications, clinical trialas, and journals.""" def find_mentions(self, drug_name, pub_list): """Finds the list of medical publication or clinical trials in which the dr...
the_stack_v2_python_sparse
drug_analysis_pipeline/src/service/publication_info_service.py
navilaji/servier-medics-data-pipeline
train
0
aae80aa54f097f48155dcca93701c06ae5fc4d82
[ "datos_persona = ('41694463V', 'Jose Lopez', 'Guest', 'jllopez@inf.uc3m.es', 'SIEMPRE')\nwith self.assertRaises(AccessManagementException) as res:\n AccessManager().request_access_code(datos_persona)\nself.assertEqual(res.exception.message, 'Número de días no válido')", "datos_persona = ('41694463V', 'Jose Lop...
<|body_start_0|> datos_persona = ('41694463V', 'Jose Lopez', 'Guest', 'jllopez@inf.uc3m.es', 'SIEMPRE') with self.assertRaises(AccessManagementException) as res: AccessManager().request_access_code(datos_persona) self.assertEqual(res.exception.message, 'Número de días no válido') <|e...
Clase para probar request_access_code
MyTestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyTestCase: """Clase para probar request_access_code""" def test_request_access_code_validity_not_a_number(self): """Validity no es un número""" <|body_0|> def test_request_access_code_validity_resident_days_not_0(self): """El AccessType es Resient y la validity ...
stack_v2_sparse_classes_75kplus_train_001321
2,690
no_license
[ { "docstring": "Validity no es un número", "name": "test_request_access_code_validity_not_a_number", "signature": "def test_request_access_code_validity_not_a_number(self)" }, { "docstring": "El AccessType es Resient y la validity no es 0", "name": "test_request_access_code_validity_resident...
6
stack_v2_sparse_classes_30k_train_038720
Implement the Python class `MyTestCase` described below. Class description: Clase para probar request_access_code Method signatures and docstrings: - def test_request_access_code_validity_not_a_number(self): Validity no es un número - def test_request_access_code_validity_resident_days_not_0(self): El AccessType es R...
Implement the Python class `MyTestCase` described below. Class description: Clase para probar request_access_code Method signatures and docstrings: - def test_request_access_code_validity_not_a_number(self): Validity no es un número - def test_request_access_code_validity_resident_days_not_0(self): El AccessType es R...
3ea97edc2ae23ead6419c3d8d96f2df8e230edc7
<|skeleton|> class MyTestCase: """Clase para probar request_access_code""" def test_request_access_code_validity_not_a_number(self): """Validity no es un número""" <|body_0|> def test_request_access_code_validity_resident_days_not_0(self): """El AccessType es Resient y la validity ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyTestCase: """Clase para probar request_access_code""" def test_request_access_code_validity_not_a_number(self): """Validity no es un número""" datos_persona = ('41694463V', 'Jose Lopez', 'Guest', 'jllopez@inf.uc3m.es', 'SIEMPRE') with self.assertRaises(AccessManagementException)...
the_stack_v2_python_sparse
src/unittest/python/test_request_access_code_2_tests.py
Gllosa/G80.T08.EG3
train
0
f3b928986c0b8b3588b0b5e195041c07725e641f
[ "res = super(StudentAttendanceByMonth, self).default_get(fields)\nstudents = self.env['student.student'].browse(self._context.get('active_id'))\nif students.state == 'draft':\n raise ValidationError(_('You can not print report for student in unconfirm state!'))\nreturn res", "stud_search = self.env['student.st...
<|body_start_0|> res = super(StudentAttendanceByMonth, self).default_get(fields) students = self.env['student.student'].browse(self._context.get('active_id')) if students.state == 'draft': raise ValidationError(_('You can not print report for student in unconfirm state!')) re...
Defining Student Attendance By Month.
StudentAttendanceByMonth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StudentAttendanceByMonth: """Defining Student Attendance By Month.""" def default_get(self, fields): """Overriding DefaultGet.""" <|body_0|> def print_report(self): """This method prints report @param self : Object Pointer @param cr : Database Cursor @param uid :...
stack_v2_sparse_classes_75kplus_train_001322
2,598
no_license
[ { "docstring": "Overriding DefaultGet.", "name": "default_get", "signature": "def default_get(self, fields)" }, { "docstring": "This method prints report @param self : Object Pointer @param cr : Database Cursor @param uid : Current Logged in User @param ids : Current Records @param context : sta...
2
stack_v2_sparse_classes_30k_train_020562
Implement the Python class `StudentAttendanceByMonth` described below. Class description: Defining Student Attendance By Month. Method signatures and docstrings: - def default_get(self, fields): Overriding DefaultGet. - def print_report(self): This method prints report @param self : Object Pointer @param cr : Databas...
Implement the Python class `StudentAttendanceByMonth` described below. Class description: Defining Student Attendance By Month. Method signatures and docstrings: - def default_get(self, fields): Overriding DefaultGet. - def print_report(self): This method prints report @param self : Object Pointer @param cr : Databas...
6a9793f3a15da9eed40bf840b1d9a46457c5fd55
<|skeleton|> class StudentAttendanceByMonth: """Defining Student Attendance By Month.""" def default_get(self, fields): """Overriding DefaultGet.""" <|body_0|> def print_report(self): """This method prints report @param self : Object Pointer @param cr : Database Cursor @param uid :...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StudentAttendanceByMonth: """Defining Student Attendance By Month.""" def default_get(self, fields): """Overriding DefaultGet.""" res = super(StudentAttendanceByMonth, self).default_get(fields) students = self.env['student.student'].browse(self._context.get('active_id')) i...
the_stack_v2_python_sparse
school_attendance/wizard/student_attendance_by_month.py
JayVora-SerpentCS/OdooEduERP
train
121
cc7468515370e4a4845ed45bba1746e7a3b83941
[ "super().__init__()\nself.config = params\ntry:\n self.my_device = self.config['my_device']\nexcept:\n self.my_device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n'\\n NV uses padding = \"same\" to preserve the input and output size of conv.\\n We can do the same as follows:...
<|body_start_0|> super().__init__() self.config = params try: self.my_device = self.config['my_device'] except: self.my_device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') '\n NV uses padding = "same" to preserve the input and ou...
Implement the architecture from Nielsen and Voigt (2018)
NVCNN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NVCNN: """Implement the architecture from Nielsen and Voigt (2018)""" def __init__(self, params): """Params are: vocab_size: the number of dimensions in the 1-hot encoding lr: learning rate filter_number: number of filters (in NV, 1-512) filter_len: length of filters (in NV, 1-48) nu...
stack_v2_sparse_classes_75kplus_train_001323
34,560
no_license
[ { "docstring": "Params are: vocab_size: the number of dimensions in the 1-hot encoding lr: learning rate filter_number: number of filters (in NV, 1-512) filter_len: length of filters (in NV, 1-48) num_dense_nodes: size of dense layer after filters input_len: length of input (batch_size, vocab_size, input_len) n...
2
stack_v2_sparse_classes_30k_train_016433
Implement the Python class `NVCNN` described below. Class description: Implement the architecture from Nielsen and Voigt (2018) Method signatures and docstrings: - def __init__(self, params): Params are: vocab_size: the number of dimensions in the 1-hot encoding lr: learning rate filter_number: number of filters (in ...
Implement the Python class `NVCNN` described below. Class description: Implement the architecture from Nielsen and Voigt (2018) Method signatures and docstrings: - def __init__(self, params): Params are: vocab_size: the number of dimensions in the 1-hot encoding lr: learning rate filter_number: number of filters (in ...
b850f7c91e16e3dacca4d3b6377c77502960dd19
<|skeleton|> class NVCNN: """Implement the architecture from Nielsen and Voigt (2018)""" def __init__(self, params): """Params are: vocab_size: the number of dimensions in the 1-hot encoding lr: learning rate filter_number: number of filters (in NV, 1-512) filter_len: length of filters (in NV, 1-48) nu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NVCNN: """Implement the architecture from Nielsen and Voigt (2018)""" def __init__(self, params): """Params are: vocab_size: the number of dimensions in the 1-hot encoding lr: learning rate filter_number: number of filters (in NV, 1-512) filter_len: length of filters (in NV, 1-48) num_dense_nodes...
the_stack_v2_python_sparse
common/mytorch.py
altLabs/attrib
train
1
7b80b4729b055503c80de3aee520dc092a4a9a25
[ "context = super().get_context_data(**kwargs)\ncar = APIHelper.get_from_api('car/' + id, self.request.user.auth_token)\ntask_list = APIHelper.get_from_api('car/' + id + '/tasks/', self.request.user.auth_token)\npart_list = APIHelper.get_from_api('parts/', self.request.user.auth_token)\ncontext['car'] = car\ncontext...
<|body_start_0|> context = super().get_context_data(**kwargs) car = APIHelper.get_from_api('car/' + id, self.request.user.auth_token) task_list = APIHelper.get_from_api('car/' + id + '/tasks/', self.request.user.auth_token) part_list = APIHelper.get_from_api('parts/', self.request.user.a...
Class that handles the car detail frontend view GET - Returns default template POST - Sends complete date for a task
CarView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CarView: """Class that handles the car detail frontend view GET - Returns default template POST - Sends complete date for a task""" def get_context_data(self, id, **kwargs): """Override the get_context_data method to add new data to the context dictionary that is passed to the templa...
stack_v2_sparse_classes_75kplus_train_001324
2,202
no_license
[ { "docstring": "Override the get_context_data method to add new data to the context dictionary that is passed to the template", "name": "get_context_data", "signature": "def get_context_data(self, id, **kwargs)" }, { "docstring": "Used to complete a task", "name": "post", "signature": "d...
2
stack_v2_sparse_classes_30k_train_010528
Implement the Python class `CarView` described below. Class description: Class that handles the car detail frontend view GET - Returns default template POST - Sends complete date for a task Method signatures and docstrings: - def get_context_data(self, id, **kwargs): Override the get_context_data method to add new da...
Implement the Python class `CarView` described below. Class description: Class that handles the car detail frontend view GET - Returns default template POST - Sends complete date for a task Method signatures and docstrings: - def get_context_data(self, id, **kwargs): Override the get_context_data method to add new da...
3a768f37e14732b79f3f0d28e772cec38a6a9ed1
<|skeleton|> class CarView: """Class that handles the car detail frontend view GET - Returns default template POST - Sends complete date for a task""" def get_context_data(self, id, **kwargs): """Override the get_context_data method to add new data to the context dictionary that is passed to the templa...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CarView: """Class that handles the car detail frontend view GET - Returns default template POST - Sends complete date for a task""" def get_context_data(self, id, **kwargs): """Override the get_context_data method to add new data to the context dictionary that is passed to the template""" ...
the_stack_v2_python_sparse
frontend/views/car_view.py
kevinbooth/redline
train
2
0b5ea9cb721ea9c4caeac2b5d2b7f0d08ecfc156
[ "group_management_page = GroupManagementPage(self.driver)\ngroup_management_page.new_group(data['groupName'], data['groupInfo'], data['groupType'], data['participants'])\ngroup_management_page.filter_search(data['groupName'])\nself.assertIsNotNone(self.driver.get_element(group_management_page.elements['listGroupNam...
<|body_start_0|> group_management_page = GroupManagementPage(self.driver) group_management_page.new_group(data['groupName'], data['groupInfo'], data['groupType'], data['participants']) group_management_page.filter_search(data['groupName']) self.assertIsNotNone(self.driver.get_element(gro...
GroupManagementTestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroupManagementTestCase: def test_new_group_success_1(self, data): """新建分组,成功""" <|body_0|> def test_new_group_failed_1(self, data): """新建分组名称为空失败""" <|body_1|> def test_new_group_failed_2(self, data): """新建分组异常失败""" <|body_2|> <|end_ske...
stack_v2_sparse_classes_75kplus_train_001325
1,996
no_license
[ { "docstring": "新建分组,成功", "name": "test_new_group_success_1", "signature": "def test_new_group_success_1(self, data)" }, { "docstring": "新建分组名称为空失败", "name": "test_new_group_failed_1", "signature": "def test_new_group_failed_1(self, data)" }, { "docstring": "新建分组异常失败", "name"...
3
stack_v2_sparse_classes_30k_train_030336
Implement the Python class `GroupManagementTestCase` described below. Class description: Implement the GroupManagementTestCase class. Method signatures and docstrings: - def test_new_group_success_1(self, data): 新建分组,成功 - def test_new_group_failed_1(self, data): 新建分组名称为空失败 - def test_new_group_failed_2(self, data): 新...
Implement the Python class `GroupManagementTestCase` described below. Class description: Implement the GroupManagementTestCase class. Method signatures and docstrings: - def test_new_group_success_1(self, data): 新建分组,成功 - def test_new_group_failed_1(self, data): 新建分组名称为空失败 - def test_new_group_failed_2(self, data): 新...
62dcefdccad1b91827072e41356976309cad5ea5
<|skeleton|> class GroupManagementTestCase: def test_new_group_success_1(self, data): """新建分组,成功""" <|body_0|> def test_new_group_failed_1(self, data): """新建分组名称为空失败""" <|body_1|> def test_new_group_failed_2(self, data): """新建分组异常失败""" <|body_2|> <|end_ske...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GroupManagementTestCase: def test_new_group_success_1(self, data): """新建分组,成功""" group_management_page = GroupManagementPage(self.driver) group_management_page.new_group(data['groupName'], data['groupInfo'], data['groupType'], data['participants']) group_management_page.filter_...
the_stack_v2_python_sparse
testcase/test_groupManagement.py
zhanghaoyu1990/UItestframework
train
0
0d054061e0bc001ff209e6613991f2bea01f5828
[ "self.img_folder = img_folder\nself.opts = opts\nself.file_names = get_images(img_folder)", "p = np.random.RandomState(seed=self.opts.seeds).permutation(len(self.file_names))\ndata = np.asarray(self.file_names)[p]\ncutoff = np.int(len(data) * self.opts.split)\ntrain_x, test_x = (data[:cutoff], data[cutoff:])\nret...
<|body_start_0|> self.img_folder = img_folder self.opts = opts self.file_names = get_images(img_folder) <|end_body_0|> <|body_start_1|> p = np.random.RandomState(seed=self.opts.seeds).permutation(len(self.file_names)) data = np.asarray(self.file_names)[p] cutoff = np.int...
Dataloader class used to load in data in an image folder. Made it so that it performs a fixed set of transformations to a pair of images in different folders
read_data
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class read_data: """Dataloader class used to load in data in an image folder. Made it so that it performs a fixed set of transformations to a pair of images in different folders""" def __init__(self, opts, img_folder): """:param opts: :param img_folder: :param attribute_file:""" <|...
stack_v2_sparse_classes_75kplus_train_001326
6,456
no_license
[ { "docstring": ":param opts: :param img_folder: :param attribute_file:", "name": "__init__", "signature": "def __init__(self, opts, img_folder)" }, { "docstring": "Given the data that's loaded above, returns a data that's been split into training and test set. :param split: what % of the data sh...
2
stack_v2_sparse_classes_30k_train_020346
Implement the Python class `read_data` described below. Class description: Dataloader class used to load in data in an image folder. Made it so that it performs a fixed set of transformations to a pair of images in different folders Method signatures and docstrings: - def __init__(self, opts, img_folder): :param opts...
Implement the Python class `read_data` described below. Class description: Dataloader class used to load in data in an image folder. Made it so that it performs a fixed set of transformations to a pair of images in different folders Method signatures and docstrings: - def __init__(self, opts, img_folder): :param opts...
112bb366dd7e65a75e8a415f7b31aff1704971df
<|skeleton|> class read_data: """Dataloader class used to load in data in an image folder. Made it so that it performs a fixed set of transformations to a pair of images in different folders""" def __init__(self, opts, img_folder): """:param opts: :param img_folder: :param attribute_file:""" <|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class read_data: """Dataloader class used to load in data in an image folder. Made it so that it performs a fixed set of transformations to a pair of images in different folders""" def __init__(self, opts, img_folder): """:param opts: :param img_folder: :param attribute_file:""" self.img_folder...
the_stack_v2_python_sparse
LearningVisualFeaturesfromLargeWeaklySupervisedData/data_loader.py
yk287/ML
train
1
ed57a0ef12a0e866de976591c31c274bee240d23
[ "if event_name in self.callbacks:\n for callback in self.callbacks[event_name]:\n if args:\n callback(args)\n else:\n callback()", "print('Add: ', event_name)\ntry:\n if self.callbacks[event_name]:\n self.callbacks[event_name].append(callback)\nexcept KeyError:\n ...
<|body_start_0|> if event_name in self.callbacks: for callback in self.callbacks[event_name]: if args: callback(args) else: callback() <|end_body_0|> <|body_start_1|> print('Add: ', event_name) try: ...
Interface for event handlers in the game. Can emit events and attach listeners
EventHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventHandler: """Interface for event handlers in the game. Can emit events and attach listeners""" def trigger(self, event_name, args=None): """Trigger an event.""" <|body_0|> def on(self, event_name, callback): """Attaches a listener for a specific event to the ...
stack_v2_sparse_classes_75kplus_train_001327
947
no_license
[ { "docstring": "Trigger an event.", "name": "trigger", "signature": "def trigger(self, event_name, args=None)" }, { "docstring": "Attaches a listener for a specific event to the object, and passes a callback to be executed when the event is triggered", "name": "on", "signature": "def on(...
2
null
Implement the Python class `EventHandler` described below. Class description: Interface for event handlers in the game. Can emit events and attach listeners Method signatures and docstrings: - def trigger(self, event_name, args=None): Trigger an event. - def on(self, event_name, callback): Attaches a listener for a s...
Implement the Python class `EventHandler` described below. Class description: Interface for event handlers in the game. Can emit events and attach listeners Method signatures and docstrings: - def trigger(self, event_name, args=None): Trigger an event. - def on(self, event_name, callback): Attaches a listener for a s...
03469910d845d024c6159bc7d119a05ef4e684fe
<|skeleton|> class EventHandler: """Interface for event handlers in the game. Can emit events and attach listeners""" def trigger(self, event_name, args=None): """Trigger an event.""" <|body_0|> def on(self, event_name, callback): """Attaches a listener for a specific event to the ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EventHandler: """Interface for event handlers in the game. Can emit events and attach listeners""" def trigger(self, event_name, args=None): """Trigger an event.""" if event_name in self.callbacks: for callback in self.callbacks[event_name]: if args: ...
the_stack_v2_python_sparse
dq-game/src/events/event_handler.py
sebastianfdez/dq-stack
train
1
b0a668ef3a2e668dce4e85bae1949851c6810a97
[ "exp_t1 = T1(physical_qubits=physical_qubits, delays=delays_t1, backend=backend)\nexp_options = {'delays_t1': delays_t1, 'delays_t2': delays_t2}\nif t2type == 'ramsey':\n exp_t2 = T2Ramsey(physical_qubits=physical_qubits, delays=delays_t2, backend=backend, osc_freq=osc_freq)\n exp_options['osc_freq'] = osc_fr...
<|body_start_0|> exp_t1 = T1(physical_qubits=physical_qubits, delays=delays_t1, backend=backend) exp_options = {'delays_t1': delays_t1, 'delays_t2': delays_t2} if t2type == 'ramsey': exp_t2 = T2Ramsey(physical_qubits=physical_qubits, delays=delays_t2, backend=backend, osc_freq=osc_fr...
An experiment to measure the qubit dephasing rate in the :math:`x - y` plane. # section: overview :math:`T_\\varphi`, or :math:`1/\\Gamma_\\varphi`, is the pure dephasing time in the :math:`x - y` plane of the Bloch sphere. We compute :math:`\\Gamma_\\varphi` by computing :math:`\\Gamma_2`, the transverse relaxation ra...
Tphi
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tphi: """An experiment to measure the qubit dephasing rate in the :math:`x - y` plane. # section: overview :math:`T_\\varphi`, or :math:`1/\\Gamma_\\varphi`, is the pure dephasing time in the :math:`x - y` plane of the Bloch sphere. We compute :math:`\\Gamma_\\varphi` by computing :math:`\\Gamma_...
stack_v2_sparse_classes_75kplus_train_001328
5,633
permissive
[ { "docstring": "Initialize the experiment object. Args: physical_qubits: A single-element sequence containing the qubit under test. t2type: What type of T2/T2* experiment to use. Can be either \"ramsey\" for :class:`.T2Ramsey` to be used, or \"hahn\" for :class:`.T2Hahn`. Defaults to \"hahn\". delays_t1: Delay ...
2
stack_v2_sparse_classes_30k_train_052714
Implement the Python class `Tphi` described below. Class description: An experiment to measure the qubit dephasing rate in the :math:`x - y` plane. # section: overview :math:`T_\\varphi`, or :math:`1/\\Gamma_\\varphi`, is the pure dephasing time in the :math:`x - y` plane of the Bloch sphere. We compute :math:`\\Gamma...
Implement the Python class `Tphi` described below. Class description: An experiment to measure the qubit dephasing rate in the :math:`x - y` plane. # section: overview :math:`T_\\varphi`, or :math:`1/\\Gamma_\\varphi`, is the pure dephasing time in the :math:`x - y` plane of the Bloch sphere. We compute :math:`\\Gamma...
a387675a3fe817cef05b968bbf3e05799a09aaae
<|skeleton|> class Tphi: """An experiment to measure the qubit dephasing rate in the :math:`x - y` plane. # section: overview :math:`T_\\varphi`, or :math:`1/\\Gamma_\\varphi`, is the pure dephasing time in the :math:`x - y` plane of the Bloch sphere. We compute :math:`\\Gamma_\\varphi` by computing :math:`\\Gamma_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Tphi: """An experiment to measure the qubit dephasing rate in the :math:`x - y` plane. # section: overview :math:`T_\\varphi`, or :math:`1/\\Gamma_\\varphi`, is the pure dephasing time in the :math:`x - y` plane of the Bloch sphere. We compute :math:`\\Gamma_\\varphi` by computing :math:`\\Gamma_2`, the trans...
the_stack_v2_python_sparse
qiskit_experiments/library/characterization/tphi.py
oliverdial/qiskit-experiments
train
0
e0c5688cbcaa72ef583ce4d6c15278546e7a7a4f
[ "if script_arguments is None:\n script_arguments = list()\nif dependent_pipelines is None and dependent_pipelines_ok_to_fail is None:\n raise ValueError('Must have some dependencies for dependency step')\nprefix_func = lambda p: p if not NAME_PREFIX else NAME_PREFIX + '_' + p\nargument_func = lambda x: [prefi...
<|body_start_0|> if script_arguments is None: script_arguments = list() if dependent_pipelines is None and dependent_pipelines_ok_to_fail is None: raise ValueError('Must have some dependencies for dependency step') prefix_func = lambda p: p if not NAME_PREFIX else NAME_PR...
PipelineDependencies Step class that helps wait for other pipelines to finish
PipelineDependenciesStep
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PipelineDependenciesStep: """PipelineDependencies Step class that helps wait for other pipelines to finish""" def __init__(self, id, pipeline_name, dependent_pipelines=None, dependent_pipelines_ok_to_fail=None, refresh_rate=300, start_date=None, script_arguments=None, **kwargs): """C...
stack_v2_sparse_classes_75kplus_train_001329
3,500
permissive
[ { "docstring": "Constructor for the QATransformStep class Args: sns_arn(str): sns topic arn for QA steps script_arguments(list of str): list of arguments to the script **kwargs(optional): Keyword arguments directly passed to base class", "name": "__init__", "signature": "def __init__(self, id, pipeline_...
2
stack_v2_sparse_classes_30k_val_002432
Implement the Python class `PipelineDependenciesStep` described below. Class description: PipelineDependencies Step class that helps wait for other pipelines to finish Method signatures and docstrings: - def __init__(self, id, pipeline_name, dependent_pipelines=None, dependent_pipelines_ok_to_fail=None, refresh_rate=...
Implement the Python class `PipelineDependenciesStep` described below. Class description: PipelineDependencies Step class that helps wait for other pipelines to finish Method signatures and docstrings: - def __init__(self, id, pipeline_name, dependent_pipelines=None, dependent_pipelines_ok_to_fail=None, refresh_rate=...
797cb719e6c2abeda0751ada3339c72bfb19c8f2
<|skeleton|> class PipelineDependenciesStep: """PipelineDependencies Step class that helps wait for other pipelines to finish""" def __init__(self, id, pipeline_name, dependent_pipelines=None, dependent_pipelines_ok_to_fail=None, refresh_rate=300, start_date=None, script_arguments=None, **kwargs): """C...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PipelineDependenciesStep: """PipelineDependencies Step class that helps wait for other pipelines to finish""" def __init__(self, id, pipeline_name, dependent_pipelines=None, dependent_pipelines_ok_to_fail=None, refresh_rate=300, start_date=None, script_arguments=None, **kwargs): """Constructor fo...
the_stack_v2_python_sparse
dataduct/steps/pipeline_dependencies.py
EverFi/dataduct
train
3
d9e65f2deae8aa58a79aa81f6582ca953949d7e2
[ "os.makedirs(os.path.dirname(cls.path_token), exist_ok=True)\nwith open(cls.path_token, 'w+') as f:\n f.write(token)", "try:\n with open(cls.path_token, 'r') as f:\n return f.read()\nexcept FileNotFoundError:\n pass", "try:\n os.remove(cls.path_token)\nexcept FileNotFoundError:\n pass" ]
<|body_start_0|> os.makedirs(os.path.dirname(cls.path_token), exist_ok=True) with open(cls.path_token, 'w+') as f: f.write(token) <|end_body_0|> <|body_start_1|> try: with open(cls.path_token, 'r') as f: return f.read() except FileNotFoundError: ...
HfFolder
[ "LGPL-2.1-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HfFolder: def save_token(cls, token): """Save token, creating folder as needed.""" <|body_0|> def get_token(cls): """Get token or None if not existent.""" <|body_1|> def delete_token(cls): """Delete token. Do not fail if token does not exist.""" ...
stack_v2_sparse_classes_75kplus_train_001330
5,878
permissive
[ { "docstring": "Save token, creating folder as needed.", "name": "save_token", "signature": "def save_token(cls, token)" }, { "docstring": "Get token or None if not existent.", "name": "get_token", "signature": "def get_token(cls)" }, { "docstring": "Delete token. Do not fail if ...
3
stack_v2_sparse_classes_30k_train_010372
Implement the Python class `HfFolder` described below. Class description: Implement the HfFolder class. Method signatures and docstrings: - def save_token(cls, token): Save token, creating folder as needed. - def get_token(cls): Get token or None if not existent. - def delete_token(cls): Delete token. Do not fail if ...
Implement the Python class `HfFolder` described below. Class description: Implement the HfFolder class. Method signatures and docstrings: - def save_token(cls, token): Save token, creating folder as needed. - def get_token(cls): Get token or None if not existent. - def delete_token(cls): Delete token. Do not fail if ...
b60c741f746877293bb85eed6806736fc8fa0ffd
<|skeleton|> class HfFolder: def save_token(cls, token): """Save token, creating folder as needed.""" <|body_0|> def get_token(cls): """Get token or None if not existent.""" <|body_1|> def delete_token(cls): """Delete token. Do not fail if token does not exist.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HfFolder: def save_token(cls, token): """Save token, creating folder as needed.""" os.makedirs(os.path.dirname(cls.path_token), exist_ok=True) with open(cls.path_token, 'w+') as f: f.write(token) def get_token(cls): """Get token or None if not existent.""" ...
the_stack_v2_python_sparse
xtune/src/transformers/hf_api.py
microsoft/unilm
train
15,313
4d049e638b60c678137b6a7d85543dce34a9d82f
[ "super().__init__(value, msg_id, msg_args)\nself._keys = kwargs.get('keys', ())\nself._msg_args.update({'keys': self._keys})", "if self._value is None or not self._keys:\n return\nif not isinstance(self._value, dict):\n raise TypeError(lang.t('pytsite.validation@dict_expected', {'got': self.value.__class__....
<|body_start_0|> super().__init__(value, msg_id, msg_args) self._keys = kwargs.get('keys', ()) self._msg_args.update({'keys': self._keys}) <|end_body_0|> <|body_start_1|> if self._value is None or not self._keys: return if not isinstance(self._value, dict): ...
Check if a dict particular keys' values are not empty.
DictPartsNonEmpty
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DictPartsNonEmpty: """Check if a dict particular keys' values are not empty.""" def __init__(self, value=None, msg_id: str=None, msg_args: dict=None, **kwargs): """Init.""" <|body_0|> def _do_validate(self): """Do actual validation of the rule.""" <|body_...
stack_v2_sparse_classes_75kplus_train_001331
15,784
permissive
[ { "docstring": "Init.", "name": "__init__", "signature": "def __init__(self, value=None, msg_id: str=None, msg_args: dict=None, **kwargs)" }, { "docstring": "Do actual validation of the rule.", "name": "_do_validate", "signature": "def _do_validate(self)" } ]
2
null
Implement the Python class `DictPartsNonEmpty` described below. Class description: Check if a dict particular keys' values are not empty. Method signatures and docstrings: - def __init__(self, value=None, msg_id: str=None, msg_args: dict=None, **kwargs): Init. - def _do_validate(self): Do actual validation of the rul...
Implement the Python class `DictPartsNonEmpty` described below. Class description: Check if a dict particular keys' values are not empty. Method signatures and docstrings: - def __init__(self, value=None, msg_id: str=None, msg_args: dict=None, **kwargs): Init. - def _do_validate(self): Do actual validation of the rul...
e4896722709607bda88b4a69400dcde4bf7e5f0a
<|skeleton|> class DictPartsNonEmpty: """Check if a dict particular keys' values are not empty.""" def __init__(self, value=None, msg_id: str=None, msg_args: dict=None, **kwargs): """Init.""" <|body_0|> def _do_validate(self): """Do actual validation of the rule.""" <|body_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DictPartsNonEmpty: """Check if a dict particular keys' values are not empty.""" def __init__(self, value=None, msg_id: str=None, msg_args: dict=None, **kwargs): """Init.""" super().__init__(value, msg_id, msg_args) self._keys = kwargs.get('keys', ()) self._msg_args.update(...
the_stack_v2_python_sparse
pytsite/validation/_rule.py
pytsite/pytsite
train
12
f7a9655c9fa4e3f485dd2dc898fcb34c7f503fa6
[ "def max(a, b):\n if a > b:\n return a\n return b\nif len(nums) == 0:\n return 0\nif len(nums) == 1:\n return nums[0]\nif len(nums) == 2:\n return max(nums[0], nums[1])\n\ndef my_rob(nums):\n cur, pre = (0, 0)\n for num in nums:\n cur, pre = (max(pre + num, cur), cur)\n return ...
<|body_start_0|> def max(a, b): if a > b: return a return b if len(nums) == 0: return 0 if len(nums) == 1: return nums[0] if len(nums) == 2: return max(nums[0], nums[1]) def my_rob(nums): cur...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rob(self, nums: List[int]) -> int: """213. 打家劫舍 II 执行用时: 32 ms , 在所有 Python3 提交中击败了 95.86% 的用户 内存消耗: 14.8 MB , 在所有 Python3 提交中击败了 75.00% 的用 :param nums: :return:""" <|body_0|> def rob5(self, nums: List[int]) -> int: """213. 打家劫舍 II 执行用时: 40 ms , 在所有 Pyt...
stack_v2_sparse_classes_75kplus_train_001332
3,370
no_license
[ { "docstring": "213. 打家劫舍 II 执行用时: 32 ms , 在所有 Python3 提交中击败了 95.86% 的用户 内存消耗: 14.8 MB , 在所有 Python3 提交中击败了 75.00% 的用 :param nums: :return:", "name": "rob", "signature": "def rob(self, nums: List[int]) -> int" }, { "docstring": "213. 打家劫舍 II 执行用时: 40 ms , 在所有 Python3 提交中击败了 60.10% 的用户 内存消耗: 15 M...
4
stack_v2_sparse_classes_30k_train_021144
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums: List[int]) -> int: 213. 打家劫舍 II 执行用时: 32 ms , 在所有 Python3 提交中击败了 95.86% 的用户 内存消耗: 14.8 MB , 在所有 Python3 提交中击败了 75.00% 的用 :param nums: :return: - def rob5(self...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums: List[int]) -> int: 213. 打家劫舍 II 执行用时: 32 ms , 在所有 Python3 提交中击败了 95.86% 的用户 内存消耗: 14.8 MB , 在所有 Python3 提交中击败了 75.00% 的用 :param nums: :return: - def rob5(self...
d613ed8a5a2c15ace7d513965b372d128845d66a
<|skeleton|> class Solution: def rob(self, nums: List[int]) -> int: """213. 打家劫舍 II 执行用时: 32 ms , 在所有 Python3 提交中击败了 95.86% 的用户 内存消耗: 14.8 MB , 在所有 Python3 提交中击败了 75.00% 的用 :param nums: :return:""" <|body_0|> def rob5(self, nums: List[int]) -> int: """213. 打家劫舍 II 执行用时: 40 ms , 在所有 Pyt...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def rob(self, nums: List[int]) -> int: """213. 打家劫舍 II 执行用时: 32 ms , 在所有 Python3 提交中击败了 95.86% 的用户 内存消耗: 14.8 MB , 在所有 Python3 提交中击败了 75.00% 的用 :param nums: :return:""" def max(a, b): if a > b: return a return b if len(nums) == 0: ...
the_stack_v2_python_sparse
array/rob.py
nomboy/leetcode
train
0
fb371baef65fb4d5662b7e63cab466944ce84474
[ "search_fields = request.GET.getlist('search_fields', [])\nsearch_values = request.GET.getlist('search', [])\nif len(search_fields) != len(search_values):\n raise GlobalErrorMessage400('search_fields 와 search 가 mapping 이 되지 않습니다. 확인해주세요')\nfilter_dictionary = {'profile': self.request.user.pk}\ndetail_value = 'if...
<|body_start_0|> search_fields = request.GET.getlist('search_fields', []) search_values = request.GET.getlist('search', []) if len(search_fields) != len(search_values): raise GlobalErrorMessage400('search_fields 와 search 가 mapping 이 되지 않습니다. 확인해주세요') filter_dictionary = {'pro...
PostView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PostView: def get(self, request): """get 에서 http://{{ip}}:{{port}}/record/posts/?search_fields=created_at&search=2020-08-16 위와 같이, search_fields 와 search 를 사용을 하여, Post.objects.all().filter(**filter_dictionary) 와 같이 필터링 가능할수 있도록 구현을 하였습니다. detail 일 경우에는 포함을 하는 경우가 있으면, 그 POST 를 찾아서 돌려 줍니...
stack_v2_sparse_classes_75kplus_train_001333
9,797
no_license
[ { "docstring": "get 에서 http://{{ip}}:{{port}}/record/posts/?search_fields=created_at&search=2020-08-16 위와 같이, search_fields 와 search 를 사용을 하여, Post.objects.all().filter(**filter_dictionary) 와 같이 필터링 가능할수 있도록 구현을 하였습니다. detail 일 경우에는 포함을 하는 경우가 있으면, 그 POST 를 찾아서 돌려 줍니다.", "name": "get", "signature": "def...
2
null
Implement the Python class `PostView` described below. Class description: Implement the PostView class. Method signatures and docstrings: - def get(self, request): get 에서 http://{{ip}}:{{port}}/record/posts/?search_fields=created_at&search=2020-08-16 위와 같이, search_fields 와 search 를 사용을 하여, Post.objects.all().filter(*...
Implement the Python class `PostView` described below. Class description: Implement the PostView class. Method signatures and docstrings: - def get(self, request): get 에서 http://{{ip}}:{{port}}/record/posts/?search_fields=created_at&search=2020-08-16 위와 같이, search_fields 와 search 를 사용을 하여, Post.objects.all().filter(*...
db1b012c586b2e3bcc6e7a23e9518e7f333ea30b
<|skeleton|> class PostView: def get(self, request): """get 에서 http://{{ip}}:{{port}}/record/posts/?search_fields=created_at&search=2020-08-16 위와 같이, search_fields 와 search 를 사용을 하여, Post.objects.all().filter(**filter_dictionary) 와 같이 필터링 가능할수 있도록 구현을 하였습니다. detail 일 경우에는 포함을 하는 경우가 있으면, 그 POST 를 찾아서 돌려 줍니...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PostView: def get(self, request): """get 에서 http://{{ip}}:{{port}}/record/posts/?search_fields=created_at&search=2020-08-16 위와 같이, search_fields 와 search 를 사용을 하여, Post.objects.all().filter(**filter_dictionary) 와 같이 필터링 가능할수 있도록 구현을 하였습니다. detail 일 경우에는 포함을 하는 경우가 있으면, 그 POST 를 찾아서 돌려 줍니다.""" ...
the_stack_v2_python_sparse
project/record/API/post.py
shunnyjang/Prography-Dahaeng-Backend
train
0
aaff995ffa4966888ef6a26f9bd5a84e65e7fd97
[ "super().__init__(event)\nself.user = IDNamePair(event['user_id'], event['user_name'])\nself.channel = IDNamePair(event['channel_id'], event['channel_name'])\nself.team = IDNamePair(event['team_id'], event['team_domain'])\nself.trigger_id = event['trigger_id']\nself.command = event['command']\nself.text = event['te...
<|body_start_0|> super().__init__(event) self.user = IDNamePair(event['user_id'], event['user_name']) self.channel = IDNamePair(event['channel_id'], event['channel_name']) self.team = IDNamePair(event['team_id'], event['team_domain']) self.trigger_id = event['trigger_id'] ...
SlashCommandInteractiveEvent
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SlashCommandInteractiveEvent: def __init__(self, event: dict): """Convenience class to parse a slash command payload from the events API Args: event: the raw event dictionary""" <|body_0|> def create_reply(message, ephemeral=False) -> dict: """Create a reply suitable...
stack_v2_sparse_classes_75kplus_train_001334
4,539
permissive
[ { "docstring": "Convenience class to parse a slash command payload from the events API Args: event: the raw event dictionary", "name": "__init__", "signature": "def __init__(self, event: dict)" }, { "docstring": "Create a reply suitable to send directly back to the invoking HTTP request Args: me...
2
stack_v2_sparse_classes_30k_train_037278
Implement the Python class `SlashCommandInteractiveEvent` described below. Class description: Implement the SlashCommandInteractiveEvent class. Method signatures and docstrings: - def __init__(self, event: dict): Convenience class to parse a slash command payload from the events API Args: event: the raw event diction...
Implement the Python class `SlashCommandInteractiveEvent` described below. Class description: Implement the SlashCommandInteractiveEvent class. Method signatures and docstrings: - def __init__(self, event: dict): Convenience class to parse a slash command payload from the events API Args: event: the raw event diction...
4b026da33695b25033c7667679f3cf552c4bf3b5
<|skeleton|> class SlashCommandInteractiveEvent: def __init__(self, event: dict): """Convenience class to parse a slash command payload from the events API Args: event: the raw event dictionary""" <|body_0|> def create_reply(message, ephemeral=False) -> dict: """Create a reply suitable...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SlashCommandInteractiveEvent: def __init__(self, event: dict): """Convenience class to parse a slash command payload from the events API Args: event: the raw event dictionary""" super().__init__(event) self.user = IDNamePair(event['user_id'], event['user_name']) self.channel = ...
the_stack_v2_python_sparse
terraform/stacks/bot/lambdas/python/slack_automation_bot/slack/web/classes/interactions.py
cloud-sniper/cloud-sniper
train
184
41121f7a154c23362f9aaebf068ceea38c149db4
[ "query = TitleQuery(title, **kwargs)\n\n@self.synchronize(wait=query.wait)\ndef assert_title():\n if not query.resolves_for(self):\n raise ExpectationNotMet(query.failure_message)\n return True\nreturn assert_title()", "query = TitleQuery(title, **kwargs)\n\n@self.synchronize(wait=query.wait)\ndef as...
<|body_start_0|> query = TitleQuery(title, **kwargs) @self.synchronize(wait=query.wait) def assert_title(): if not query.resolves_for(self): raise ExpectationNotMet(query.failure_message) return True return assert_title() <|end_body_0|> <|body_st...
DocumentMatchersMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DocumentMatchersMixin: def assert_title(self, title, **kwargs): """Asserts that the page has the given title. Args: title (str | RegexObject): The string or regex that the title should match. **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`. Returns: True Raises: Expectation...
stack_v2_sparse_classes_75kplus_train_001335
2,594
permissive
[ { "docstring": "Asserts that the page has the given title. Args: title (str | RegexObject): The string or regex that the title should match. **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`. Returns: True Raises: ExpectationNotMet: If the assertion hasn't succeeded during the wait time.", "name...
4
stack_v2_sparse_classes_30k_train_004150
Implement the Python class `DocumentMatchersMixin` described below. Class description: Implement the DocumentMatchersMixin class. Method signatures and docstrings: - def assert_title(self, title, **kwargs): Asserts that the page has the given title. Args: title (str | RegexObject): The string or regex that the title ...
Implement the Python class `DocumentMatchersMixin` described below. Class description: Implement the DocumentMatchersMixin class. Method signatures and docstrings: - def assert_title(self, title, **kwargs): Asserts that the page has the given title. Args: title (str | RegexObject): The string or regex that the title ...
eafd9ac50d02e8b57ef90d767493c8fa2be0739a
<|skeleton|> class DocumentMatchersMixin: def assert_title(self, title, **kwargs): """Asserts that the page has the given title. Args: title (str | RegexObject): The string or regex that the title should match. **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`. Returns: True Raises: Expectation...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DocumentMatchersMixin: def assert_title(self, title, **kwargs): """Asserts that the page has the given title. Args: title (str | RegexObject): The string or regex that the title should match. **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`. Returns: True Raises: ExpectationNotMet: If the...
the_stack_v2_python_sparse
capybara/node/document_matchers.py
elliterate/capybara.py
train
63
79a4bbb562a1bd284c9fd53f124f57ffa0841d93
[ "yaml_this = yamlr.YAML()\nyaml_this.register_class(StandardYAMLTag)\nloaded = yaml_this.load(text_has_anchors_tags)\ncleaned = yaml_clean(loaded)\nself.assertEqual(cleaned, {'greeting': 'hello mary'})", "loaded = yaml.load(text_has_anchors_tags, Loader=yaml.Loader)\ncleaned = yaml_clean(loaded)\nself.assertEqual...
<|body_start_0|> yaml_this = yamlr.YAML() yaml_this.register_class(StandardYAMLTag) loaded = yaml_this.load(text_has_anchors_tags) cleaned = yaml_clean(loaded) self.assertEqual(cleaned, {'greeting': 'hello mary'}) <|end_body_0|> <|body_start_1|> loaded = yaml.load(text_h...
These test cases handle conversion between YAML and dictionaries instead of class objects.
YAMLTalk
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class YAMLTalk: """These test cases handle conversion between YAML and dictionaries instead of class objects.""" def test_standard_ruamel(self): """Standard yaml_tag method for ruamel.""" <|body_0|> def test_standard_pyyaml(self): """Standard yaml_tag method for pyyaml...
stack_v2_sparse_classes_75kplus_train_001336
7,417
permissive
[ { "docstring": "Standard yaml_tag method for ruamel.", "name": "test_standard_ruamel", "signature": "def test_standard_ruamel(self)" }, { "docstring": "Standard yaml_tag method for pyyaml.", "name": "test_standard_pyyaml", "signature": "def test_standard_pyyaml(self)" } ]
2
stack_v2_sparse_classes_30k_train_025962
Implement the Python class `YAMLTalk` described below. Class description: These test cases handle conversion between YAML and dictionaries instead of class objects. Method signatures and docstrings: - def test_standard_ruamel(self): Standard yaml_tag method for ruamel. - def test_standard_pyyaml(self): Standard yaml_...
Implement the Python class `YAMLTalk` described below. Class description: These test cases handle conversion between YAML and dictionaries instead of class objects. Method signatures and docstrings: - def test_standard_ruamel(self): Standard yaml_tag method for ruamel. - def test_standard_pyyaml(self): Standard yaml_...
f671b4d75fd45e5cd8deb16395081c0731551b0a
<|skeleton|> class YAMLTalk: """These test cases handle conversion between YAML and dictionaries instead of class objects.""" def test_standard_ruamel(self): """Standard yaml_tag method for ruamel.""" <|body_0|> def test_standard_pyyaml(self): """Standard yaml_tag method for pyyaml...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class YAMLTalk: """These test cases handle conversion between YAML and dictionaries instead of class objects.""" def test_standard_ruamel(self): """Standard yaml_tag method for ruamel.""" yaml_this = yamlr.YAML() yaml_this.register_class(StandardYAMLTag) loaded = yaml_this.load(...
the_stack_v2_python_sparse
ortho/test_yaml.py
bradleyrp/ortho
train
0
e0977fc86d832332beadc5d949f5e66b4b981364
[ "if not root:\n return '[]'\nqueue = [root]\nans = []\nwhile queue:\n tmp = queue.pop(0)\n if tmp is None:\n ans.append('null')\n else:\n ans.append(str(tmp.val))\n queue.append(tmp.left)\n queue.append(tmp.right)\nreturn '[' + ','.join(ans) + ']'", "if data == '[]':\n r...
<|body_start_0|> if not root: return '[]' queue = [root] ans = [] while queue: tmp = queue.pop(0) if tmp is None: ans.append('null') else: ans.append(str(tmp.val)) queue.append(tmp.left) ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_75kplus_train_001337
3,154
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
2a370ddfbf3200f6922429e65b60e6cbb74705a0
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return '[]' queue = [root] ans = [] while queue: tmp = queue.pop(0) if tmp is None: ans.append('n...
the_stack_v2_python_sparse
297.二叉树的序列化与反序列化.py
liuchangling/leetcode
train
0
0cf74fe152a4cf94f4f22190dd45c879a96611e3
[ "if isinstance(start_date, str):\n start_date = parser.parse(start_date).date()\nif isinstance(end_date, str):\n end_date = parser.parse(end_date).date()\ncluster_id = get_cluster_id_from_provider(openshift_provider_uuid)\nwith OCPReportDBAccessor(self._schema) as accessor:\n report_period = accessor.repor...
<|body_start_0|> if isinstance(start_date, str): start_date = parser.parse(start_date).date() if isinstance(end_date, str): end_date = parser.parse(end_date).date() cluster_id = get_cluster_id_from_provider(openshift_provider_uuid) with OCPReportDBAccessor(self._s...
Class to update OCP report summary data.
OCPCloudParquetReportSummaryUpdater
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OCPCloudParquetReportSummaryUpdater: """Class to update OCP report summary data.""" def update_aws_summary_tables(self, openshift_provider_uuid, aws_provider_uuid, start_date, end_date): """Update operations specifically for OpenShift on AWS.""" <|body_0|> def update_azu...
stack_v2_sparse_classes_75kplus_train_001338
7,056
permissive
[ { "docstring": "Update operations specifically for OpenShift on AWS.", "name": "update_aws_summary_tables", "signature": "def update_aws_summary_tables(self, openshift_provider_uuid, aws_provider_uuid, start_date, end_date)" }, { "docstring": "Update operations specifically for OpenShift on Azur...
2
stack_v2_sparse_classes_30k_train_039276
Implement the Python class `OCPCloudParquetReportSummaryUpdater` described below. Class description: Class to update OCP report summary data. Method signatures and docstrings: - def update_aws_summary_tables(self, openshift_provider_uuid, aws_provider_uuid, start_date, end_date): Update operations specifically for Op...
Implement the Python class `OCPCloudParquetReportSummaryUpdater` described below. Class description: Class to update OCP report summary data. Method signatures and docstrings: - def update_aws_summary_tables(self, openshift_provider_uuid, aws_provider_uuid, start_date, end_date): Update operations specifically for Op...
88e2d679148d0e4735c5018faada638f73d4dc5c
<|skeleton|> class OCPCloudParquetReportSummaryUpdater: """Class to update OCP report summary data.""" def update_aws_summary_tables(self, openshift_provider_uuid, aws_provider_uuid, start_date, end_date): """Update operations specifically for OpenShift on AWS.""" <|body_0|> def update_azu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OCPCloudParquetReportSummaryUpdater: """Class to update OCP report summary data.""" def update_aws_summary_tables(self, openshift_provider_uuid, aws_provider_uuid, start_date, end_date): """Update operations specifically for OpenShift on AWS.""" if isinstance(start_date, str): ...
the_stack_v2_python_sparse
koku/masu/processor/ocp/ocp_cloud_parquet_summary_updater.py
pavanyadavalli/koku
train
2
62f05792f20bf5cff9761ca23035483296156426
[ "for image_url in item['image_urls']:\n image_url = 'http:' + image_url\n yield scrapy.Request(image_url)", "image_paths = [x['path'] for ok, x in results if ok]\nif not image_paths:\n raise DropItem('Item contains no images')\nreturn item" ]
<|body_start_0|> for image_url in item['image_urls']: image_url = 'http:' + image_url yield scrapy.Request(image_url) <|end_body_0|> <|body_start_1|> image_paths = [x['path'] for ok, x in results if ok] if not image_paths: raise DropItem('Item contains no ima...
JiandanPipeline
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JiandanPipeline: def get_media_requests(self, item, info): """:param item: :param info: :return: 在工作流程中可以看到, 管道会得到文件的URL并从项目中下载。 为了这么做,你需要重写 get_media_requests() 方法, 并对各个图片URL返回一个Request:""" <|body_0|> def item_completed(self, results, item, info): """:param results:...
stack_v2_sparse_classes_75kplus_train_001339
2,344
permissive
[ { "docstring": ":param item: :param info: :return: 在工作流程中可以看到, 管道会得到文件的URL并从项目中下载。 为了这么做,你需要重写 get_media_requests() 方法, 并对各个图片URL返回一个Request:", "name": "get_media_requests", "signature": "def get_media_requests(self, item, info)" }, { "docstring": ":param results: :param item: :param info: :retu...
2
stack_v2_sparse_classes_30k_train_053640
Implement the Python class `JiandanPipeline` described below. Class description: Implement the JiandanPipeline class. Method signatures and docstrings: - def get_media_requests(self, item, info): :param item: :param info: :return: 在工作流程中可以看到, 管道会得到文件的URL并从项目中下载。 为了这么做,你需要重写 get_media_requests() 方法, 并对各个图片URL返回一个Reque...
Implement the Python class `JiandanPipeline` described below. Class description: Implement the JiandanPipeline class. Method signatures and docstrings: - def get_media_requests(self, item, info): :param item: :param info: :return: 在工作流程中可以看到, 管道会得到文件的URL并从项目中下载。 为了这么做,你需要重写 get_media_requests() 方法, 并对各个图片URL返回一个Reque...
8933c7a6d444d3d86a173984e6cf4c08dbf84039
<|skeleton|> class JiandanPipeline: def get_media_requests(self, item, info): """:param item: :param info: :return: 在工作流程中可以看到, 管道会得到文件的URL并从项目中下载。 为了这么做,你需要重写 get_media_requests() 方法, 并对各个图片URL返回一个Request:""" <|body_0|> def item_completed(self, results, item, info): """:param results:...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class JiandanPipeline: def get_media_requests(self, item, info): """:param item: :param info: :return: 在工作流程中可以看到, 管道会得到文件的URL并从项目中下载。 为了这么做,你需要重写 get_media_requests() 方法, 并对各个图片URL返回一个Request:""" for image_url in item['image_urls']: image_url = 'http:' + image_url yield scra...
the_stack_v2_python_sparse
jiandan/jiandan/pipelines.py
MisterZhouZhou/pythonLearn
train
1
e527c2db8b182bbe208f446d07b5c47c1dd77d08
[ "self.__screen = screen\nself.__msg = INSTALLATION_COMPLETED.localize() + REBOOT_MSG.localize()\nself.__buttonsBar = ButtonBar(self.__screen, [(REBOOT.localize(), 'reboot')])\nself.__grid = GridForm(self.__screen, IBM_ZKVM.localize() % STR_VERSION, 1, 2)\nself.__grid.add(self.__buttonsBar, 0, 1, (0, 1, 0, 0))", "...
<|body_start_0|> self.__screen = screen self.__msg = INSTALLATION_COMPLETED.localize() + REBOOT_MSG.localize() self.__buttonsBar = ButtonBar(self.__screen, [(REBOOT.localize(), 'reboot')]) self.__grid = GridForm(self.__screen, IBM_ZKVM.localize() % STR_VERSION, 1, 2) self.__grid....
Last screen for the installer application
RebootSystem
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RebootSystem: """Last screen for the installer application""" def __init__(self, screen): """Constructor @type screen: SnackScreen @param screen: SnackScreen instance""" <|body_0|> def run(self, error=False): """Draws the screen @type error: boolean @param error:...
stack_v2_sparse_classes_75kplus_train_001340
1,427
no_license
[ { "docstring": "Constructor @type screen: SnackScreen @param screen: SnackScreen instance", "name": "__init__", "signature": "def __init__(self, screen)" }, { "docstring": "Draws the screen @type error: boolean @param error: reboot due to error @rtype: integer @returns: sucess status", "name...
2
stack_v2_sparse_classes_30k_train_015200
Implement the Python class `RebootSystem` described below. Class description: Last screen for the installer application Method signatures and docstrings: - def __init__(self, screen): Constructor @type screen: SnackScreen @param screen: SnackScreen instance - def run(self, error=False): Draws the screen @type error: ...
Implement the Python class `RebootSystem` described below. Class description: Last screen for the installer application Method signatures and docstrings: - def __init__(self, screen): Constructor @type screen: SnackScreen @param screen: SnackScreen instance - def run(self, error=False): Draws the screen @type error: ...
1c738fd5e6ee3f8fd4f47acf2207038f20868212
<|skeleton|> class RebootSystem: """Last screen for the installer application""" def __init__(self, screen): """Constructor @type screen: SnackScreen @param screen: SnackScreen instance""" <|body_0|> def run(self, error=False): """Draws the screen @type error: boolean @param error:...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RebootSystem: """Last screen for the installer application""" def __init__(self, screen): """Constructor @type screen: SnackScreen @param screen: SnackScreen instance""" self.__screen = screen self.__msg = INSTALLATION_COMPLETED.localize() + REBOOT_MSG.localize() self.__bu...
the_stack_v2_python_sparse
zfrobisher-installer/src/viewer/newt/rebootsystem.py
fedosu85nce/work
train
2
b5df2e2be24605efcb6fb9e694f233e50889e34b
[ "while len(lists) > 1:\n temp = []\n for i in xrange(0, len(lists), 2):\n if i + 1 < len(lists):\n merged = self.merge2Lists(lists[i], lists[i + 1])\n temp.append(merged)\n if len(lists) % 2 == 1:\n temp.append(lists[-1])\n lists = temp\nreturn lists[0] if len(lists) ...
<|body_start_0|> while len(lists) > 1: temp = [] for i in xrange(0, len(lists), 2): if i + 1 < len(lists): merged = self.merge2Lists(lists[i], lists[i + 1]) temp.append(merged) if len(lists) % 2 == 1: tem...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mergeKLists(self, lists): """:type lists: List[ListNode] :rtype: ListNode""" <|body_0|> def merge2Lists(self, list1, list2): """:type list1: ListNode :type list2: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_001341
1,575
no_license
[ { "docstring": ":type lists: List[ListNode] :rtype: ListNode", "name": "mergeKLists", "signature": "def mergeKLists(self, lists)" }, { "docstring": ":type list1: ListNode :type list2: ListNode :rtype: ListNode", "name": "merge2Lists", "signature": "def merge2Lists(self, list1, list2)" ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode - def merge2Lists(self, list1, list2): :type list1: ListNode :type list2: ListNode :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode - def merge2Lists(self, list1, list2): :type list1: ListNode :type list2: ListNode :rtype: ListNode <|...
5c74114577dbc69c4501d025861e0e5a8f5d2ac6
<|skeleton|> class Solution: def mergeKLists(self, lists): """:type lists: List[ListNode] :rtype: ListNode""" <|body_0|> def merge2Lists(self, list1, list2): """:type list1: ListNode :type list2: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def mergeKLists(self, lists): """:type lists: List[ListNode] :rtype: ListNode""" while len(lists) > 1: temp = [] for i in xrange(0, len(lists), 2): if i + 1 < len(lists): merged = self.merge2Lists(lists[i], lists[i + 1]) ...
the_stack_v2_python_sparse
leetcode/p23.py
linyue2000/review
train
0
79de1495d3e8e3f61410e0289695912e3215c685
[ "self.tree = tree\nself.alignment = alignment\nself.pamlpath = pamlpath\nmodel = 'M1'\nself.defaultmodel = model\nwd = workdir\nself.workdir = wd", "print('Running model %s paml on input.' % str(self.defaultmodel))\ntree = EvolTree(self.tree)\ntree.link_to_alignment(self.alignment)\ntree.workdir = self.workdir\nt...
<|body_start_0|> self.tree = tree self.alignment = alignment self.pamlpath = pamlpath model = 'M1' self.defaultmodel = model wd = workdir self.workdir = wd <|end_body_0|> <|body_start_1|> print('Running model %s paml on input.' % str(self.defaultmodel)) ...
Test codeml with a default tree and newick file.
PamlTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PamlTest: """Test codeml with a default tree and newick file.""" def __init__(self, tree='ECP_EDN_15.nw', alignment='ECP_EDN_15.fasta', workdir='', pamlpath=''): """Test that paml is in your path and working properly. :param tree: (Default value = "ECP_EDN_15.nw") :param alignment: (...
stack_v2_sparse_classes_75kplus_train_001342
1,351
no_license
[ { "docstring": "Test that paml is in your path and working properly. :param tree: (Default value = \"ECP_EDN_15.nw\") :param alignment: (Default value = \"ECP_EDN_15.fasta\") :param workdir: (Default value = \"\") :param pamlpath: (Default value = \"\")", "name": "__init__", "signature": "def __init__(s...
2
stack_v2_sparse_classes_30k_train_036223
Implement the Python class `PamlTest` described below. Class description: Test codeml with a default tree and newick file. Method signatures and docstrings: - def __init__(self, tree='ECP_EDN_15.nw', alignment='ECP_EDN_15.fasta', workdir='', pamlpath=''): Test that paml is in your path and working properly. :param tr...
Implement the Python class `PamlTest` described below. Class description: Test codeml with a default tree and newick file. Method signatures and docstrings: - def __init__(self, tree='ECP_EDN_15.nw', alignment='ECP_EDN_15.fasta', workdir='', pamlpath=''): Test that paml is in your path and working properly. :param tr...
e207046ec36387751fe2bba8b6782fdc2a580107
<|skeleton|> class PamlTest: """Test codeml with a default tree and newick file.""" def __init__(self, tree='ECP_EDN_15.nw', alignment='ECP_EDN_15.fasta', workdir='', pamlpath=''): """Test that paml is in your path and working properly. :param tree: (Default value = "ECP_EDN_15.nw") :param alignment: (...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PamlTest: """Test codeml with a default tree and newick file.""" def __init__(self, tree='ECP_EDN_15.nw', alignment='ECP_EDN_15.fasta', workdir='', pamlpath=''): """Test that paml is in your path and working properly. :param tree: (Default value = "ECP_EDN_15.nw") :param alignment: (Default value...
the_stack_v2_python_sparse
OrthoEvol/Orthologs/Phylogenetics/PAML/ete3paml_test/ete3paml_test.py
datasnakes/OrthoEvolution
train
19
17b375be02c4b176d4265f5dde24ef8ff55cf4ea
[ "parametros_faltantes = ''\nif disquera.nombre is None:\n parametros_faltantes += '<nombre>'\nif disquera.direccion is None:\n parametros_faltantes += '<direccion> '\nif disquera.email is None:\n parametros_faltantes += '<email>'\nif len(parametros_faltantes) > 0:\n mensaje = 'Los siguientes parametros ...
<|body_start_0|> parametros_faltantes = '' if disquera.nombre is None: parametros_faltantes += '<nombre>' if disquera.direccion is None: parametros_faltantes += '<direccion> ' if disquera.email is None: parametros_faltantes += '<email>' if len(...
ValidacionDisquera
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidacionDisquera: def _validar_campos_requeridos(disquera): """Valida que los atributos requeridos se encuentren en el objeto disquera :param disquera: La disquera validar que tenga todos los atributos requeridos :return: Un diccionario con el error y su mensaje si faltan campos requer...
stack_v2_sparse_classes_75kplus_train_001343
4,617
no_license
[ { "docstring": "Valida que los atributos requeridos se encuentren en el objeto disquera :param disquera: La disquera validar que tenga todos los atributos requeridos :return: Un diccionario con el error y su mensaje si faltan campos requeridos o None si no faltan", "name": "_validar_campos_requeridos", ...
4
stack_v2_sparse_classes_30k_train_044940
Implement the Python class `ValidacionDisquera` described below. Class description: Implement the ValidacionDisquera class. Method signatures and docstrings: - def _validar_campos_requeridos(disquera): Valida que los atributos requeridos se encuentren en el objeto disquera :param disquera: La disquera validar que ten...
Implement the Python class `ValidacionDisquera` described below. Class description: Implement the ValidacionDisquera class. Method signatures and docstrings: - def _validar_campos_requeridos(disquera): Valida que los atributos requeridos se encuentren en el objeto disquera :param disquera: La disquera validar que ten...
49bbaaf0bd4d1bec2d81eb35882e5f073b1c149f
<|skeleton|> class ValidacionDisquera: def _validar_campos_requeridos(disquera): """Valida que los atributos requeridos se encuentren en el objeto disquera :param disquera: La disquera validar que tenga todos los atributos requeridos :return: Un diccionario con el error y su mensaje si faltan campos requer...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ValidacionDisquera: def _validar_campos_requeridos(disquera): """Valida que los atributos requeridos se encuentren en el objeto disquera :param disquera: La disquera validar que tenga todos los atributos requeridos :return: Un diccionario con el error y su mensaje si faltan campos requeridos o None si...
the_stack_v2_python_sparse
app/util/validaciones/modelos/ValidacionDisquera.py
codeChinoUV/EspotifeiAPI
train
0
440fa2c0cfcf6e5b4875dc700c31c61af8210bf7
[ "context = super(SignUpFormView, self).get_context_data(**kwargs)\ncontext['title'] = 'Sign Up'\nreturn context", "user_name = form.cleaned_data['username']\nemail = form.cleaned_data['email']\npassword = form.cleaned_data['password']\nconfirm_password = form.cleaned_data['confirm_password']\ncontext = self.get_c...
<|body_start_0|> context = super(SignUpFormView, self).get_context_data(**kwargs) context['title'] = 'Sign Up' return context <|end_body_0|> <|body_start_1|> user_name = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['passwo...
A class of FormView to register a new user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_valid(form): Register the new user
SignUpFormView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignUpFormView: """A class of FormView to register a new user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_vali...
stack_v2_sparse_classes_75kplus_train_001344
9,386
no_license
[ { "docstring": "Call the original method of the view and add the title on the context Parameters ---------- kwargs : str Some argument that Django are passing, need when call the original method of the view Returns ------- dict a dict of the context of the page", "name": "get_context_data", "signature":...
2
stack_v2_sparse_classes_30k_train_037564
Implement the Python class `SignUpFormView` described below. Class description: A class of FormView to register a new user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs)...
Implement the Python class `SignUpFormView` described below. Class description: A class of FormView to register a new user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs)...
939245d046974fabf33fa540b4c3b6d077100ff5
<|skeleton|> class SignUpFormView: """A class of FormView to register a new user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_vali...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SignUpFormView: """A class of FormView to register a new user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_valid(form): Regi...
the_stack_v2_python_sparse
purebeurre/views/user.py
M0l42/P08_PureBeurre
train
1
61ecd17fe5604c61951a55f0df50bff8e4731745
[ "self.gps_data = gps_data\nself.names = []\nself.longitudes = []\nself.latitudes = []", "for gps in self.gps_data:\n if 'GPSLongitude' not in gps or 'GPSLatitude' not in gps:\n continue\n self.names.append(gps.get('SourceFile'))\n self.longitudes.append(gps.get('GPSLongitude'))\n self.latitudes...
<|body_start_0|> self.gps_data = gps_data self.names = [] self.longitudes = [] self.latitudes = [] <|end_body_0|> <|body_start_1|> for gps in self.gps_data: if 'GPSLongitude' not in gps or 'GPSLatitude' not in gps: continue self.names.appe...
Class KML
KML
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KML: """Class KML""" def __init__(self, gps_data): """Constructor""" <|body_0|> def prepare_kml_data(self): """Prepare the date for writing""" <|body_1|> def write(self, filename='data/exif_data.kml'): """Write kml file""" <|body_2|> ...
stack_v2_sparse_classes_75kplus_train_001345
3,240
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, gps_data)" }, { "docstring": "Prepare the date for writing", "name": "prepare_kml_data", "signature": "def prepare_kml_data(self)" }, { "docstring": "Write kml file", "name": "write", "sign...
3
null
Implement the Python class `KML` described below. Class description: Class KML Method signatures and docstrings: - def __init__(self, gps_data): Constructor - def prepare_kml_data(self): Prepare the date for writing - def write(self, filename='data/exif_data.kml'): Write kml file
Implement the Python class `KML` described below. Class description: Class KML Method signatures and docstrings: - def __init__(self, gps_data): Constructor - def prepare_kml_data(self): Prepare the date for writing - def write(self, filename='data/exif_data.kml'): Write kml file <|skeleton|> class KML: """Class...
4b11ef5fa3b3278ded084a9486740d76747caa30
<|skeleton|> class KML: """Class KML""" def __init__(self, gps_data): """Constructor""" <|body_0|> def prepare_kml_data(self): """Prepare the date for writing""" <|body_1|> def write(self, filename='data/exif_data.kml'): """Write kml file""" <|body_2|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KML: """Class KML""" def __init__(self, gps_data): """Constructor""" self.gps_data = gps_data self.names = [] self.longitudes = [] self.latitudes = [] def prepare_kml_data(self): """Prepare the date for writing""" for gps in self.gps_data: ...
the_stack_v2_python_sparse
lib/exif_tool.py
franklehner/cryptology
train
0
0c2788a81165d030a39546552cf8de0b63dd7ed8
[ "self.index = index\nself.refresh_rate = refresh_rate\nself.datadir = datadir\nself.viewport_width = viewport_width\nself.viewport_height = viewport_height\nself.viewport_max_height = viewport_max_height", "try:\n timer = time.time()\n url = self._checkout_url()\n console.dp(f'taking photo of {url.to_str...
<|body_start_0|> self.index = index self.refresh_rate = refresh_rate self.datadir = datadir self.viewport_width = viewport_width self.viewport_height = viewport_height self.viewport_max_height = viewport_max_height <|end_body_0|> <|body_start_1|> try: ...
Photographer class.
Photographer
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Photographer: """Photographer class.""" def __init__(self, index: Index, refresh_rate: Type[refresh.RefreshRate], datadir: DataDirectory, viewport_width: int=1920, viewport_height: int=0, viewport_max_height: Optional[int]=None): """Create new photographer. Args: index: Index where c...
stack_v2_sparse_classes_75kplus_train_001346
3,860
permissive
[ { "docstring": "Create new photographer. Args: index: Index where crawled urls are stored and photos should be indexed. refresh_rate: How often photographs should be refreshed, more exactly defines which lock should be placed on crawled urls datadir: Data directory to store pictures in viewport_width: width of ...
3
stack_v2_sparse_classes_30k_train_028911
Implement the Python class `Photographer` described below. Class description: Photographer class. Method signatures and docstrings: - def __init__(self, index: Index, refresh_rate: Type[refresh.RefreshRate], datadir: DataDirectory, viewport_width: int=1920, viewport_height: int=0, viewport_max_height: Optional[int]=N...
Implement the Python class `Photographer` described below. Class description: Photographer class. Method signatures and docstrings: - def __init__(self, index: Index, refresh_rate: Type[refresh.RefreshRate], datadir: DataDirectory, viewport_width: int=1920, viewport_height: int=0, viewport_max_height: Optional[int]=N...
766b538ac90daa8f8eadce8a1fd43f83413610de
<|skeleton|> class Photographer: """Photographer class.""" def __init__(self, index: Index, refresh_rate: Type[refresh.RefreshRate], datadir: DataDirectory, viewport_width: int=1920, viewport_height: int=0, viewport_max_height: Optional[int]=None): """Create new photographer. Args: index: Index where c...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Photographer: """Photographer class.""" def __init__(self, index: Index, refresh_rate: Type[refresh.RefreshRate], datadir: DataDirectory, viewport_width: int=1920, viewport_height: int=0, viewport_max_height: Optional[int]=None): """Create new photographer. Args: index: Index where crawled urls a...
the_stack_v2_python_sparse
saas/photographer/photographer.py
nattvara/saas
train
2
a98c901ab776273d9592e319c5825b465b714825
[ "self.to_email = to_email\nself.from_email = from_email\nself._email_send_threshold = email_send_threshold\nself._email_last_sent_time = datetime(1970, 1, 1)", "if datetime.now() - self._email_last_sent_time < self._email_send_threshold:\n if logger:\n logger.info('did not send email: %s' % message)\n ...
<|body_start_0|> self.to_email = to_email self.from_email = from_email self._email_send_threshold = email_send_threshold self._email_last_sent_time = datetime(1970, 1, 1) <|end_body_0|> <|body_start_1|> if datetime.now() - self._email_last_sent_time < self._email_send_threshold:...
Send alert emails. Throttle the sending to allow at most one message every self._email_send_threshold
ThrottledMailer
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThrottledMailer: """Send alert emails. Throttle the sending to allow at most one message every self._email_send_threshold""" def __init__(self, to_email, from_email, email_send_threshold): """Args: email_send_threshold: timedelta""" <|body_0|> def send_email(self, messag...
stack_v2_sparse_classes_75kplus_train_001347
1,374
permissive
[ { "docstring": "Args: email_send_threshold: timedelta", "name": "__init__", "signature": "def __init__(self, to_email, from_email, email_send_threshold)" }, { "docstring": "send an alert email if one hasn't been sent recently Args: message (string): the email body logger [optional] (logger objec...
2
stack_v2_sparse_classes_30k_train_028077
Implement the Python class `ThrottledMailer` described below. Class description: Send alert emails. Throttle the sending to allow at most one message every self._email_send_threshold Method signatures and docstrings: - def __init__(self, to_email, from_email, email_send_threshold): Args: email_send_threshold: timedel...
Implement the Python class `ThrottledMailer` described below. Class description: Send alert emails. Throttle the sending to allow at most one message every self._email_send_threshold Method signatures and docstrings: - def __init__(self, to_email, from_email, email_send_threshold): Args: email_send_threshold: timedel...
70280110ec342a6f6db1c102e96756fcc3c3c01b
<|skeleton|> class ThrottledMailer: """Send alert emails. Throttle the sending to allow at most one message every self._email_send_threshold""" def __init__(self, to_email, from_email, email_send_threshold): """Args: email_send_threshold: timedelta""" <|body_0|> def send_email(self, messag...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ThrottledMailer: """Send alert emails. Throttle the sending to allow at most one message every self._email_send_threshold""" def __init__(self, to_email, from_email, email_send_threshold): """Args: email_send_threshold: timedelta""" self.to_email = to_email self.from_email = from_...
the_stack_v2_python_sparse
pylib/net/mailer.py
room77/py77
train
0
b95da1d90ea2e1f57aecf7e28c7c28ea49f71d9c
[ "satSolverName = satSolverName.lower()\nif satSolverName == 'lingeling' or satSolverName == '':\n return SatSolver.LINGELING\nelif satSolverName == 'minisat':\n return SatSolver.MINISAT\nelif satSolverName == 'picosat':\n return SatSolver.PICOSAT\nelse:\n errMsg = 'Unknown backend SAT solver for Boolect...
<|body_start_0|> satSolverName = satSolverName.lower() if satSolverName == 'lingeling' or satSolverName == '': return SatSolver.LINGELING elif satSolverName == 'minisat': return SatSolver.MINISAT elif satSolverName == 'picosat': return SatSolver.PICOSA...
This class represents the SAT solver used by Boolector.
SatSolver
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SatSolver: """This class represents the SAT solver used by Boolector.""" def getSatSolver(satSolverName): """Returns the SatSolver representation of the SAT solver whose name is provided. @param satSolverName Name of a SAT solver. @retval SatSolver representation of the SAT solver wh...
stack_v2_sparse_classes_75kplus_train_001348
5,145
no_license
[ { "docstring": "Returns the SatSolver representation of the SAT solver whose name is provided. @param satSolverName Name of a SAT solver. @retval SatSolver representation of the SAT solver whose name is provided.", "name": "getSatSolver", "signature": "def getSatSolver(satSolverName)" }, { "docs...
2
stack_v2_sparse_classes_30k_train_003613
Implement the Python class `SatSolver` described below. Class description: This class represents the SAT solver used by Boolector. Method signatures and docstrings: - def getSatSolver(satSolverName): Returns the SatSolver representation of the SAT solver whose name is provided. @param satSolverName Name of a SAT solv...
Implement the Python class `SatSolver` described below. Class description: This class represents the SAT solver used by Boolector. Method signatures and docstrings: - def getSatSolver(satSolverName): Returns the SatSolver representation of the SAT solver whose name is provided. @param satSolverName Name of a SAT solv...
43fbd6ae7f83c9ebf55dbedb4f98ce064c04514c
<|skeleton|> class SatSolver: """This class represents the SAT solver used by Boolector.""" def getSatSolver(satSolverName): """Returns the SatSolver representation of the SAT solver whose name is provided. @param satSolverName Name of a SAT solver. @retval SatSolver representation of the SAT solver wh...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SatSolver: """This class represents the SAT solver used by Boolector.""" def getSatSolver(satSolverName): """Returns the SatSolver representation of the SAT solver whose name is provided. @param satSolverName Name of a SAT solver. @retval SatSolver representation of the SAT solver whose name is p...
the_stack_v2_python_sparse
build/lib.linux-x86_64-2.7/gametime/smt/solvers/boolectorSolver.py
jerryduan07/gametime
train
0
e04f857ccfad76cbf06f8c74727bc55653faa71a
[ "self.cardinality = cardinality\nif norm_factory is None:\n norm_factory = nn.BatchNorm2d\nself.norm_factory = norm_factory\nself.resnext_class = copy(models.resnet.Bottleneck)\nself.resnext_class.expansion = 2", "stride = 1\nprojection = None\nif downsample > 1:\n stride = downsample\nif downsample > 1 or ...
<|body_start_0|> self.cardinality = cardinality if norm_factory is None: norm_factory = nn.BatchNorm2d self.norm_factory = norm_factory self.resnext_class = copy(models.resnet.Bottleneck) self.resnext_class.expansion = 2 <|end_body_0|> <|body_start_1|> stride...
Factory wrapper for ``torchvision`` ResNeXt blocks.
ResNeXtBlockFactory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResNeXtBlockFactory: """Factory wrapper for ``torchvision`` ResNeXt blocks.""" def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None): """Args: cardinality: The cardinality of the block as defined in the ResNeXt paper. norm_factory: A factory obje...
stack_v2_sparse_classes_75kplus_train_001349
6,999
permissive
[ { "docstring": "Args: cardinality: The cardinality of the block as defined in the ResNeXt paper. norm_factory: A factory object to produce the normalization layers used in the ResNet blocks. Defaults to batch norm.", "name": "__init__", "signature": "def __init__(self, cardinality=32, norm_factory: Opti...
2
stack_v2_sparse_classes_30k_train_034747
Implement the Python class `ResNeXtBlockFactory` described below. Class description: Factory wrapper for ``torchvision`` ResNeXt blocks. Method signatures and docstrings: - def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None): Args: cardinality: The cardinality of the block as d...
Implement the Python class `ResNeXtBlockFactory` described below. Class description: Factory wrapper for ``torchvision`` ResNeXt blocks. Method signatures and docstrings: - def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None): Args: cardinality: The cardinality of the block as d...
a27e329cd30337995c359160a0d878bf331c13fb
<|skeleton|> class ResNeXtBlockFactory: """Factory wrapper for ``torchvision`` ResNeXt blocks.""" def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None): """Args: cardinality: The cardinality of the block as defined in the ResNeXt paper. norm_factory: A factory obje...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ResNeXtBlockFactory: """Factory wrapper for ``torchvision`` ResNeXt blocks.""" def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None): """Args: cardinality: The cardinality of the block as defined in the ResNeXt paper. norm_factory: A factory object to produce...
the_stack_v2_python_sparse
quantnn/models/pytorch/torchvision.py
simonpf/quantnn
train
7
962b2476b73530dac7b44dad1d2e5214fcddec46
[ "raise_error = kwargs.get(RAISE_ERROR, True)\ntry:\n cls.check_valid_status(appointment, cls.status_enum.ON_MODERATION)\nexcept WrongStatusError as err:\n valid_err = cls.reject_error(title=err.title)\n if raise_error:\n raise valid_err\n else:\n logging.warning(valid_err, extra={APPOINTME...
<|body_start_0|> raise_error = kwargs.get(RAISE_ERROR, True) try: cls.check_valid_status(appointment, cls.status_enum.ON_MODERATION) except WrongStatusError as err: valid_err = cls.reject_error(title=err.title) if raise_error: raise valid_err ...
AppointmentModerationValidator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AppointmentModerationValidator: def validate_before_reject(cls, appointment: Appointment, **kwargs) -> None: """:raises: apps.appointments.exceptions.AppointmentRejectError""" <|body_0|> def validate_before_approve(cls, appointment: Appointment) -> None: """:raises: ...
stack_v2_sparse_classes_75kplus_train_001350
12,944
no_license
[ { "docstring": ":raises: apps.appointments.exceptions.AppointmentRejectError", "name": "validate_before_reject", "signature": "def validate_before_reject(cls, appointment: Appointment, **kwargs) -> None" }, { "docstring": ":raises: apps.appointments.exceptions.AppointmentApproveError", "name...
3
stack_v2_sparse_classes_30k_val_001220
Implement the Python class `AppointmentModerationValidator` described below. Class description: Implement the AppointmentModerationValidator class. Method signatures and docstrings: - def validate_before_reject(cls, appointment: Appointment, **kwargs) -> None: :raises: apps.appointments.exceptions.AppointmentRejectEr...
Implement the Python class `AppointmentModerationValidator` described below. Class description: Implement the AppointmentModerationValidator class. Method signatures and docstrings: - def validate_before_reject(cls, appointment: Appointment, **kwargs) -> None: :raises: apps.appointments.exceptions.AppointmentRejectEr...
447a4c46e578f9aa1ae015edd39752d3b9b5cb28
<|skeleton|> class AppointmentModerationValidator: def validate_before_reject(cls, appointment: Appointment, **kwargs) -> None: """:raises: apps.appointments.exceptions.AppointmentRejectError""" <|body_0|> def validate_before_approve(cls, appointment: Appointment) -> None: """:raises: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AppointmentModerationValidator: def validate_before_reject(cls, appointment: Appointment, **kwargs) -> None: """:raises: apps.appointments.exceptions.AppointmentRejectError""" raise_error = kwargs.get(RAISE_ERROR, True) try: cls.check_valid_status(appointment, cls.status_en...
the_stack_v2_python_sparse
apps/appointments/validators.py
kirmalyshev/django_example
train
0
cd3573f0dfa867d336d395af0fa81e99a4782534
[ "res = []\nif root:\n queue = deque([root])\n while queue:\n tmp = queue.pop()\n res.append(str(tmp.val))\n res.append(str(len(tmp.children)))\n for ch in tmp.children:\n queue.appendleft(ch)\nreturn ','.join(res)", "if not data:\n return\ndata = map(int, data.split...
<|body_start_0|> res = [] if root: queue = deque([root]) while queue: tmp = queue.pop() res.append(str(tmp.val)) res.append(str(len(tmp.children))) for ch in tmp.children: queue.appendleft(ch) ...
Codec1
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec1: def serialize(self, root: 'Node') -> str: """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data: str) -> 'Node': """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|...
stack_v2_sparse_classes_75kplus_train_001351
2,421
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: Node :rtype: str", "name": "serialize", "signature": "def serialize(self, root: 'Node') -> str" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node", "name": "deserialize", "signature": "def des...
2
stack_v2_sparse_classes_30k_train_039075
Implement the Python class `Codec1` described below. Class description: Implement the Codec1 class. Method signatures and docstrings: - def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str - def deserialize(self, data: str) -> 'Node': Decodes your encoded data to t...
Implement the Python class `Codec1` described below. Class description: Implement the Codec1 class. Method signatures and docstrings: - def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str - def deserialize(self, data: str) -> 'Node': Decodes your encoded data to t...
631df2ce6892a6fbb3e435f57e90d85f8200d125
<|skeleton|> class Codec1: def serialize(self, root: 'Node') -> str: """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data: str) -> 'Node': """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec1: def serialize(self, root: 'Node') -> str: """Encodes a tree to a single string. :type root: Node :rtype: str""" res = [] if root: queue = deque([root]) while queue: tmp = queue.pop() res.append(str(tmp.val)) ...
the_stack_v2_python_sparse
428. Serialize and Deserialize N-ary Tree.py
c940606/leetcode
train
3
af15dc2333d6fb9f33f8f7b9703e55149d65f034
[ "mocker.patch.object(Microsoft365DefenderEventCollector.dateparser, 'parse', return_value=datetime.datetime.now())\nmocker.patch.object(demisto, 'setLastRun')\nmocker.patch.object(demisto, 'getLastRun', return_value=None)\nmain(command='fetch-events', params=PARAMS)\nMicrosoft365DefenderEventCollector.dateparser.pa...
<|body_start_0|> mocker.patch.object(Microsoft365DefenderEventCollector.dateparser, 'parse', return_value=datetime.datetime.now()) mocker.patch.object(demisto, 'setLastRun') mocker.patch.object(demisto, 'getLastRun', return_value=None) main(command='fetch-events', params=PARAMS) ...
TestFetchEventsHappyPath
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestFetchEventsHappyPath: def test_fetch_events_first_time(self, mocker): """Given - there is no object returned by demist.getLastRun. When - fetch_events called for the first time. Then - ensure the dateparser was called.""" <|body_0|> def test_fetch_events_second_time(self...
stack_v2_sparse_classes_75kplus_train_001352
8,420
permissive
[ { "docstring": "Given - there is no object returned by demist.getLastRun. When - fetch_events called for the first time. Then - ensure the dateparser was called.", "name": "test_fetch_events_first_time", "signature": "def test_fetch_events_first_time(self, mocker)" }, { "docstring": "Given - dem...
3
stack_v2_sparse_classes_30k_train_047171
Implement the Python class `TestFetchEventsHappyPath` described below. Class description: Implement the TestFetchEventsHappyPath class. Method signatures and docstrings: - def test_fetch_events_first_time(self, mocker): Given - there is no object returned by demist.getLastRun. When - fetch_events called for the first...
Implement the Python class `TestFetchEventsHappyPath` described below. Class description: Implement the TestFetchEventsHappyPath class. Method signatures and docstrings: - def test_fetch_events_first_time(self, mocker): Given - there is no object returned by demist.getLastRun. When - fetch_events called for the first...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class TestFetchEventsHappyPath: def test_fetch_events_first_time(self, mocker): """Given - there is no object returned by demist.getLastRun. When - fetch_events called for the first time. Then - ensure the dateparser was called.""" <|body_0|> def test_fetch_events_second_time(self...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestFetchEventsHappyPath: def test_fetch_events_first_time(self, mocker): """Given - there is no object returned by demist.getLastRun. When - fetch_events called for the first time. Then - ensure the dateparser was called.""" mocker.patch.object(Microsoft365DefenderEventCollector.dateparser, '...
the_stack_v2_python_sparse
Packs/MicrosoftDefenderAdvancedThreatProtection/Integrations/Microsoft365DefenderEventCollector/Microsoft365DefenderEventCollector_test.py
demisto/content
train
1,023
a9fbf03c4343d9e0e251ffc65f234739c143cfda
[ "time_elements_structure = self._GetValueFromStructure(structure, 'date_time')\nlog_line = self._GetValueFromStructure(structure, 'log_line', default_value='')\nlog_line = log_line.lstrip().rstrip()\npids = self._GetValueFromStructure(structure, 'pid', default_value=[])\ntime_zone_string = self._GetValueFromStructu...
<|body_start_0|> time_elements_structure = self._GetValueFromStructure(structure, 'date_time') log_line = self._GetValueFromStructure(structure, 'log_line', default_value='') log_line = log_line.lstrip().rstrip() pids = self._GetValueFromStructure(structure, 'pid', default_value=[]) ...
Text parser plugin for PostgreSQL application log files.
PostgreSQLTextPlugin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PostgreSQLTextPlugin: """Text parser plugin for PostgreSQL application log files.""" def _ParseRecord(self, parser_mediator, key, structure): """Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as s...
stack_v2_sparse_classes_75kplus_train_001353
9,463
permissive
[ { "docstring": "Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. key (str): name of the parsed structure. structure (pyparsing.ParseResults): tokens from a parsed log line. Raises: ParseError: if the stru...
3
stack_v2_sparse_classes_30k_train_014753
Implement the Python class `PostgreSQLTextPlugin` described below. Class description: Text parser plugin for PostgreSQL application log files. Method signatures and docstrings: - def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates int...
Implement the Python class `PostgreSQLTextPlugin` described below. Class description: Text parser plugin for PostgreSQL application log files. Method signatures and docstrings: - def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates int...
d6022f8cfebfddf2d08ab2d300a41b61f3349933
<|skeleton|> class PostgreSQLTextPlugin: """Text parser plugin for PostgreSQL application log files.""" def _ParseRecord(self, parser_mediator, key, structure): """Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PostgreSQLTextPlugin: """Text parser plugin for PostgreSQL application log files.""" def _ParseRecord(self, parser_mediator, key, structure): """Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and df...
the_stack_v2_python_sparse
plaso/parsers/text_plugins/postgresql.py
log2timeline/plaso
train
1,506
240396d6192d944ea6a8f39385c0ecbd62e67128
[ "super(_HashDropZones, self).__init__(parent)\npen = qt.QPen()\npen.setColor(qt.QColor('#D0D0D0'))\npen.setStyle(qt.Qt.DotLine)\npen.setWidth(2)\nself.__dropPen = pen", "displayDropZone = False\nif index.isValid():\n model = index.model()\n rowIndex = model.index(index.row(), 0, index.parent())\n rowItem...
<|body_start_0|> super(_HashDropZones, self).__init__(parent) pen = qt.QPen() pen.setColor(qt.QColor('#D0D0D0')) pen.setStyle(qt.Qt.DotLine) pen.setWidth(2) self.__dropPen = pen <|end_body_0|> <|body_start_1|> displayDropZone = False if index.isValid(): ...
Delegate item displaying a drop zone when the item do not contains dataset.
_HashDropZones
[ "MIT", "LicenseRef-scancode-public-domain-disclaimer", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _HashDropZones: """Delegate item displaying a drop zone when the item do not contains dataset.""" def __init__(self, parent=None): """Constructor""" <|body_0|> def paint(self, painter, option, index): """Paint the item :param qt.QPainter painter: A painter :param...
stack_v2_sparse_classes_75kplus_train_001354
34,928
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, parent=None)" }, { "docstring": "Paint the item :param qt.QPainter painter: A painter :param qt.QStyleOptionViewItem option: Options of the item to paint :param qt.QModelIndex index: Index of the item to paint", ...
2
stack_v2_sparse_classes_30k_train_043156
Implement the Python class `_HashDropZones` described below. Class description: Delegate item displaying a drop zone when the item do not contains dataset. Method signatures and docstrings: - def __init__(self, parent=None): Constructor - def paint(self, painter, option, index): Paint the item :param qt.QPainter pain...
Implement the Python class `_HashDropZones` described below. Class description: Delegate item displaying a drop zone when the item do not contains dataset. Method signatures and docstrings: - def __init__(self, parent=None): Constructor - def paint(self, painter, option, index): Paint the item :param qt.QPainter pain...
5e33cb69afd2a8b1cfe3183282acdd8b34c1a74f
<|skeleton|> class _HashDropZones: """Delegate item displaying a drop zone when the item do not contains dataset.""" def __init__(self, parent=None): """Constructor""" <|body_0|> def paint(self, painter, option, index): """Paint the item :param qt.QPainter painter: A painter :param...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _HashDropZones: """Delegate item displaying a drop zone when the item do not contains dataset.""" def __init__(self, parent=None): """Constructor""" super(_HashDropZones, self).__init__(parent) pen = qt.QPen() pen.setColor(qt.QColor('#D0D0D0')) pen.setStyle(qt.Qt.D...
the_stack_v2_python_sparse
src/silx/app/view/CustomNxdataWidget.py
silx-kit/silx
train
120
05720cf49161e4e7ee89a94e5b97bf749bae35e3
[ "self.scales = scales\nself.img_scale_mode = img_scale_mode\nself.inclPixelStats = inclPixelStats", "if isinstance(image, torch.Tensor):\n image = image.numpy()\nimage = np.squeeze(image)\nassert image.ndim == 2\na = Analysis(image, nsc=self.scales, scale_mode=self.img_scale_mode)\na.computeFeatures()\njointSt...
<|body_start_0|> self.scales = scales self.img_scale_mode = img_scale_mode self.inclPixelStats = inclPixelStats <|end_body_0|> <|body_start_1|> if isinstance(image, torch.Tensor): image = image.numpy() image = np.squeeze(image) assert image.ndim == 2 ...
Extracts Portilla & Simoncelli Texture Model features. [1] Portilla & Simoncelli (2000). A parametric texture model based on joint statistics of complex wavelet coefficients. http://www.cns.nyu.edu/pub/lcv/portilla99-reprint.pdf Usage ====== transform = PSTMfeatures() transform(gsImage) OR psfeatures = PSTMfeatures() m...
PSTMfeatures
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PSTMfeatures: """Extracts Portilla & Simoncelli Texture Model features. [1] Portilla & Simoncelli (2000). A parametric texture model based on joint statistics of complex wavelet coefficients. http://www.cns.nyu.edu/pub/lcv/portilla99-reprint.pdf Usage ====== transform = PSTMfeatures() transform(g...
stack_v2_sparse_classes_75kplus_train_001355
2,751
permissive
[ { "docstring": "Initialize all parameters needed to analyze a texture image. Args: scales: spatial neighborhood of autocorrelations is Na x Na coefficients (must be odd) img_scale_mode: default None. 'rescale01', 'norm255'", "name": "__init__", "signature": "def __init__(self, scales=2, img_scale_mode=N...
2
stack_v2_sparse_classes_30k_train_009494
Implement the Python class `PSTMfeatures` described below. Class description: Extracts Portilla & Simoncelli Texture Model features. [1] Portilla & Simoncelli (2000). A parametric texture model based on joint statistics of complex wavelet coefficients. http://www.cns.nyu.edu/pub/lcv/portilla99-reprint.pdf Usage ======...
Implement the Python class `PSTMfeatures` described below. Class description: Extracts Portilla & Simoncelli Texture Model features. [1] Portilla & Simoncelli (2000). A parametric texture model based on joint statistics of complex wavelet coefficients. http://www.cns.nyu.edu/pub/lcv/portilla99-reprint.pdf Usage ======...
08476d21ce17cc95180525d48202a1690dfc8a08
<|skeleton|> class PSTMfeatures: """Extracts Portilla & Simoncelli Texture Model features. [1] Portilla & Simoncelli (2000). A parametric texture model based on joint statistics of complex wavelet coefficients. http://www.cns.nyu.edu/pub/lcv/portilla99-reprint.pdf Usage ====== transform = PSTMfeatures() transform(g...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PSTMfeatures: """Extracts Portilla & Simoncelli Texture Model features. [1] Portilla & Simoncelli (2000). A parametric texture model based on joint statistics of complex wavelet coefficients. http://www.cns.nyu.edu/pub/lcv/portilla99-reprint.pdf Usage ====== transform = PSTMfeatures() transform(gsImage) OR ps...
the_stack_v2_python_sparse
ummon/features/psTMfeatures.py
matherm/ummon3
train
1
d9196278f76499515f3876a8c6e4a81905976057
[ "serializer_context = {'request': request}\narticle = request.data.get('article', {})\nserializer = self.serializer_class(data=article, context=serializer_context)\nserializer.is_valid(raise_exception=True)\nserializer.save(author=request.user.profile)\nreturn Response(serializer.data, status=status.HTTP_201_CREATE...
<|body_start_0|> serializer_context = {'request': request} article = request.data.get('article', {}) serializer = self.serializer_class(data=article, context=serializer_context) serializer.is_valid(raise_exception=True) serializer.save(author=request.user.profile) return ...
This class defines the create behavior of our articles.
ArticleAPIView
[ "MIT", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArticleAPIView: """This class defines the create behavior of our articles.""" def create(self, request): """Create an article""" <|body_0|> def retrieve(self, request, slug): """Get one article""" <|body_1|> def update(self, request, slug): "...
stack_v2_sparse_classes_75kplus_train_001356
12,608
permissive
[ { "docstring": "Create an article", "name": "create", "signature": "def create(self, request)" }, { "docstring": "Get one article", "name": "retrieve", "signature": "def retrieve(self, request, slug)" }, { "docstring": "Edit an article", "name": "update", "signature": "de...
4
null
Implement the Python class `ArticleAPIView` described below. Class description: This class defines the create behavior of our articles. Method signatures and docstrings: - def create(self, request): Create an article - def retrieve(self, request, slug): Get one article - def update(self, request, slug): Edit an artic...
Implement the Python class `ArticleAPIView` described below. Class description: This class defines the create behavior of our articles. Method signatures and docstrings: - def create(self, request): Create an article - def retrieve(self, request, slug): Get one article - def update(self, request, slug): Edit an artic...
19f5550f97905ee4a97574cab799d42a0471f12b
<|skeleton|> class ArticleAPIView: """This class defines the create behavior of our articles.""" def create(self, request): """Create an article""" <|body_0|> def retrieve(self, request, slug): """Get one article""" <|body_1|> def update(self, request, slug): "...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ArticleAPIView: """This class defines the create behavior of our articles.""" def create(self, request): """Create an article""" serializer_context = {'request': request} article = request.data.get('article', {}) serializer = self.serializer_class(data=article, context=ser...
the_stack_v2_python_sparse
authors/apps/articles/views.py
Tittoh/blogAPI
train
1
dbcd35e613d486f17c850f59d71a8420ff8ada9d
[ "flag = []\nfor i in range(n):\n flag.append(False)\ncount = 1\nwhile count <= n:\n idx = count\n while idx <= n:\n flag[idx - 1] = not flag[idx - 1]\n idx += count\n print('{} - {}'.format(count, flag))\n count += 1\npass\nnum = 0\nfor _, ele in enumerate(flag):\n if ele:\n n...
<|body_start_0|> flag = [] for i in range(n): flag.append(False) count = 1 while count <= n: idx = count while idx <= n: flag[idx - 1] = not flag[idx - 1] idx += count print('{} - {}'.format(count, flag)) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def bulbSwitch(self, n: int) -> int: """思路:首先,这一定是一个不可取的方法!创建个数组,模拟灯泡。然后从头遍历n次,每次步幅为n :param n: :return:""" <|body_0|> def func2(self, n): """思路:发现灯泡的被操作次数与这个数的因子个数有关。 比如12这个灯泡,当count=1、2、3、4、6、12时都将影响这个灯泡,它的最终结果是关!因为因子个数是偶数 所以一次遍历即可,且不需要额外的存储空间。 很抱歉地通知:时间超...
stack_v2_sparse_classes_75kplus_train_001357
3,421
no_license
[ { "docstring": "思路:首先,这一定是一个不可取的方法!创建个数组,模拟灯泡。然后从头遍历n次,每次步幅为n :param n: :return:", "name": "bulbSwitch", "signature": "def bulbSwitch(self, n: int) -> int" }, { "docstring": "思路:发现灯泡的被操作次数与这个数的因子个数有关。 比如12这个灯泡,当count=1、2、3、4、6、12时都将影响这个灯泡,它的最终结果是关!因为因子个数是偶数 所以一次遍历即可,且不需要额外的存储空间。 很抱歉地通知:时间超出限制,在求...
4
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def bulbSwitch(self, n: int) -> int: 思路:首先,这一定是一个不可取的方法!创建个数组,模拟灯泡。然后从头遍历n次,每次步幅为n :param n: :return: - def func2(self, n): 思路:发现灯泡的被操作次数与这个数的因子个数有关。 比如12这个灯泡,当count=1、2、3、4、6、12...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def bulbSwitch(self, n: int) -> int: 思路:首先,这一定是一个不可取的方法!创建个数组,模拟灯泡。然后从头遍历n次,每次步幅为n :param n: :return: - def func2(self, n): 思路:发现灯泡的被操作次数与这个数的因子个数有关。 比如12这个灯泡,当count=1、2、3、4、6、12...
46cfe84921a9a3e865edd1f94e7807b320b53778
<|skeleton|> class Solution: def bulbSwitch(self, n: int) -> int: """思路:首先,这一定是一个不可取的方法!创建个数组,模拟灯泡。然后从头遍历n次,每次步幅为n :param n: :return:""" <|body_0|> def func2(self, n): """思路:发现灯泡的被操作次数与这个数的因子个数有关。 比如12这个灯泡,当count=1、2、3、4、6、12时都将影响这个灯泡,它的最终结果是关!因为因子个数是偶数 所以一次遍历即可,且不需要额外的存储空间。 很抱歉地通知:时间超...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def bulbSwitch(self, n: int) -> int: """思路:首先,这一定是一个不可取的方法!创建个数组,模拟灯泡。然后从头遍历n次,每次步幅为n :param n: :return:""" flag = [] for i in range(n): flag.append(False) count = 1 while count <= n: idx = count while idx <= n: ...
the_stack_v2_python_sparse
2020-08/Q319-bulb_switch.py
EAGLE50/LearnLeetCode
train
0
24e38dfbd7c7d4f8642274b6fc8910979aed7da9
[ "real_item_id = self.get_argument('real_item_id')\nif not real_item_id:\n return\nremark = self.get_argument('return_remark')\nreturn_amount = Decimal(self.get_argument('return_amount'))\npart_refund_price = self.get_argument('refund_part_price')\nif part_refund_price and Decimal(part_refund_price) > 0:\n ret...
<|body_start_0|> real_item_id = self.get_argument('real_item_id') if not real_item_id: return remark = self.get_argument('return_remark') return_amount = Decimal(self.get_argument('return_amount')) part_refund_price = self.get_argument('refund_part_price') if ...
RealGoodsRefundHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RealGoodsRefundHandler: def post(self): """处理退款、退货""" <|body_0|> def handleRefundOfNoSend(self, real_item, remark, return_amount): """处理退款""" <|body_1|> <|end_skeleton|> <|body_start_0|> real_item_id = self.get_argument('real_item_id') if no...
stack_v2_sparse_classes_75kplus_train_001358
9,076
no_license
[ { "docstring": "处理退款、退货", "name": "post", "signature": "def post(self)" }, { "docstring": "处理退款", "name": "handleRefundOfNoSend", "signature": "def handleRefundOfNoSend(self, real_item, remark, return_amount)" } ]
2
stack_v2_sparse_classes_30k_train_053652
Implement the Python class `RealGoodsRefundHandler` described below. Class description: Implement the RealGoodsRefundHandler class. Method signatures and docstrings: - def post(self): 处理退款、退货 - def handleRefundOfNoSend(self, real_item, remark, return_amount): 处理退款
Implement the Python class `RealGoodsRefundHandler` described below. Class description: Implement the RealGoodsRefundHandler class. Method signatures and docstrings: - def post(self): 处理退款、退货 - def handleRefundOfNoSend(self, real_item, remark, return_amount): 处理退款 <|skeleton|> class RealGoodsRefundHandler: def ...
daf260ecd5adf553490a8ac6b389a74439234b6a
<|skeleton|> class RealGoodsRefundHandler: def post(self): """处理退款、退货""" <|body_0|> def handleRefundOfNoSend(self, real_item, remark, return_amount): """处理退款""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RealGoodsRefundHandler: def post(self): """处理退款、退货""" real_item_id = self.get_argument('real_item_id') if not real_item_id: return remark = self.get_argument('return_remark') return_amount = Decimal(self.get_argument('return_amount')) part_refund_pri...
the_stack_v2_python_sparse
apps/op/controllers/real/return_entry.py
xutaoding/osp_autumn
train
0
8966446ff73c6fa6e2d697c6cebe86b7b7a67777
[ "ConfigInitializer._generate_config_file_if_missing(path)\nconfig_parser = SafeConfigParser()\nconfig_parser.read(path)\nreturn config_parser", "if not os.path.isfile(dest_path):\n print(dest_path + ' missing, generating new one from ' + src_path)\n copyfile(src_path, dest_path)" ]
<|body_start_0|> ConfigInitializer._generate_config_file_if_missing(path) config_parser = SafeConfigParser() config_parser.read(path) return config_parser <|end_body_0|> <|body_start_1|> if not os.path.isfile(dest_path): print(dest_path + ' missing, generating new on...
Initialize the SafeConfigParser.
ConfigInitializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigInitializer: """Initialize the SafeConfigParser.""" def get_config_parser(path=dir_path + '../config.ini'): """Get a SafeConfigParser that parses a given config file. :param path: input path to the config file :return: SafeConfigParser for the config file""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_001359
1,177
no_license
[ { "docstring": "Get a SafeConfigParser that parses a given config file. :param path: input path to the config file :return: SafeConfigParser for the config file", "name": "get_config_parser", "signature": "def get_config_parser(path=dir_path + '../config.ini')" }, { "docstring": "Make a copy of ...
2
stack_v2_sparse_classes_30k_train_037524
Implement the Python class `ConfigInitializer` described below. Class description: Initialize the SafeConfigParser. Method signatures and docstrings: - def get_config_parser(path=dir_path + '../config.ini'): Get a SafeConfigParser that parses a given config file. :param path: input path to the config file :return: Sa...
Implement the Python class `ConfigInitializer` described below. Class description: Initialize the SafeConfigParser. Method signatures and docstrings: - def get_config_parser(path=dir_path + '../config.ini'): Get a SafeConfigParser that parses a given config file. :param path: input path to the config file :return: Sa...
187023f93937985e10f593b032ea7f48c1d61060
<|skeleton|> class ConfigInitializer: """Initialize the SafeConfigParser.""" def get_config_parser(path=dir_path + '../config.ini'): """Get a SafeConfigParser that parses a given config file. :param path: input path to the config file :return: SafeConfigParser for the config file""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConfigInitializer: """Initialize the SafeConfigParser.""" def get_config_parser(path=dir_path + '../config.ini'): """Get a SafeConfigParser that parses a given config file. :param path: input path to the config file :return: SafeConfigParser for the config file""" ConfigInitializer._gener...
the_stack_v2_python_sparse
config_initializer/config_initializer.py
janetzki/fact_extraction
train
5
7bf94723357d75790a5614d990d0a1c7e3b1b865
[ "kwargs['default'] = default\nkwargs['types'] = (tuple, list)\nsuper().__init__(**kwargs)", "if isinstance(value, (list, tuple)) and all((isinstance(x, (int, float)) for x in value)):\n return value\nvalue = super().parse(value)\nif value is None or value is UNDEF:\n return value\nif callable(value):\n r...
<|body_start_0|> kwargs['default'] = default kwargs['types'] = (tuple, list) super().__init__(**kwargs) <|end_body_0|> <|body_start_1|> if isinstance(value, (list, tuple)) and all((isinstance(x, (int, float)) for x in value)): return value value = super().parse(value...
Defines a line dash property. The value must be provided as a list or tuple of numbers defining the length of lines and spaces in-between.
DashProperty
[ "LicenseRef-scancode-philippe-de-muyter", "LicenseRef-scancode-commercial-license", "AGPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DashProperty: """Defines a line dash property. The value must be provided as a list or tuple of numbers defining the length of lines and spaces in-between.""" def __init__(self, default=UNDEF, **kwargs): """Initializes a new instance of DashProperty.""" <|body_0|> def pa...
stack_v2_sparse_classes_75kplus_train_001360
4,576
permissive
[ { "docstring": "Initializes a new instance of DashProperty.", "name": "__init__", "signature": "def __init__(self, default=UNDEF, **kwargs)" }, { "docstring": "Validates and converts given value.", "name": "parse", "signature": "def parse(self, value)" } ]
2
stack_v2_sparse_classes_30k_train_010117
Implement the Python class `DashProperty` described below. Class description: Defines a line dash property. The value must be provided as a list or tuple of numbers defining the length of lines and spaces in-between. Method signatures and docstrings: - def __init__(self, default=UNDEF, **kwargs): Initializes a new in...
Implement the Python class `DashProperty` described below. Class description: Defines a line dash property. The value must be provided as a list or tuple of numbers defining the length of lines and spaces in-between. Method signatures and docstrings: - def __init__(self, default=UNDEF, **kwargs): Initializes a new in...
d59b1bc056f3037b7b7ab635b6deb41120612965
<|skeleton|> class DashProperty: """Defines a line dash property. The value must be provided as a list or tuple of numbers defining the length of lines and spaces in-between.""" def __init__(self, default=UNDEF, **kwargs): """Initializes a new instance of DashProperty.""" <|body_0|> def pa...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DashProperty: """Defines a line dash property. The value must be provided as a list or tuple of numbers defining the length of lines and spaces in-between.""" def __init__(self, default=UNDEF, **kwargs): """Initializes a new instance of DashProperty.""" kwargs['default'] = default ...
the_stack_v2_python_sparse
pero/properties/special.py
xxao/pero
train
31
4dbd6f9a9560fcc80842e38cdf9741d712215c77
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Missing associated documentation comment in .proto file.
AzureStorageServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AzureStorageServiceServicer: """Missing associated documentation comment in .proto file.""" def listAzureStorage(self, request, context): """Storage""" <|body_0|> def getAzureStorage(self, request, context): """Missing associated documentation comment in .proto f...
stack_v2_sparse_classes_75kplus_train_001361
9,910
permissive
[ { "docstring": "Storage", "name": "listAzureStorage", "signature": "def listAzureStorage(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "getAzureStorage", "signature": "def getAzureStorage(self, request, context)" }, { ...
5
stack_v2_sparse_classes_30k_train_000199
Implement the Python class `AzureStorageServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def listAzureStorage(self, request, context): Storage - def getAzureStorage(self, request, context): Missing associated documentatio...
Implement the Python class `AzureStorageServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def listAzureStorage(self, request, context): Storage - def getAzureStorage(self, request, context): Missing associated documentatio...
c69e14b409add099d151434b9add711e41f41b20
<|skeleton|> class AzureStorageServiceServicer: """Missing associated documentation comment in .proto file.""" def listAzureStorage(self, request, context): """Storage""" <|body_0|> def getAzureStorage(self, request, context): """Missing associated documentation comment in .proto f...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AzureStorageServiceServicer: """Missing associated documentation comment in .proto file.""" def listAzureStorage(self, request, context): """Storage""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError(...
the_stack_v2_python_sparse
python-sdk/src/airavata_mft_sdk/azure/AzureStorageService_pb2_grpc.py
apache/airavata-mft
train
23
d0b14fea03f5898aea3b93a4ce7f463b716b7f6b
[ "super(CreateVolumeServerfromSnapshotTest, cls).setUpClass()\ncls.server = cls.server_behaviors.create_active_server().entity\ncls.volume_sec = cls.blockstorage_behavior.create_available_volume(size=cls.volume_size, volume_type=cls.volume_type, image_ref=cls.image_ref, timeout=cls.volume_create_timeout)\ncls.snapsh...
<|body_start_0|> super(CreateVolumeServerfromSnapshotTest, cls).setUpClass() cls.server = cls.server_behaviors.create_active_server().entity cls.volume_sec = cls.blockstorage_behavior.create_available_volume(size=cls.volume_size, volume_type=cls.volume_type, image_ref=cls.image_ref, timeout=cls....
CreateVolumeServerfromSnapshotTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateVolumeServerfromSnapshotTest: def setUpClass(cls): """Perform actions that setup the necessary resources for testing. The following resources are created during this setup: - Creates an active server. - Creates an available volume from CBS. - Creates an available snapshot. - Create...
stack_v2_sparse_classes_75kplus_train_001362
6,013
permissive
[ { "docstring": "Perform actions that setup the necessary resources for testing. The following resources are created during this setup: - Creates an active server. - Creates an available volume from CBS. - Creates an available snapshot. - Creates an active image. - Creates an available volume from snapshot. - Cr...
3
null
Implement the Python class `CreateVolumeServerfromSnapshotTest` described below. Class description: Implement the CreateVolumeServerfromSnapshotTest class. Method signatures and docstrings: - def setUpClass(cls): Perform actions that setup the necessary resources for testing. The following resources are created durin...
Implement the Python class `CreateVolumeServerfromSnapshotTest` described below. Class description: Implement the CreateVolumeServerfromSnapshotTest class. Method signatures and docstrings: - def setUpClass(cls): Perform actions that setup the necessary resources for testing. The following resources are created durin...
30f0e64672676c3f90b4a582fe90fac6621475b3
<|skeleton|> class CreateVolumeServerfromSnapshotTest: def setUpClass(cls): """Perform actions that setup the necessary resources for testing. The following resources are created during this setup: - Creates an active server. - Creates an available volume from CBS. - Creates an available snapshot. - Create...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CreateVolumeServerfromSnapshotTest: def setUpClass(cls): """Perform actions that setup the necessary resources for testing. The following resources are created during this setup: - Creates an active server. - Creates an available volume from CBS. - Creates an available snapshot. - Creates an active im...
the_stack_v2_python_sparse
cloudroast/compute/integration/volumes/boot_from_volume/v1/images/test_volume_server_from_snapshot.py
RULCSoft/cloudroast
train
1
0da4dbf872686d52e81232857338deaa0950e0e3
[ "self.start = start\nself.stop = stop\nself.step = step", "n = self.start\nwhile n < self.stop:\n yield n\n n += self.step" ]
<|body_start_0|> self.start = start self.stop = stop self.step = step <|end_body_0|> <|body_start_1|> n = self.start while n < self.stop: yield n n += self.step <|end_body_1|>
Create an iterable inexhaustable range-like object. three input parameters: start, stop, step=1 __iter__ but not __next__ is implemented to make objects of this class inexhaustable like range()
IterateMe_2
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IterateMe_2: """Create an iterable inexhaustable range-like object. three input parameters: start, stop, step=1 __iter__ but not __next__ is implemented to make objects of this class inexhaustable like range()""" def __init__(self, start, stop, step=1): """Parameters: start, stop (as...
stack_v2_sparse_classes_75kplus_train_001363
6,278
no_license
[ { "docstring": "Parameters: start, stop (assume > start), step (defaults to 1).", "name": "__init__", "signature": "def __init__(self, start, stop, step=1)" }, { "docstring": "Implement iter with yield statement.", "name": "__iter__", "signature": "def __iter__(self)" } ]
2
null
Implement the Python class `IterateMe_2` described below. Class description: Create an iterable inexhaustable range-like object. three input parameters: start, stop, step=1 __iter__ but not __next__ is implemented to make objects of this class inexhaustable like range() Method signatures and docstrings: - def __init_...
Implement the Python class `IterateMe_2` described below. Class description: Create an iterable inexhaustable range-like object. three input parameters: start, stop, step=1 __iter__ but not __next__ is implemented to make objects of this class inexhaustable like range() Method signatures and docstrings: - def __init_...
eb151196178f27b23911fd937e082034fc17af3f
<|skeleton|> class IterateMe_2: """Create an iterable inexhaustable range-like object. three input parameters: start, stop, step=1 __iter__ but not __next__ is implemented to make objects of this class inexhaustable like range()""" def __init__(self, start, stop, step=1): """Parameters: start, stop (as...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IterateMe_2: """Create an iterable inexhaustable range-like object. three input parameters: start, stop, step=1 __iter__ but not __next__ is implemented to make objects of this class inexhaustable like range()""" def __init__(self, start, stop, step=1): """Parameters: start, stop (assume > start)...
the_stack_v2_python_sparse
students/alex_skrn/Lesson01/iterator_1.py
pinstripezebra/Sp2018-Online
train
0
7d56a6e7634b5bcb2548305e98d87218ce79f5a3
[ "splitified = toParse.split('--------')\nsequence = list(splitified[0].rstrip().strip())\nsequence.insert(0, 'source')\nsequence.append('sink')\navailableStates = splitified[2].rstrip().strip().split()\ntransMatrix = splitified[3].rstrip().strip().splitlines()\nemissionMatrix = splitified[4].rstrip().strip().splitl...
<|body_start_0|> splitified = toParse.split('--------') sequence = list(splitified[0].rstrip().strip()) sequence.insert(0, 'source') sequence.append('sink') availableStates = splitified[2].rstrip().strip().split() transMatrix = splitified[3].rstrip().strip().splitlines() ...
Parses the input file and builds/returns a dictionary of transition probabilities between states and a dictionary of emission probabilties (probability of a sequence given its state)
ForwardBackward
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ForwardBackward: """Parses the input file and builds/returns a dictionary of transition probabilities between states and a dictionary of emission probabilties (probability of a sequence given its state)""" def parseInput(self, toParse): """Takes the input file and parses it the seque...
stack_v2_sparse_classes_75kplus_train_001364
5,166
no_license
[ { "docstring": "Takes the input file and parses it the sequence and states into lists and the transition and emission matrices into dictionaries", "name": "parseInput", "signature": "def parseInput(self, toParse)" }, { "docstring": "Constructs a graph as a dictionary of transition edges with the...
4
null
Implement the Python class `ForwardBackward` described below. Class description: Parses the input file and builds/returns a dictionary of transition probabilities between states and a dictionary of emission probabilties (probability of a sequence given its state) Method signatures and docstrings: - def parseInput(sel...
Implement the Python class `ForwardBackward` described below. Class description: Parses the input file and builds/returns a dictionary of transition probabilities between states and a dictionary of emission probabilties (probability of a sequence given its state) Method signatures and docstrings: - def parseInput(sel...
93d0d0194341dd5a6cd6877fdd8b664a50bd9734
<|skeleton|> class ForwardBackward: """Parses the input file and builds/returns a dictionary of transition probabilities between states and a dictionary of emission probabilties (probability of a sequence given its state)""" def parseInput(self, toParse): """Takes the input file and parses it the seque...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ForwardBackward: """Parses the input file and builds/returns a dictionary of transition probabilities between states and a dictionary of emission probabilties (probability of a sequence given its state)""" def parseInput(self, toParse): """Takes the input file and parses it the sequence and state...
the_stack_v2_python_sparse
Bioinformatics-Algorithms/ubuntu-Seven/problem25.py
ajmak/Bioinformatics-Algorithms
train
0
bf0b1422d15ebe8c48221d55aaab887a3da43790
[ "j.builder.buildenv.install()\nif self.tools.isUbuntu:\n j.builder.system.package.ensure('g++')\nurl = 'https://capnproto.org/capnproto-c++-0.7.0.tar.gz'\nself.tools.file_download(url, to='{}/capnproto'.format(self.DIR_BUILD), overwrite=False, retry=3, expand=True, minsizekb=900, removeTopDir=True, deletedest=Tr...
<|body_start_0|> j.builder.buildenv.install() if self.tools.isUbuntu: j.builder.system.package.ensure('g++') url = 'https://capnproto.org/capnproto-c++-0.7.0.tar.gz' self.tools.file_download(url, to='{}/capnproto'.format(self.DIR_BUILD), overwrite=False, retry=3, expand=True,...
BuilderCapnp
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BuilderCapnp: def build(self): """install capnp kosmos 'j.builder.libs.capnp.build(reset=True)' kosmos 'j.builder.libs.capnp.build()'""" <|body_0|> def install(self): """install capnp kosmos 'j.builder.libs.capnp.install()'""" <|body_1|> def test(self): ...
stack_v2_sparse_classes_75kplus_train_001365
1,668
permissive
[ { "docstring": "install capnp kosmos 'j.builder.libs.capnp.build(reset=True)' kosmos 'j.builder.libs.capnp.build()'", "name": "build", "signature": "def build(self)" }, { "docstring": "install capnp kosmos 'j.builder.libs.capnp.install()'", "name": "install", "signature": "def install(se...
3
stack_v2_sparse_classes_30k_train_047810
Implement the Python class `BuilderCapnp` described below. Class description: Implement the BuilderCapnp class. Method signatures and docstrings: - def build(self): install capnp kosmos 'j.builder.libs.capnp.build(reset=True)' kosmos 'j.builder.libs.capnp.build()' - def install(self): install capnp kosmos 'j.builder....
Implement the Python class `BuilderCapnp` described below. Class description: Implement the BuilderCapnp class. Method signatures and docstrings: - def build(self): install capnp kosmos 'j.builder.libs.capnp.build(reset=True)' kosmos 'j.builder.libs.capnp.build()' - def install(self): install capnp kosmos 'j.builder....
7fff1c40fcd226d33a1df8c89ee35677d62efb22
<|skeleton|> class BuilderCapnp: def build(self): """install capnp kosmos 'j.builder.libs.capnp.build(reset=True)' kosmos 'j.builder.libs.capnp.build()'""" <|body_0|> def install(self): """install capnp kosmos 'j.builder.libs.capnp.install()'""" <|body_1|> def test(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BuilderCapnp: def build(self): """install capnp kosmos 'j.builder.libs.capnp.build(reset=True)' kosmos 'j.builder.libs.capnp.build()'""" j.builder.buildenv.install() if self.tools.isUbuntu: j.builder.system.package.ensure('g++') url = 'https://capnproto.org/capnprot...
the_stack_v2_python_sparse
Jumpscale/builder/libs/BuilderCapnp.py
Pishoy/jumpscaleX
train
0
5a486f85abd0e2ecd39a71b267bac6375bd6f02a
[ "if self.is_empty():\n self.add_first(e)\nelse:\n self.add_after(self.last(), e)", "if self.is_empty():\n self.add_first(e)\nelif self.before(p):\n self.add_after(self.before(p), e)\nelse:\n self.add_first(e)" ]
<|body_start_0|> if self.is_empty(): self.add_first(e) else: self.add_after(self.last(), e) <|end_body_0|> <|body_start_1|> if self.is_empty(): self.add_first(e) elif self.before(p): self.add_after(self.before(p), e) else: ...
PList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PList: def add_last(self, e): """Use methods in the following list to implement this method: {is_empty, first, last, before, after, add_after, add_first}""" <|body_0|> def add_before(self, p, e): """Use methods in the following list to implement this method: {is_empt...
stack_v2_sparse_classes_75kplus_train_001366
982
no_license
[ { "docstring": "Use methods in the following list to implement this method: {is_empty, first, last, before, after, add_after, add_first}", "name": "add_last", "signature": "def add_last(self, e)" }, { "docstring": "Use methods in the following list to implement this method: {is_empty, first, las...
2
null
Implement the Python class `PList` described below. Class description: Implement the PList class. Method signatures and docstrings: - def add_last(self, e): Use methods in the following list to implement this method: {is_empty, first, last, before, after, add_after, add_first} - def add_before(self, p, e): Use method...
Implement the Python class `PList` described below. Class description: Implement the PList class. Method signatures and docstrings: - def add_last(self, e): Use methods in the following list to implement this method: {is_empty, first, last, before, after, add_after, add_first} - def add_before(self, p, e): Use method...
70b23ead7a89e46a84d9d914e7c8fa678edd1f90
<|skeleton|> class PList: def add_last(self, e): """Use methods in the following list to implement this method: {is_empty, first, last, before, after, add_after, add_first}""" <|body_0|> def add_before(self, p, e): """Use methods in the following list to implement this method: {is_empt...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PList: def add_last(self, e): """Use methods in the following list to implement this method: {is_empty, first, last, before, after, add_after, add_first}""" if self.is_empty(): self.add_first(e) else: self.add_after(self.last(), e) def add_before(self, p, e...
the_stack_v2_python_sparse
linded_list_ch07/reinforcement/positional_list_r7_16.py
wanyikang/dsap
train
1
36d62ba9d55f7c9d5af93892648b7a393e06f062
[ "def wrapper(self, *args, **kwargs):\n try:\n return func(self, *args, **kwargs)\n except:\n pubTool = publicTool(self.poco)\n pubTool.allow_permissionBox()\n return func(self, *args, **kwargs)\nreturn wrapper", "pubTool = publicTool(self.poco)\nif pubTool.get_Routetitle() == '选择...
<|body_start_0|> def wrapper(self, *args, **kwargs): try: return func(self, *args, **kwargs) except: pubTool = publicTool(self.poco) pubTool.allow_permissionBox() return func(self, *args, **kwargs) return wrapper <|e...
idcardPage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class idcardPage: def permission(func): """处理权限弹框 :param func: :return:""" <|body_0|> def click_Chinese(self): """选择内地居民""" <|body_1|> def upload_idcardpositive(self): """身份证正面--国徽面""" <|body_2|> def upload_idcardNegative(self): ""...
stack_v2_sparse_classes_75kplus_train_001367
3,249
no_license
[ { "docstring": "处理权限弹框 :param func: :return:", "name": "permission", "signature": "def permission(func)" }, { "docstring": "选择内地居民", "name": "click_Chinese", "signature": "def click_Chinese(self)" }, { "docstring": "身份证正面--国徽面", "name": "upload_idcardpositive", "signature...
4
stack_v2_sparse_classes_30k_train_015614
Implement the Python class `idcardPage` described below. Class description: Implement the idcardPage class. Method signatures and docstrings: - def permission(func): 处理权限弹框 :param func: :return: - def click_Chinese(self): 选择内地居民 - def upload_idcardpositive(self): 身份证正面--国徽面 - def upload_idcardNegative(self): 身份证正面--人...
Implement the Python class `idcardPage` described below. Class description: Implement the idcardPage class. Method signatures and docstrings: - def permission(func): 处理权限弹框 :param func: :return: - def click_Chinese(self): 选择内地居民 - def upload_idcardpositive(self): 身份证正面--国徽面 - def upload_idcardNegative(self): 身份证正面--人...
a741a858ab2ac6bb5e0befbea3a5efa0fe48383a
<|skeleton|> class idcardPage: def permission(func): """处理权限弹框 :param func: :return:""" <|body_0|> def click_Chinese(self): """选择内地居民""" <|body_1|> def upload_idcardpositive(self): """身份证正面--国徽面""" <|body_2|> def upload_idcardNegative(self): ""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class idcardPage: def permission(func): """处理权限弹框 :param func: :return:""" def wrapper(self, *args, **kwargs): try: return func(self, *args, **kwargs) except: pubTool = publicTool(self.poco) pubTool.allow_permissionBox() ...
the_stack_v2_python_sparse
ElementPage/idcardPage.py
sevencrime/airtest-APP
train
0
1bb9db5eb0f6d75336bbc4809832f4967405ae92
[ "try:\n release = Release.objects.get(organization_id=project.organization_id, projects=project, version=version)\nexcept Release.DoesNotExist:\n raise ResourceDoesNotExist\nreturn self.get_releasefile(request, release, file_id, check_permission_fn=lambda: has_download_permission(request, project))", "try:\...
<|body_start_0|> try: release = Release.objects.get(organization_id=project.organization_id, projects=project, version=version) except Release.DoesNotExist: raise ResourceDoesNotExist return self.get_releasefile(request, release, file_id, check_permission_fn=lambda: has_d...
ProjectReleaseFileDetailsEndpoint
[ "Apache-2.0", "BUSL-1.1" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectReleaseFileDetailsEndpoint: def get(self, request: Request, project, version, file_id) -> Response: """Retrieve a Project Release's File ````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file,...
stack_v2_sparse_classes_75kplus_train_001368
10,538
permissive
[ { "docstring": "Retrieve a Project Release's File ````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file, just the associated metadata. :pparam string organization_slug: the slug of the organization the release belongs to. ...
3
stack_v2_sparse_classes_30k_train_009621
Implement the Python class `ProjectReleaseFileDetailsEndpoint` described below. Class description: Implement the ProjectReleaseFileDetailsEndpoint class. Method signatures and docstrings: - def get(self, request: Request, project, version, file_id) -> Response: Retrieve a Project Release's File ``````````````````````...
Implement the Python class `ProjectReleaseFileDetailsEndpoint` described below. Class description: Implement the ProjectReleaseFileDetailsEndpoint class. Method signatures and docstrings: - def get(self, request: Request, project, version, file_id) -> Response: Retrieve a Project Release's File ``````````````````````...
d9dd4f382f96b5c4576b64cbf015db651556c18b
<|skeleton|> class ProjectReleaseFileDetailsEndpoint: def get(self, request: Request, project, version, file_id) -> Response: """Retrieve a Project Release's File ````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file,...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProjectReleaseFileDetailsEndpoint: def get(self, request: Request, project, version, file_id) -> Response: """Retrieve a Project Release's File ````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file, just the asso...
the_stack_v2_python_sparse
src/sentry/api/endpoints/project_release_file_details.py
nagyist/sentry
train
0
4febda9545ec8124687e8d8e80a8f316120030ad
[ "if not isinstance(config.__class__, Config.__class__):\n raise TypeError(f'A config must be an instance of a class that implements AbstractConfig.')\nif not config.validate(workers=IterableRequirement(list, AbstractWorker), hook=MetaTypeRequirement(MetaHook), callback=TypeRequirement(types.MethodType), submissi...
<|body_start_0|> if not isinstance(config.__class__, Config.__class__): raise TypeError(f'A config must be an instance of a class that implements AbstractConfig.') if not config.validate(workers=IterableRequirement(list, AbstractWorker), hook=MetaTypeRequirement(MetaHook), callback=TypeRequi...
MandateWorker
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MandateWorker: def __init__(self, config): """Initializes a mandate worker with a respective config which follows the following guideline: - a common mutable workers-queue:[AbstractWorker] - a hook for the dispatchers - a callback method - submitted data: - a requested payload - a runnin...
stack_v2_sparse_classes_75kplus_train_001369
4,071
no_license
[ { "docstring": "Initializes a mandate worker with a respective config which follows the following guideline: - a common mutable workers-queue:[AbstractWorker] - a hook for the dispatchers - a callback method - submitted data: - a requested payload - a running length - a suspension length :param config::Abstract...
2
stack_v2_sparse_classes_30k_val_002335
Implement the Python class `MandateWorker` described below. Class description: Implement the MandateWorker class. Method signatures and docstrings: - def __init__(self, config): Initializes a mandate worker with a respective config which follows the following guideline: - a common mutable workers-queue:[AbstractWorke...
Implement the Python class `MandateWorker` described below. Class description: Implement the MandateWorker class. Method signatures and docstrings: - def __init__(self, config): Initializes a mandate worker with a respective config which follows the following guideline: - a common mutable workers-queue:[AbstractWorke...
6eeedc6b61247bed79ec4d65e1ef77e89a39352f
<|skeleton|> class MandateWorker: def __init__(self, config): """Initializes a mandate worker with a respective config which follows the following guideline: - a common mutable workers-queue:[AbstractWorker] - a hook for the dispatchers - a callback method - submitted data: - a requested payload - a runnin...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MandateWorker: def __init__(self, config): """Initializes a mandate worker with a respective config which follows the following guideline: - a common mutable workers-queue:[AbstractWorker] - a hook for the dispatchers - a callback method - submitted data: - a requested payload - a running length - a s...
the_stack_v2_python_sparse
application/tool/enumerator/utils/model/worker/mandate.py
VictorJan/Bruteforcer
train
0
18d06109c15b51173d876e3369f003a6570b10cc
[ "super(DirectEncoder, self).__init__()\nfor name, module in feature_modules.iteritems():\n self.add_module('feat-' + name, module)\nself.features = features", "if offset is None:\n embeds = self.features(nodes, mode).t()\n norm = embeds.norm(p=2, dim=0, keepdim=True)\n return embeds.div(norm)\nelse:\n...
<|body_start_0|> super(DirectEncoder, self).__init__() for name, module in feature_modules.iteritems(): self.add_module('feat-' + name, module) self.features = features <|end_body_0|> <|body_start_1|> if offset is None: embeds = self.features(nodes, mode).t() ...
Encodes a node as a embedding via direct lookup. (i.e., this is just like basic node2vec or matrix factorization)
DirectEncoder
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DirectEncoder: """Encodes a node as a embedding via direct lookup. (i.e., this is just like basic node2vec or matrix factorization)""" def __init__(self, features, feature_modules): """Initializes the model for a specific graph. features -- function mapping (node_list, features, offs...
stack_v2_sparse_classes_75kplus_train_001370
34,194
permissive
[ { "docstring": "Initializes the model for a specific graph. features -- function mapping (node_list, features, offset) to feature values see torch.nn.EmbeddingBag and forward function below docs for offset meaning. feature_modules -- This should be a map from mode -> torch.nn.EmbeddingBag features(nodes, mode):...
2
null
Implement the Python class `DirectEncoder` described below. Class description: Encodes a node as a embedding via direct lookup. (i.e., this is just like basic node2vec or matrix factorization) Method signatures and docstrings: - def __init__(self, features, feature_modules): Initializes the model for a specific graph...
Implement the Python class `DirectEncoder` described below. Class description: Encodes a node as a embedding via direct lookup. (i.e., this is just like basic node2vec or matrix factorization) Method signatures and docstrings: - def __init__(self, features, feature_modules): Initializes the model for a specific graph...
0e5a630a8403d4c7965de0f71e2e22b95f7be7bd
<|skeleton|> class DirectEncoder: """Encodes a node as a embedding via direct lookup. (i.e., this is just like basic node2vec or matrix factorization)""" def __init__(self, features, feature_modules): """Initializes the model for a specific graph. features -- function mapping (node_list, features, offs...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DirectEncoder: """Encodes a node as a embedding via direct lookup. (i.e., this is just like basic node2vec or matrix factorization)""" def __init__(self, features, feature_modules): """Initializes the model for a specific graph. features -- function mapping (node_list, features, offset) to featur...
the_stack_v2_python_sparse
graphqa/netquery/encoders.py
Moon-xm/se-kge
train
0
76e461fa0de99880d0b5e6834962986dd7bba102
[ "super(ConvolutionalEncoder, self).__init__()\nself.blocks = nn.ModuleList([Residual3dBlock(in_channels=channel[0], out_channels=channel[1], activation=activation, normalization=normalization, downscale=True, dropout=dropout) for channel in channels])\nself.final_mapping = nn.Sequential(nn.Conv3d(in_channels=channe...
<|body_start_0|> super(ConvolutionalEncoder, self).__init__() self.blocks = nn.ModuleList([Residual3dBlock(in_channels=channel[0], out_channels=channel[1], activation=activation, normalization=normalization, downscale=True, dropout=dropout) for channel in channels]) self.final_mapping = nn.Seque...
This class implements a 3d convolutional encoder for MRI volumes.
ConvolutionalEncoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConvolutionalEncoder: """This class implements a 3d convolutional encoder for MRI volumes.""" def __init__(self, channels: Tuple[Tuple[int, int], ...]=((4, 4), (4, 4), (4, 8), (8, 16), (16, 32)), activation: Type[nn.Module]=nn.ReLU, normalization: Type[nn.Module]=nn.BatchNorm3d, dropout: flo...
stack_v2_sparse_classes_75kplus_train_001371
9,310
permissive
[ { "docstring": "Constructor method :param channels: (Tuple[Tuple[int, int], ...]) Channels (in and out) utilized in each block :param activation: (Type[nn.Module]) Type of activation to be used :param normalization: (Type[nn.Module]) Type of normalization to be used :param dropout: (float) Dropout rate to be ut...
2
stack_v2_sparse_classes_30k_train_030591
Implement the Python class `ConvolutionalEncoder` described below. Class description: This class implements a 3d convolutional encoder for MRI volumes. Method signatures and docstrings: - def __init__(self, channels: Tuple[Tuple[int, int], ...]=((4, 4), (4, 4), (4, 8), (8, 16), (16, 32)), activation: Type[nn.Module]=...
Implement the Python class `ConvolutionalEncoder` described below. Class description: This class implements a 3d convolutional encoder for MRI volumes. Method signatures and docstrings: - def __init__(self, channels: Tuple[Tuple[int, int], ...]=((4, 4), (4, 4), (4, 8), (8, 16), (16, 32)), activation: Type[nn.Module]=...
7d0066990822bf63ac6f40523a53e8ea938cd9a1
<|skeleton|> class ConvolutionalEncoder: """This class implements a 3d convolutional encoder for MRI volumes.""" def __init__(self, channels: Tuple[Tuple[int, int], ...]=((4, 4), (4, 4), (4, 8), (8, 16), (16, 32)), activation: Type[nn.Module]=nn.ReLU, normalization: Type[nn.Module]=nn.BatchNorm3d, dropout: flo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConvolutionalEncoder: """This class implements a 3d convolutional encoder for MRI volumes.""" def __init__(self, channels: Tuple[Tuple[int, int], ...]=((4, 4), (4, 4), (4, 8), (8, 16), (16, 32)), activation: Type[nn.Module]=nn.ReLU, normalization: Type[nn.Module]=nn.BatchNorm3d, dropout: float=0.0, **kwa...
the_stack_v2_python_sparse
oss_net/encoder.py
ChristophReich1996/OSS-Net
train
22
9510a83adeb81c80dd396e63d1d809a7368ae555
[ "scores = Scores.objects.all().values()\nothers = Other.objects.all().values()\nscore = [i for i in scores]\nother = [i for i in others]\nrs = score + other\nresult_dict = defaultdict(dict)\nfor d in rs:\n id_ = d['id']\n result_dict[id_].update(d)\nreturn result_dict.values()", "temp_id = params.get('id', ...
<|body_start_0|> scores = Scores.objects.all().values() others = Other.objects.all().values() score = [i for i in scores] other = [i for i in others] rs = score + other result_dict = defaultdict(dict) for d in rs: id_ = d['id'] result_dict[...
成绩页面处理逻辑
ScoreManage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScoreManage: """成绩页面处理逻辑""" def main_score(cls): """成绩显示的主页面""" <|body_0|> def mark_short(cls, params): """批改简答题部分""" <|body_1|> def save_short_score(cls, params): """传入分数并算总分""" <|body_2|> def record_page(cls, params): "...
stack_v2_sparse_classes_75kplus_train_001372
8,285
no_license
[ { "docstring": "成绩显示的主页面", "name": "main_score", "signature": "def main_score(cls)" }, { "docstring": "批改简答题部分", "name": "mark_short", "signature": "def mark_short(cls, params)" }, { "docstring": "传入分数并算总分", "name": "save_short_score", "signature": "def save_short_score(c...
4
stack_v2_sparse_classes_30k_train_027467
Implement the Python class `ScoreManage` described below. Class description: 成绩页面处理逻辑 Method signatures and docstrings: - def main_score(cls): 成绩显示的主页面 - def mark_short(cls, params): 批改简答题部分 - def save_short_score(cls, params): 传入分数并算总分 - def record_page(cls, params): 回溯页面
Implement the Python class `ScoreManage` described below. Class description: 成绩页面处理逻辑 Method signatures and docstrings: - def main_score(cls): 成绩显示的主页面 - def mark_short(cls, params): 批改简答题部分 - def save_short_score(cls, params): 传入分数并算总分 - def record_page(cls, params): 回溯页面 <|skeleton|> class ScoreManage: """成绩页面...
4febccac57bfa5f7ef46f5f57e52206c8b0a57ac
<|skeleton|> class ScoreManage: """成绩页面处理逻辑""" def main_score(cls): """成绩显示的主页面""" <|body_0|> def mark_short(cls, params): """批改简答题部分""" <|body_1|> def save_short_score(cls, params): """传入分数并算总分""" <|body_2|> def record_page(cls, params): "...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ScoreManage: """成绩页面处理逻辑""" def main_score(cls): """成绩显示的主页面""" scores = Scores.objects.all().values() others = Other.objects.all().values() score = [i for i in scores] other = [i for i in others] rs = score + other result_dict = defaultdict(dict) ...
the_stack_v2_python_sparse
item/interview/backend/utils.py
soulorman/Python
train
0
b216cd0a77b5ae88e58846c90524c662291e2596
[ "d = {}\nfor col in self.__table__.columns:\n value = getattr(self, col.name)\n if issubclass(value.__class__, enum.Enum):\n value = value.name\n elif issubclass(value.__class__, cnaas_nms.db.base.Base):\n continue\n d[col.name] = value\nreturn d", "index_num = 0\nmatch = re.match('^[a-z...
<|body_start_0|> d = {} for col in self.__table__.columns: value = getattr(self, col.name) if issubclass(value.__class__, enum.Enum): value = value.name elif issubclass(value.__class__, cnaas_nms.db.base.Base): continue d[co...
Interface
[ "BSD-2-Clause-Views", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Interface: def as_dict(self) -> dict: """Return JSON serializable dict.""" <|body_0|> def interface_index_num(cls, ifname: str): """Calculate a unique numerical value for a physical interface name Ethernet1 -> 2 Ethernet1/0 -> 201 Ethernet4/3/2/1 -> 5040302 Args: ifn...
stack_v2_sparse_classes_75kplus_train_001373
2,845
permissive
[ { "docstring": "Return JSON serializable dict.", "name": "as_dict", "signature": "def as_dict(self) -> dict" }, { "docstring": "Calculate a unique numerical value for a physical interface name Ethernet1 -> 2 Ethernet1/0 -> 201 Ethernet4/3/2/1 -> 5040302 Args: ifname: interface name, ex Ethernet1...
2
null
Implement the Python class `Interface` described below. Class description: Implement the Interface class. Method signatures and docstrings: - def as_dict(self) -> dict: Return JSON serializable dict. - def interface_index_num(cls, ifname: str): Calculate a unique numerical value for a physical interface name Ethernet...
Implement the Python class `Interface` described below. Class description: Implement the Interface class. Method signatures and docstrings: - def as_dict(self) -> dict: Return JSON serializable dict. - def interface_index_num(cls, ifname: str): Calculate a unique numerical value for a physical interface name Ethernet...
d755dfed69bebe0c7bea66ad1802cba2cd89fec8
<|skeleton|> class Interface: def as_dict(self) -> dict: """Return JSON serializable dict.""" <|body_0|> def interface_index_num(cls, ifname: str): """Calculate a unique numerical value for a physical interface name Ethernet1 -> 2 Ethernet1/0 -> 201 Ethernet4/3/2/1 -> 5040302 Args: ifn...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Interface: def as_dict(self) -> dict: """Return JSON serializable dict.""" d = {} for col in self.__table__.columns: value = getattr(self, col.name) if issubclass(value.__class__, enum.Enum): value = value.name elif issubclass(value._...
the_stack_v2_python_sparse
src/cnaas_nms/db/interface.py
SUNET/cnaas-nms
train
67
5c1c6cf1f359088b42e0965fa4ac36b2439efe41
[ "super(RKDLoss, self).__init__()\nself.distance_loss_weight = distance_loss_weight\nself.angle_loss_weight = angle_loss_weight", "if self.distance_loss_weight > 0:\n with torch.no_grad():\n t_dist = self.pdist(feature_teacher, squared=False)\n mean_td = t_dist[t_dist > 0].mean()\n t_dist =...
<|body_start_0|> super(RKDLoss, self).__init__() self.distance_loss_weight = distance_loss_weight self.angle_loss_weight = angle_loss_weight <|end_body_0|> <|body_start_1|> if self.distance_loss_weight > 0: with torch.no_grad(): t_dist = self.pdist(feature_te...
Compute RKD Distance Loss. Paper Refer to: Relational Knowledge Disitllation, CVPR2019. https://arxiv.org/abs/1904.05068 Code Refer to: https://github.com/HobbitLong/RepDistiller/blob/master/distiller_zoo/RKD.py and https://github.com/lenscloth/RKD/blob/master/metric/loss.py
RKDLoss
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RKDLoss: """Compute RKD Distance Loss. Paper Refer to: Relational Knowledge Disitllation, CVPR2019. https://arxiv.org/abs/1904.05068 Code Refer to: https://github.com/HobbitLong/RepDistiller/blob/master/distiller_zoo/RKD.py and https://github.com/lenscloth/RKD/blob/master/metric/loss.py""" d...
stack_v2_sparse_classes_75kplus_train_001374
12,454
permissive
[ { "docstring": "Parameters ---------- distance_loss_weight Weight of RKD distance loss angle_loss_weight Weight of RKD angle loss Returns -------", "name": "__init__", "signature": "def __init__(self, distance_loss_weight: Optional[float]=25.0, angle_loss_weight: Optional[float]=50.0)" }, { "doc...
3
null
Implement the Python class `RKDLoss` described below. Class description: Compute RKD Distance Loss. Paper Refer to: Relational Knowledge Disitllation, CVPR2019. https://arxiv.org/abs/1904.05068 Code Refer to: https://github.com/HobbitLong/RepDistiller/blob/master/distiller_zoo/RKD.py and https://github.com/lenscloth/R...
Implement the Python class `RKDLoss` described below. Class description: Compute RKD Distance Loss. Paper Refer to: Relational Knowledge Disitllation, CVPR2019. https://arxiv.org/abs/1904.05068 Code Refer to: https://github.com/HobbitLong/RepDistiller/blob/master/distiller_zoo/RKD.py and https://github.com/lenscloth/R...
6af92e149491f6e5062495d87306b3625d12d992
<|skeleton|> class RKDLoss: """Compute RKD Distance Loss. Paper Refer to: Relational Knowledge Disitllation, CVPR2019. https://arxiv.org/abs/1904.05068 Code Refer to: https://github.com/HobbitLong/RepDistiller/blob/master/distiller_zoo/RKD.py and https://github.com/lenscloth/RKD/blob/master/metric/loss.py""" d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RKDLoss: """Compute RKD Distance Loss. Paper Refer to: Relational Knowledge Disitllation, CVPR2019. https://arxiv.org/abs/1904.05068 Code Refer to: https://github.com/HobbitLong/RepDistiller/blob/master/distiller_zoo/RKD.py and https://github.com/lenscloth/RKD/blob/master/metric/loss.py""" def __init__(s...
the_stack_v2_python_sparse
multimodal/src/autogluon/multimodal/optimization/losses.py
stjordanis/autogluon
train
0
bd3b7fbed6a091f1c8f2fe64d9510d4a7534ff00
[ "assert len(data) == len(labels), 'Unmatchable dataset!'\nassert K <= len(data), 'K is over size!'\nself.dataset = np.array(data)\nself.labels = labels\nself.num = len(self.dataset)\nself.K = K", "euclidean_distance = []\nfor i in range(self.num):\n euclidean_distance.append((np.sqrt((self.dataset[i][0] - samp...
<|body_start_0|> assert len(data) == len(labels), 'Unmatchable dataset!' assert K <= len(data), 'K is over size!' self.dataset = np.array(data) self.labels = labels self.num = len(self.dataset) self.K = K <|end_body_0|> <|body_start_1|> euclidean_distance = [] ...
KNN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KNN: def __init__(self, data, labels: List, K=9): """:param data: 训练集数据,[(x1, y1), (x2, y2), ... ] :param labels: 训练集标注,与data对应, [label1, label2, ... ] :param K: 统计的邻居数""" <|body_0|> def predict(self, sample): """预测sample所属的类别""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_75kplus_train_001375
2,643
no_license
[ { "docstring": ":param data: 训练集数据,[(x1, y1), (x2, y2), ... ] :param labels: 训练集标注,与data对应, [label1, label2, ... ] :param K: 统计的邻居数", "name": "__init__", "signature": "def __init__(self, data, labels: List, K=9)" }, { "docstring": "预测sample所属的类别", "name": "predict", "signature": "def pre...
2
stack_v2_sparse_classes_30k_train_051375
Implement the Python class `KNN` described below. Class description: Implement the KNN class. Method signatures and docstrings: - def __init__(self, data, labels: List, K=9): :param data: 训练集数据,[(x1, y1), (x2, y2), ... ] :param labels: 训练集标注,与data对应, [label1, label2, ... ] :param K: 统计的邻居数 - def predict(self, sample)...
Implement the Python class `KNN` described below. Class description: Implement the KNN class. Method signatures and docstrings: - def __init__(self, data, labels: List, K=9): :param data: 训练集数据,[(x1, y1), (x2, y2), ... ] :param labels: 训练集标注,与data对应, [label1, label2, ... ] :param K: 统计的邻居数 - def predict(self, sample)...
2a906dd94e9b092d201eb7fdb078f56ed7eefce0
<|skeleton|> class KNN: def __init__(self, data, labels: List, K=9): """:param data: 训练集数据,[(x1, y1), (x2, y2), ... ] :param labels: 训练集标注,与data对应, [label1, label2, ... ] :param K: 统计的邻居数""" <|body_0|> def predict(self, sample): """预测sample所属的类别""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KNN: def __init__(self, data, labels: List, K=9): """:param data: 训练集数据,[(x1, y1), (x2, y2), ... ] :param labels: 训练集标注,与data对应, [label1, label2, ... ] :param K: 统计的邻居数""" assert len(data) == len(labels), 'Unmatchable dataset!' assert K <= len(data), 'K is over size!' self.data...
the_stack_v2_python_sparse
《算法之美》/MachineLearning-KNN.py
noob-cod/Algorithm-python
train
0
a9e3593ebca8db719cb0f34061d85471d2e40b4e
[ "super().__init__()\nself.fc_x = nn.Linear(x_size, self.hidden_units[0])\nself.fc_y = nn.Linear(y_size, self.hidden_units[0])\nfc_hidden = []\nfor in_features, out_features in zip(self.hidden_units[0:], self.hidden_units[1:]):\n fc_hidden.append(nn.Linear(in_features=in_features, out_features=out_features))\nsel...
<|body_start_0|> super().__init__() self.fc_x = nn.Linear(x_size, self.hidden_units[0]) self.fc_y = nn.Linear(y_size, self.hidden_units[0]) fc_hidden = [] for in_features, out_features in zip(self.hidden_units[0:], self.hidden_units[1:]): fc_hidden.append(nn.Linear(in...
https://arxiv.org/pdf/1801.04062.pdf
MutualInfoNeuralEstimationNetwork
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MutualInfoNeuralEstimationNetwork: """https://arxiv.org/pdf/1801.04062.pdf""" def __init__(self, x_size: int, y_size: int): """:param x_size: hidden layer shape :param y_size: input/target data shape""" <|body_0|> def forward(self, x, y): """:param x: some hidden...
stack_v2_sparse_classes_75kplus_train_001376
10,285
permissive
[ { "docstring": ":param x_size: hidden layer shape :param y_size: input/target data shape", "name": "__init__", "signature": "def __init__(self, x_size: int, y_size: int)" }, { "docstring": ":param x: some hidden layer batch activations of shape (batch_size, embedding_size) :param y: either input...
2
stack_v2_sparse_classes_30k_train_043336
Implement the Python class `MutualInfoNeuralEstimationNetwork` described below. Class description: https://arxiv.org/pdf/1801.04062.pdf Method signatures and docstrings: - def __init__(self, x_size: int, y_size: int): :param x_size: hidden layer shape :param y_size: input/target data shape - def forward(self, x, y): ...
Implement the Python class `MutualInfoNeuralEstimationNetwork` described below. Class description: https://arxiv.org/pdf/1801.04062.pdf Method signatures and docstrings: - def __init__(self, x_size: int, y_size: int): :param x_size: hidden layer shape :param y_size: input/target data shape - def forward(self, x, y): ...
9777075d6bb15ee0215a62fb0bf6ed5247a9e58e
<|skeleton|> class MutualInfoNeuralEstimationNetwork: """https://arxiv.org/pdf/1801.04062.pdf""" def __init__(self, x_size: int, y_size: int): """:param x_size: hidden layer shape :param y_size: input/target data shape""" <|body_0|> def forward(self, x, y): """:param x: some hidden...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MutualInfoNeuralEstimationNetwork: """https://arxiv.org/pdf/1801.04062.pdf""" def __init__(self, x_size: int, y_size: int): """:param x_size: hidden layer shape :param y_size: input/target data shape""" super().__init__() self.fc_x = nn.Linear(x_size, self.hidden_units[0]) ...
the_stack_v2_python_sparse
monitor/mutual_info/neural_estimation.py
hronoses/EmbedderSDR
train
0
cbccd7f63b292b12037f6fa05b62befee0b6a20a
[ "self.tik_instance = tik.Tik(tik.Dprofile())\nself.aicore_num = cce.cce_conf.get_soc_spec(cce.cce_conf.CORE_NUM)\nself.shape = list(shape)\nself.dtype = dtype\nself.kernel_name = kernel_name\nblock_byte_size = 32\ndtype_byte_size = cce.cce_intrin.get_bit_len(dtype) // 8\nself.data_each_block = block_byte_size // dt...
<|body_start_0|> self.tik_instance = tik.Tik(tik.Dprofile()) self.aicore_num = cce.cce_conf.get_soc_spec(cce.cce_conf.CORE_NUM) self.shape = list(shape) self.dtype = dtype self.kernel_name = kernel_name block_byte_size = 32 dtype_byte_size = cce.cce_intrin.get_bit...
Function: move the data from gm to gm via ub
MoveFromGm2Gm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MoveFromGm2Gm: """Function: move the data from gm to gm via ub""" def __init__(self, shape, dtype, kernel_name): """init the parameters Parameters ---------- shape: tuple or list the shape of input tensor dtype: string the dtype of input tensor kernel_name: str kernel name, default v...
stack_v2_sparse_classes_75kplus_train_001377
39,050
no_license
[ { "docstring": "init the parameters Parameters ---------- shape: tuple or list the shape of input tensor dtype: string the dtype of input tensor kernel_name: str kernel name, default value is \"reverse_ext2\" Returns ------- None", "name": "__init__", "signature": "def __init__(self, shape, dtype, kerne...
5
stack_v2_sparse_classes_30k_train_012455
Implement the Python class `MoveFromGm2Gm` described below. Class description: Function: move the data from gm to gm via ub Method signatures and docstrings: - def __init__(self, shape, dtype, kernel_name): init the parameters Parameters ---------- shape: tuple or list the shape of input tensor dtype: string the dtyp...
Implement the Python class `MoveFromGm2Gm` described below. Class description: Function: move the data from gm to gm via ub Method signatures and docstrings: - def __init__(self, shape, dtype, kernel_name): init the parameters Parameters ---------- shape: tuple or list the shape of input tensor dtype: string the dtyp...
148511a31bfd195df889291946c43bb585acb546
<|skeleton|> class MoveFromGm2Gm: """Function: move the data from gm to gm via ub""" def __init__(self, shape, dtype, kernel_name): """init the parameters Parameters ---------- shape: tuple or list the shape of input tensor dtype: string the dtype of input tensor kernel_name: str kernel name, default v...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MoveFromGm2Gm: """Function: move the data from gm to gm via ub""" def __init__(self, shape, dtype, kernel_name): """init the parameters Parameters ---------- shape: tuple or list the shape of input tensor dtype: string the dtype of input tensor kernel_name: str kernel name, default value is "reve...
the_stack_v2_python_sparse
convertor/huawei/impl/reverse_v2_d.py
jizhuoran/caffe-huawei-atlas-convertor
train
4
6be7b4569a4ded2ec185a27a8966a83f2b369e4c
[ "super().__init__(model, nb_epochs, mini_batch_size, lr, criterion)\nif not isinstance(b1, float) or not 0 <= b1 <= 1:\n raise ValueError('Beta 1 must be a float in [0, 1]')\nif not isinstance(b2, float) or not 0 <= b2 <= 1:\n raise ValueError('Beta 2 must be a float in [0, 1]')\nif not isinstance(epsilon, fl...
<|body_start_0|> super().__init__(model, nb_epochs, mini_batch_size, lr, criterion) if not isinstance(b1, float) or not 0 <= b1 <= 1: raise ValueError('Beta 1 must be a float in [0, 1]') if not isinstance(b2, float) or not 0 <= b2 <= 1: raise ValueError('Beta 2 must be a ...
Class implementing mini-batch Adam optimization
Adam
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Adam: """Class implementing mini-batch Adam optimization""" def __init__(self, model, nb_epochs=50, mini_batch_size=1, lr=0.001, criterion=LossMSE(), b1=0.9, b2=0.999, epsilon=1e-08): """Adam constructor :param model: the model to train, models.Sequential object (only one currently p...
stack_v2_sparse_classes_75kplus_train_001378
8,106
no_license
[ { "docstring": "Adam constructor :param model: the model to train, models.Sequential object (only one currently possible) :param nb_epochs: maximum number of training epochs, positive int, optional, default is 50 :param mini_batch_size: number of samples per mini-batch, int in [1, num_train_samples], optional, ...
2
null
Implement the Python class `Adam` described below. Class description: Class implementing mini-batch Adam optimization Method signatures and docstrings: - def __init__(self, model, nb_epochs=50, mini_batch_size=1, lr=0.001, criterion=LossMSE(), b1=0.9, b2=0.999, epsilon=1e-08): Adam constructor :param model: the model...
Implement the Python class `Adam` described below. Class description: Class implementing mini-batch Adam optimization Method signatures and docstrings: - def __init__(self, model, nb_epochs=50, mini_batch_size=1, lr=0.001, criterion=LossMSE(), b1=0.9, b2=0.999, epsilon=1e-08): Adam constructor :param model: the model...
ff82572e5a7f7df12fca5a79f07fc260afe70209
<|skeleton|> class Adam: """Class implementing mini-batch Adam optimization""" def __init__(self, model, nb_epochs=50, mini_batch_size=1, lr=0.001, criterion=LossMSE(), b1=0.9, b2=0.999, epsilon=1e-08): """Adam constructor :param model: the model to train, models.Sequential object (only one currently p...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Adam: """Class implementing mini-batch Adam optimization""" def __init__(self, model, nb_epochs=50, mini_batch_size=1, lr=0.001, criterion=LossMSE(), b1=0.9, b2=0.999, epsilon=1e-08): """Adam constructor :param model: the model to train, models.Sequential object (only one currently possible) :par...
the_stack_v2_python_sparse
Proj2/train.py
Nic9407/DeepLearning-EPFL
train
0
ba289cd7d160fcd3ba650825071d46f3cd95dc7d
[ "self._cvm = config['cvm']\nself._name = config['name']\nself._slots = [str(slot) for slot in config['slots']]\nself._mf_dim = config['mf_dim']\nself._backward = config['backward']\nself._emb_dim = self._mf_dim + 3\nself._emb_layers = []", "show_clk = fluid.layers.concat([param['layer']['show'], param['layer']['c...
<|body_start_0|> self._cvm = config['cvm'] self._name = config['name'] self._slots = [str(slot) for slot in config['slots']] self._mf_dim = config['mf_dim'] self._backward = config['backward'] self._emb_dim = self._mf_dim + 3 self._emb_layers = [] <|end_body_0|> ...
embedding + sequence + concat
EmbeddingFuseLayer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmbeddingFuseLayer: """embedding + sequence + concat""" def __init__(self, config): """R""" <|body_0|> def generate(self, param): """R""" <|body_1|> <|end_skeleton|> <|body_start_0|> self._cvm = config['cvm'] self._name = config['name'] ...
stack_v2_sparse_classes_75kplus_train_001379
10,717
permissive
[ { "docstring": "R", "name": "__init__", "signature": "def __init__(self, config)" }, { "docstring": "R", "name": "generate", "signature": "def generate(self, param)" } ]
2
null
Implement the Python class `EmbeddingFuseLayer` described below. Class description: embedding + sequence + concat Method signatures and docstrings: - def __init__(self, config): R - def generate(self, param): R
Implement the Python class `EmbeddingFuseLayer` described below. Class description: embedding + sequence + concat Method signatures and docstrings: - def __init__(self, config): R - def generate(self, param): R <|skeleton|> class EmbeddingFuseLayer: """embedding + sequence + concat""" def __init__(self, con...
98872470969ab640de1a76d295b93ae155519ecd
<|skeleton|> class EmbeddingFuseLayer: """embedding + sequence + concat""" def __init__(self, config): """R""" <|body_0|> def generate(self, param): """R""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EmbeddingFuseLayer: """embedding + sequence + concat""" def __init__(self, config): """R""" self._cvm = config['cvm'] self._name = config['name'] self._slots = [str(slot) for slot in config['slots']] self._mf_dim = config['mf_dim'] self._backward = config['...
the_stack_v2_python_sparse
core/modules/modul/layers.py
frankwhzhang/PaddleRec
train
3
fe6183ae51829d4cd615e3be642be74de34b7af6
[ "super().__init__(**kwargs)\nself.model = self.build_model(self.feature_shape, self.data.num_classes, **kwargs)\nself.set_logger()\nprint(self.model.summary())\nif self.data is not None:\n print('Training set size: %d; Validation set size: %d' % (self.get_training_data_size(), self.get_validation_data_size()))",...
<|body_start_0|> super().__init__(**kwargs) self.model = self.build_model(self.feature_shape, self.data.num_classes, **kwargs) self.set_logger() print(self.model.summary()) if self.data is not None: print('Training set size: %d; Validation set size: %d' % (self.get_tr...
A basic convolutional neural network model.
KerasCNN
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-protobuf", "Apache-2.0", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KerasCNN: """A basic convolutional neural network model.""" def __init__(self, **kwargs): """Initializer Args: **kwargs: Additional parameters to pass to the function""" <|body_0|> def build_model(self, input_shape, num_classes, conv_kernel_size=(4, 4), conv_strides=(2, ...
stack_v2_sparse_classes_75kplus_train_001380
3,114
permissive
[ { "docstring": "Initializer Args: **kwargs: Additional parameters to pass to the function", "name": "__init__", "signature": "def __init__(self, **kwargs)" }, { "docstring": "Define the model architecture. Args: input_shape (numpy.ndarray): The shape of the data num_classes (int): The number of ...
2
stack_v2_sparse_classes_30k_train_033008
Implement the Python class `KerasCNN` described below. Class description: A basic convolutional neural network model. Method signatures and docstrings: - def __init__(self, **kwargs): Initializer Args: **kwargs: Additional parameters to pass to the function - def build_model(self, input_shape, num_classes, conv_kerne...
Implement the Python class `KerasCNN` described below. Class description: A basic convolutional neural network model. Method signatures and docstrings: - def __init__(self, **kwargs): Initializer Args: **kwargs: Additional parameters to pass to the function - def build_model(self, input_shape, num_classes, conv_kerne...
d8e2d22dfccfb8488f70f1fb5593d4e6ee1eca1f
<|skeleton|> class KerasCNN: """A basic convolutional neural network model.""" def __init__(self, **kwargs): """Initializer Args: **kwargs: Additional parameters to pass to the function""" <|body_0|> def build_model(self, input_shape, num_classes, conv_kernel_size=(4, 4), conv_strides=(2, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KerasCNN: """A basic convolutional neural network model.""" def __init__(self, **kwargs): """Initializer Args: **kwargs: Additional parameters to pass to the function""" super().__init__(**kwargs) self.model = self.build_model(self.feature_shape, self.data.num_classes, **kwargs) ...
the_stack_v2_python_sparse
openfl/models/tensorflow/keras_cnn/keras_cnn.py
sbakas/OpenFederatedLearning-1
train
0
54581552b7ca7416920e3e8caf13da8e89da3d02
[ "self.zoneType = zoneType\nself.filter = filter\nself.thenEffects = thenEffects", "zone = context.loadZone(self.zoneType)\npossibleCards = self.filter.evaluate(context)\nevent = CardsEvent(possibleCards, zone, context)\ncoroutine = PerformEffects(self.thenEffects, event.context)\nresponse = (yield coroutine.next(...
<|body_start_0|> self.zoneType = zoneType self.filter = filter self.thenEffects = thenEffects <|end_body_0|> <|body_start_1|> zone = context.loadZone(self.zoneType) possibleCards = self.filter.evaluate(context) event = CardsEvent(possibleCards, zone, context) cor...
Represents an effect to pick cards from a zone and an optional filter
Filter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Filter: """Represents an effect to pick cards from a zone and an optional filter""" def __init__(self, zoneType, filter, thenEffects): """Initialize the options""" <|body_0|> def perform(self, context): """Perform the Game Effect""" <|body_1|> <|end_skel...
stack_v2_sparse_classes_75kplus_train_001381
858
no_license
[ { "docstring": "Initialize the options", "name": "__init__", "signature": "def __init__(self, zoneType, filter, thenEffects)" }, { "docstring": "Perform the Game Effect", "name": "perform", "signature": "def perform(self, context)" } ]
2
stack_v2_sparse_classes_30k_train_009245
Implement the Python class `Filter` described below. Class description: Represents an effect to pick cards from a zone and an optional filter Method signatures and docstrings: - def __init__(self, zoneType, filter, thenEffects): Initialize the options - def perform(self, context): Perform the Game Effect
Implement the Python class `Filter` described below. Class description: Represents an effect to pick cards from a zone and an optional filter Method signatures and docstrings: - def __init__(self, zoneType, filter, thenEffects): Initialize the options - def perform(self, context): Perform the Game Effect <|skeleton|...
0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258
<|skeleton|> class Filter: """Represents an effect to pick cards from a zone and an optional filter""" def __init__(self, zoneType, filter, thenEffects): """Initialize the options""" <|body_0|> def perform(self, context): """Perform the Game Effect""" <|body_1|> <|end_skel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Filter: """Represents an effect to pick cards from a zone and an optional filter""" def __init__(self, zoneType, filter, thenEffects): """Initialize the options""" self.zoneType = zoneType self.filter = filter self.thenEffects = thenEffects def perform(self, context):...
the_stack_v2_python_sparse
src/Game/Effects/filter.py
dfwarden/DeckBuilding
train
0
d3c4973ebb4599aae04a88b822e28d65139846dc
[ "active_object = context.active_object\nif active_object and active_object.type == 'ARMATURE' and active_object.animation_data:\n action = active_object.animation_data.action\n if action:\n _animation_utils.set_fps_for_preview(context.scene, self.length, self.anim_start, self.anim_end)", "active_obje...
<|body_start_0|> active_object = context.active_object if active_object and active_object.type == 'ARMATURE' and active_object.animation_data: action = active_object.animation_data.action if action: _animation_utils.set_fps_for_preview(context.scene, self.length, ...
Animation property inventory, which gets saved into *.blend file.
ObjectAnimationInventoryItem
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObjectAnimationInventoryItem: """Animation property inventory, which gets saved into *.blend file.""" def length_update(self, context): """If the total time for animation is tweaked, FPS value is recalculated to keep the playback speed as close as possible to the resulting playback s...
stack_v2_sparse_classes_75kplus_train_001382
48,834
no_license
[ { "docstring": "If the total time for animation is tweaked, FPS value is recalculated to keep the playback speed as close as possible to the resulting playback speed in the game engine. :param context: Blender Context :type context: bpy.types.Context", "name": "length_update", "signature": "def length_u...
3
stack_v2_sparse_classes_30k_train_010420
Implement the Python class `ObjectAnimationInventoryItem` described below. Class description: Animation property inventory, which gets saved into *.blend file. Method signatures and docstrings: - def length_update(self, context): If the total time for animation is tweaked, FPS value is recalculated to keep the playba...
Implement the Python class `ObjectAnimationInventoryItem` described below. Class description: Animation property inventory, which gets saved into *.blend file. Method signatures and docstrings: - def length_update(self, context): If the total time for animation is tweaked, FPS value is recalculated to keep the playba...
7b796d30dfd22b7706a93e4419ed913d18d29a44
<|skeleton|> class ObjectAnimationInventoryItem: """Animation property inventory, which gets saved into *.blend file.""" def length_update(self, context): """If the total time for animation is tweaked, FPS value is recalculated to keep the playback speed as close as possible to the resulting playback s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ObjectAnimationInventoryItem: """Animation property inventory, which gets saved into *.blend file.""" def length_update(self, context): """If the total time for animation is tweaked, FPS value is recalculated to keep the playback speed as close as possible to the resulting playback speed in the g...
the_stack_v2_python_sparse
All_In_One/addons/io_scs_tools/properties/object.py
2434325680/Learnbgame
train
0
611b84c36bee10e39968b29376b6f74735da43fe
[ "super().__init__(option_strings=option_strings, dest=dest, nargs=nargs, const=const, default=default, type=type, choices=choices, required=required, help=help, metavar=metavar)\nif hasattr(signal, 'Signals'):\n\n def _signal_number(signame):\n cooked = 'SIG{}'.format(signame)\n try:\n r...
<|body_start_0|> super().__init__(option_strings=option_strings, dest=dest, nargs=nargs, const=const, default=default, type=type, choices=choices, required=required, help=help, metavar=metavar) if hasattr(signal, 'Signals'): def _signal_number(signame): cooked = 'SIG{}'.form...
Validate input as a signal.
SignalAction
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignalAction: """Validate input as a signal.""" def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=str, choices=None, required=False, help='The signal to send. It may be given as a name or a number.', metavar='SIGNAL'): """Create SignalAction object."...
stack_v2_sparse_classes_75kplus_train_001383
7,908
permissive
[ { "docstring": "Create SignalAction object.", "name": "__init__", "signature": "def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=str, choices=None, required=False, help='The signal to send. It may be given as a name or a number.', metavar='SIGNAL')" }, { "docst...
2
stack_v2_sparse_classes_30k_train_047984
Implement the Python class `SignalAction` described below. Class description: Validate input as a signal. Method signatures and docstrings: - def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=str, choices=None, required=False, help='The signal to send. It may be given as a name or a ...
Implement the Python class `SignalAction` described below. Class description: Validate input as a signal. Method signatures and docstrings: - def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=str, choices=None, required=False, help='The signal to send. It may be given as a name or a ...
94a46127cb0db2b6187186788a941ec72af476dd
<|skeleton|> class SignalAction: """Validate input as a signal.""" def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=str, choices=None, required=False, help='The signal to send. It may be given as a name or a number.', metavar='SIGNAL'): """Create SignalAction object."...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SignalAction: """Validate input as a signal.""" def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=str, choices=None, required=False, help='The signal to send. It may be given as a name or a number.', metavar='SIGNAL'): """Create SignalAction object.""" su...
the_stack_v2_python_sparse
pypodman/pypodman/lib/parser_actions.py
4383/python-podman
train
0
1ba3dc14fb641f05813677091a0c053fdcf290f0
[ "maxprofit = 0\nfor i in range(i, len(prices)):\n tmp = prices[i] - prices[i - 1]\n if tmp > 0:\n maxprofit += tmp\nreturn maxprofit", "if len(prices) < 2:\n return 0\ndp = [[0, 0]] * len(prices)\ndp[0][0], dp[0][1] = (0, -prices[0])\nfor i in range(1, len(prices)):\n dp[i][0] = max(dp[i - 1][0...
<|body_start_0|> maxprofit = 0 for i in range(i, len(prices)): tmp = prices[i] - prices[i - 1] if tmp > 0: maxprofit += tmp return maxprofit <|end_body_0|> <|body_start_1|> if len(prices) < 2: return 0 dp = [[0, 0]] * len(price...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit1(self, prices: List[int]) -> int: """贪心 股票买卖策略 单独交易日:设今天价格为p1,明天价格为p2,则今天买入,明天卖出 可赚取金额p2-p1(负值代表亏损) 连续上涨交易日:设此上涨交易日股票价格分别为p1, p2, pn,则第一 天买最后一天卖收益最大,即 pn-p1,;等价于每天都买卖,即 pn-p1 = p2-p1 + p3-p2+...+pn-pn-1 连续下降交易日:则不买卖收益最大,即不会亏钱 算法流程: 遍历整个股票交易日价格列表price,策略是所有上涨交易日都买卖...
stack_v2_sparse_classes_75kplus_train_001384
5,779
no_license
[ { "docstring": "贪心 股票买卖策略 单独交易日:设今天价格为p1,明天价格为p2,则今天买入,明天卖出 可赚取金额p2-p1(负值代表亏损) 连续上涨交易日:设此上涨交易日股票价格分别为p1, p2, pn,则第一 天买最后一天卖收益最大,即 pn-p1,;等价于每天都买卖,即 pn-p1 = p2-p1 + p3-p2+...+pn-pn-1 连续下降交易日:则不买卖收益最大,即不会亏钱 算法流程: 遍历整个股票交易日价格列表price,策略是所有上涨交易日都买卖(转到 所有的利润),所有下降交易日都不买卖(永不亏钱) 1,设tmp为第 i-1 日买入与第 i 日卖出赚取的利润, 2,当该天利润为正...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit1(self, prices: List[int]) -> int: 贪心 股票买卖策略 单独交易日:设今天价格为p1,明天价格为p2,则今天买入,明天卖出 可赚取金额p2-p1(负值代表亏损) 连续上涨交易日:设此上涨交易日股票价格分别为p1, p2, pn,则第一 天买最后一天卖收益最大,即 pn-p1,;等价于每天都买卖,...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit1(self, prices: List[int]) -> int: 贪心 股票买卖策略 单独交易日:设今天价格为p1,明天价格为p2,则今天买入,明天卖出 可赚取金额p2-p1(负值代表亏损) 连续上涨交易日:设此上涨交易日股票价格分别为p1, p2, pn,则第一 天买最后一天卖收益最大,即 pn-p1,;等价于每天都买卖,...
51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a
<|skeleton|> class Solution: def maxProfit1(self, prices: List[int]) -> int: """贪心 股票买卖策略 单独交易日:设今天价格为p1,明天价格为p2,则今天买入,明天卖出 可赚取金额p2-p1(负值代表亏损) 连续上涨交易日:设此上涨交易日股票价格分别为p1, p2, pn,则第一 天买最后一天卖收益最大,即 pn-p1,;等价于每天都买卖,即 pn-p1 = p2-p1 + p3-p2+...+pn-pn-1 连续下降交易日:则不买卖收益最大,即不会亏钱 算法流程: 遍历整个股票交易日价格列表price,策略是所有上涨交易日都买卖...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxProfit1(self, prices: List[int]) -> int: """贪心 股票买卖策略 单独交易日:设今天价格为p1,明天价格为p2,则今天买入,明天卖出 可赚取金额p2-p1(负值代表亏损) 连续上涨交易日:设此上涨交易日股票价格分别为p1, p2, pn,则第一 天买最后一天卖收益最大,即 pn-p1,;等价于每天都买卖,即 pn-p1 = p2-p1 + p3-p2+...+pn-pn-1 连续下降交易日:则不买卖收益最大,即不会亏钱 算法流程: 遍历整个股票交易日价格列表price,策略是所有上涨交易日都买卖(转到 所有的利润),所有下...
the_stack_v2_python_sparse
LeetCode_practice/DynamicProgramming/0122_BestTimeToBuyAndSellStock_2.py
LeBron-Jian/BasicAlgorithmPractice
train
13
d5cdf8967413792ddac5e425bf79d23e43d52f0f
[ "self._coef_proportional = proportional\nself._coef_integral = integral\nself._coef_derivative = derivative\nself._integral_discounting = integral_discounting_per_step\nself._dt = unit_time_per_step\nself._previous_error = None\nself._error_integral = 0.0", "error_integral = self._error_integral\nerror_integral *...
<|body_start_0|> self._coef_proportional = proportional self._coef_integral = integral self._coef_derivative = derivative self._integral_discounting = integral_discounting_per_step self._dt = unit_time_per_step self._previous_error = None self._error_integral = 0....
PidController
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PidController: def __init__(self, unit_time_per_step, proportional=1.0, integral=0.0, derivative=0.0, integral_discounting_per_step=0.0): """A basic PID controller with integral discounting. :param integral_discounting_per_step: The multiplier with which to discount the control error int...
stack_v2_sparse_classes_75kplus_train_001385
8,781
permissive
[ { "docstring": "A basic PID controller with integral discounting. :param integral_discounting_per_step: The multiplier with which to discount the control error integral. Must be between 0.0 (no discounting) and 1.0 (only consider the latest error value).", "name": "__init__", "signature": "def __init__(...
2
null
Implement the Python class `PidController` described below. Class description: Implement the PidController class. Method signatures and docstrings: - def __init__(self, unit_time_per_step, proportional=1.0, integral=0.0, derivative=0.0, integral_discounting_per_step=0.0): A basic PID controller with integral discount...
Implement the Python class `PidController` described below. Class description: Implement the PidController class. Method signatures and docstrings: - def __init__(self, unit_time_per_step, proportional=1.0, integral=0.0, derivative=0.0, integral_discounting_per_step=0.0): A basic PID controller with integral discount...
f8c647819fe6abe0f3972e669d2f7d155f275d55
<|skeleton|> class PidController: def __init__(self, unit_time_per_step, proportional=1.0, integral=0.0, derivative=0.0, integral_discounting_per_step=0.0): """A basic PID controller with integral discounting. :param integral_discounting_per_step: The multiplier with which to discount the control error int...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PidController: def __init__(self, unit_time_per_step, proportional=1.0, integral=0.0, derivative=0.0, integral_discounting_per_step=0.0): """A basic PID controller with integral discounting. :param integral_discounting_per_step: The multiplier with which to discount the control error integral. Must be...
the_stack_v2_python_sparse
intervention/controller.py
ZhangCeGitHub/intervention
train
0
43ff8b0c6ee8708dc99acba83615cf2f6f125781
[ "self.head = None\nif nodes is not None:\n node = Node(value=nodes.pop(0))\n self.head = node\n for elem in nodes:\n node.next = Node(value=elem)\n node = node.next", "node = self.head\nnodes = []\nwhile node is not None:\n nodes.append(node.value)\n node = node.next\nnodes.append('No...
<|body_start_0|> self.head = None if nodes is not None: node = Node(value=nodes.pop(0)) self.head = node for elem in nodes: node.next = Node(value=elem) node = node.next <|end_body_0|> <|body_start_1|> node = self.head ...
This is my Class LinkedList with methods __init__ and __insert__
LinkedList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinkedList: """This is my Class LinkedList with methods __init__ and __insert__""" def __init__(self, nodes=None): """This is my initialize of LinkedList""" <|body_0|> def __repr__(self): """Return an object instance""" <|body_1|> def __iter__(self):...
stack_v2_sparse_classes_75kplus_train_001386
2,355
no_license
[ { "docstring": "This is my initialize of LinkedList", "name": "__init__", "signature": "def __init__(self, nodes=None)" }, { "docstring": "Return an object instance", "name": "__repr__", "signature": "def __repr__(self)" }, { "docstring": "To traverse a linked list", "name": ...
3
stack_v2_sparse_classes_30k_train_035752
Implement the Python class `LinkedList` described below. Class description: This is my Class LinkedList with methods __init__ and __insert__ Method signatures and docstrings: - def __init__(self, nodes=None): This is my initialize of LinkedList - def __repr__(self): Return an object instance - def __iter__(self): To ...
Implement the Python class `LinkedList` described below. Class description: This is my Class LinkedList with methods __init__ and __insert__ Method signatures and docstrings: - def __init__(self, nodes=None): This is my initialize of LinkedList - def __repr__(self): Return an object instance - def __iter__(self): To ...
a864173664324769e9de004d387f0ffde45f5cfc
<|skeleton|> class LinkedList: """This is my Class LinkedList with methods __init__ and __insert__""" def __init__(self, nodes=None): """This is my initialize of LinkedList""" <|body_0|> def __repr__(self): """Return an object instance""" <|body_1|> def __iter__(self):...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LinkedList: """This is my Class LinkedList with methods __init__ and __insert__""" def __init__(self, nodes=None): """This is my initialize of LinkedList""" self.head = None if nodes is not None: node = Node(value=nodes.pop(0)) self.head = node ...
the_stack_v2_python_sparse
challenges/ll_merge/ll_merge.py
sydoruk89/python-data-structures-and-algorithms
train
0
88fe0b93d6fead5379ca0b748f24e3e7ca767162
[ "if 'pix' in string_rep:\n return u.Quantity(string_rep[:-3], u.dimensionless_unscaled)\nif 'h' in string_rep or 'rad' in string_rep:\n return Angle(string_rep)\nunit = u.deg\nif len(string_rep.split('.')) >= 3:\n string_rep = string_rep.replace('.', ':', 2)\nelif string_rep.count(':') == 2:\n unit = u....
<|body_start_0|> if 'pix' in string_rep: return u.Quantity(string_rep[:-3], u.dimensionless_unscaled) if 'h' in string_rep or 'rad' in string_rep: return Angle(string_rep) unit = u.deg if len(string_rep.split('.')) >= 3: string_rep = string_rep.replace...
Helper class to structure coordinate parser.
_CRTFCoordinateParser
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _CRTFCoordinateParser: """Helper class to structure coordinate parser.""" def parse_coordinate(string_rep): """Parse a single coordinate.""" <|body_0|> def parse_angular_length_quantity(string_rep): """Parse a string into a Quantity object. Given a string that is...
stack_v2_sparse_classes_75kplus_train_001387
19,388
permissive
[ { "docstring": "Parse a single coordinate.", "name": "parse_coordinate", "signature": "def parse_coordinate(string_rep)" }, { "docstring": "Parse a string into a Quantity object. Given a string that is a number and a unit, return a Quantity of that string. An error is raised if there is no unit,...
2
stack_v2_sparse_classes_30k_test_001528
Implement the Python class `_CRTFCoordinateParser` described below. Class description: Helper class to structure coordinate parser. Method signatures and docstrings: - def parse_coordinate(string_rep): Parse a single coordinate. - def parse_angular_length_quantity(string_rep): Parse a string into a Quantity object. G...
Implement the Python class `_CRTFCoordinateParser` described below. Class description: Helper class to structure coordinate parser. Method signatures and docstrings: - def parse_coordinate(string_rep): Parse a single coordinate. - def parse_angular_length_quantity(string_rep): Parse a string into a Quantity object. G...
501d12d5f5879c49413e20bed90a2d3eb725d5b7
<|skeleton|> class _CRTFCoordinateParser: """Helper class to structure coordinate parser.""" def parse_coordinate(string_rep): """Parse a single coordinate.""" <|body_0|> def parse_angular_length_quantity(string_rep): """Parse a string into a Quantity object. Given a string that is...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _CRTFCoordinateParser: """Helper class to structure coordinate parser.""" def parse_coordinate(string_rep): """Parse a single coordinate.""" if 'pix' in string_rep: return u.Quantity(string_rep[:-3], u.dimensionless_unscaled) if 'h' in string_rep or 'rad' in string_rep...
the_stack_v2_python_sparse
regions/io/crtf/read.py
e-koch/regions
train
0
4a74295ff5aec9a00e0c0a1669020977255ba743
[ "self.__limit = limit\nself.__function = function\nself.__timeout_exception = timeout_exception\nself.__exception_message = exception_message\nself.__name__ = function.__name__\nself.__doc__ = function.__doc__\nself.__timeout = time.time()\nself.__process = multiprocess.Process()\nself.__queue = multiprocess.Queue(...
<|body_start_0|> self.__limit = limit self.__function = function self.__timeout_exception = timeout_exception self.__exception_message = exception_message self.__name__ = function.__name__ self.__doc__ = function.__doc__ self.__timeout = time.time() self._...
Wrap a function and add a timeout (limit) attribute to it. Instances of this class are automatically generated by the add_timeout function defined above. Wrapping a function allows asynchronous calls to be made and termination of execution after a timeout has passed.
_Timeout
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _Timeout: """Wrap a function and add a timeout (limit) attribute to it. Instances of this class are automatically generated by the add_timeout function defined above. Wrapping a function allows asynchronous calls to be made and termination of execution after a timeout has passed.""" def __in...
stack_v2_sparse_classes_75kplus_train_001388
4,510
no_license
[ { "docstring": "Initialize instance in preparation for being called.", "name": "__init__", "signature": "def __init__(self, function, timeout_exception, exception_message, limit)" }, { "docstring": "Execute the embedded function object asynchronously. The function given to the constructor is tra...
5
stack_v2_sparse_classes_30k_train_043805
Implement the Python class `_Timeout` described below. Class description: Wrap a function and add a timeout (limit) attribute to it. Instances of this class are automatically generated by the add_timeout function defined above. Wrapping a function allows asynchronous calls to be made and termination of execution after...
Implement the Python class `_Timeout` described below. Class description: Wrap a function and add a timeout (limit) attribute to it. Instances of this class are automatically generated by the add_timeout function defined above. Wrapping a function allows asynchronous calls to be made and termination of execution after...
7cf573adc6712dfc0d616419fff8d91339d8aa8b
<|skeleton|> class _Timeout: """Wrap a function and add a timeout (limit) attribute to it. Instances of this class are automatically generated by the add_timeout function defined above. Wrapping a function allows asynchronous calls to be made and termination of execution after a timeout has passed.""" def __in...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _Timeout: """Wrap a function and add a timeout (limit) attribute to it. Instances of this class are automatically generated by the add_timeout function defined above. Wrapping a function allows asynchronous calls to be made and termination of execution after a timeout has passed.""" def __init__(self, fu...
the_stack_v2_python_sparse
misc/bpm_cloud/ge.bpmc/ge/bpmc/utilities/timeout.py
dbenlopers/SANDBOX
train
0
a3ac01b465bcaf541c7789b907369192bae807dd
[ "wm = context.window_manager\nvrs_session = session.VerseSession.instance()\nuser_item = wm.verse_users[wm.cur_verse_user_index]\nuser_id = user_item.node_id\nobj_node = vrs_session.nodes[context.active_object.verse_node_id]\nvrs_session.send_node_perm(obj_node.prio, obj_node.id, user_id, vrs.PERM_NODE_READ)\nmesh_...
<|body_start_0|> wm = context.window_manager vrs_session = session.VerseSession.instance() user_item = wm.verse_users[wm.cur_verse_user_index] user_id = user_item.node_id obj_node = vrs_session.nodes[context.active_object.verse_node_id] vrs_session.send_node_perm(obj_node...
This operator tries to subscribe to Blender Mesh object at Verse server.
VerseObjectOtRemWritePerm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VerseObjectOtRemWritePerm: """This operator tries to subscribe to Blender Mesh object at Verse server.""" def invoke(self, context, event): """This method will try to create new node representing Mesh Object at Verse server""" <|body_0|> def poll(cls, context): "...
stack_v2_sparse_classes_75kplus_train_001389
18,592
no_license
[ { "docstring": "This method will try to create new node representing Mesh Object at Verse server", "name": "invoke", "signature": "def invoke(self, context, event)" }, { "docstring": "This class method is used, when Blender check, if this operator can be executed", "name": "poll", "signa...
2
stack_v2_sparse_classes_30k_test_002657
Implement the Python class `VerseObjectOtRemWritePerm` described below. Class description: This operator tries to subscribe to Blender Mesh object at Verse server. Method signatures and docstrings: - def invoke(self, context, event): This method will try to create new node representing Mesh Object at Verse server - d...
Implement the Python class `VerseObjectOtRemWritePerm` described below. Class description: This operator tries to subscribe to Blender Mesh object at Verse server. Method signatures and docstrings: - def invoke(self, context, event): This method will try to create new node representing Mesh Object at Verse server - d...
7b796d30dfd22b7706a93e4419ed913d18d29a44
<|skeleton|> class VerseObjectOtRemWritePerm: """This operator tries to subscribe to Blender Mesh object at Verse server.""" def invoke(self, context, event): """This method will try to create new node representing Mesh Object at Verse server""" <|body_0|> def poll(cls, context): "...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VerseObjectOtRemWritePerm: """This operator tries to subscribe to Blender Mesh object at Verse server.""" def invoke(self, context, event): """This method will try to create new node representing Mesh Object at Verse server""" wm = context.window_manager vrs_session = session.Vers...
the_stack_v2_python_sparse
All_In_One/addons/io_verse/ui_object3d.py
2434325680/Learnbgame
train
0
95c82addde9a37044f1ca314017a74cd486dea12
[ "if len(array) == 0:\n return False\nrownum = len(array)\ncolnum = len(array[0])\ni = colnum - 1\nj = 0\nwhile i >= 0 and j < rownum:\n if array[j][i] < target:\n j += 1\n elif array[j][i] > target:\n i -= 1\n else:\n return True\nreturn False", "if not matrix or len(matrix) == 0:...
<|body_start_0|> if len(array) == 0: return False rownum = len(array) colnum = len(array[0]) i = colnum - 1 j = 0 while i >= 0 and j < rownum: if array[j][i] < target: j += 1 elif array[j][i] > target: i ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def Find(self, array, target): """是否存在""" <|body_0|> def searchMatrix(self, matrix, target): """输出个数""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(array) == 0: return False rownum = len(array) colnum = ...
stack_v2_sparse_classes_75kplus_train_001390
2,335
no_license
[ { "docstring": "是否存在", "name": "Find", "signature": "def Find(self, array, target)" }, { "docstring": "输出个数", "name": "searchMatrix", "signature": "def searchMatrix(self, matrix, target)" } ]
2
stack_v2_sparse_classes_30k_train_002069
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def Find(self, array, target): 是否存在 - def searchMatrix(self, matrix, target): 输出个数
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def Find(self, array, target): 是否存在 - def searchMatrix(self, matrix, target): 输出个数 <|skeleton|> class Solution: def Find(self, array, target): """是否存在""" <|...
ae191a449619418e3eba23f18574c7841e7ba52a
<|skeleton|> class Solution: def Find(self, array, target): """是否存在""" <|body_0|> def searchMatrix(self, matrix, target): """输出个数""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def Find(self, array, target): """是否存在""" if len(array) == 0: return False rownum = len(array) colnum = len(array[0]) i = colnum - 1 j = 0 while i >= 0 and j < rownum: if array[j][i] < target: j += 1 ...
the_stack_v2_python_sparse
target_offer/two_dimensions_search.py
zealfory/dive_python
train
0
dfb6dffb0f177d15b329a7ec41cdbdf6521be772
[ "try:\n serializer = RadiologistReportFilesSerializers(RadiologistReportFiles.objects.all(), many=True)\n return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)\nexcept Exception as e:\n info_message = 'Internal Server Error'\n logger.error(info_message, e)\n return JsonR...
<|body_start_0|> try: serializer = RadiologistReportFilesSerializers(RadiologistReportFiles.objects.all(), many=True) return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200) except Exception as e: info_message = 'Internal Server Error' ...
RadiologistReportFilesView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RadiologistReportFilesView: def get(self, request): """Get all sellers""" <|body_0|> def post(self, request): """Save seller data""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: serializer = RadiologistReportFilesSerializers(Radiolo...
stack_v2_sparse_classes_75kplus_train_001391
31,833
no_license
[ { "docstring": "Get all sellers", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Save seller data", "name": "post", "signature": "def post(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_021575
Implement the Python class `RadiologistReportFilesView` described below. Class description: Implement the RadiologistReportFilesView class. Method signatures and docstrings: - def get(self, request): Get all sellers - def post(self, request): Save seller data
Implement the Python class `RadiologistReportFilesView` described below. Class description: Implement the RadiologistReportFilesView class. Method signatures and docstrings: - def get(self, request): Get all sellers - def post(self, request): Save seller data <|skeleton|> class RadiologistReportFilesView: def g...
b63849983a592fd6a1f654191020fd86aa0787ae
<|skeleton|> class RadiologistReportFilesView: def get(self, request): """Get all sellers""" <|body_0|> def post(self, request): """Save seller data""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RadiologistReportFilesView: def get(self, request): """Get all sellers""" try: serializer = RadiologistReportFilesSerializers(RadiologistReportFiles.objects.all(), many=True) return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200) exc...
the_stack_v2_python_sparse
radiologist/views.py
RupeshKurlekar/biocare
train
1
58fbd41101fb1067638c898c0f5a0402d3443e63
[ "test_cases = [([3, 6, 9], (3, 10)), ([5], (5, 10))]\nfor test_case in test_cases:\n multiples = multiples_of_x_below_y(test_case[1][0], test_case[1][1])\n self.assertEqual(multiples, test_case[0])", "test_case = (23, [3, 5], 10)\nsum_solution = solution(test_case[1], test_case[2])\nself.assertEqual(sum_sol...
<|body_start_0|> test_cases = [([3, 6, 9], (3, 10)), ([5], (5, 10))] for test_case in test_cases: multiples = multiples_of_x_below_y(test_case[1][0], test_case[1][1]) self.assertEqual(multiples, test_case[0]) <|end_body_0|> <|body_start_1|> test_case = (23, [3, 5], 10) ...
Test0001
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test0001: def test_multiples_of_x_below_y_examples(self): """it should get the example correct""" <|body_0|> def test_solution_example(self): """it should get the example correct""" <|body_1|> <|end_skeleton|> <|body_start_0|> test_cases = [([3, 6, ...
stack_v2_sparse_classes_75kplus_train_001392
691
no_license
[ { "docstring": "it should get the example correct", "name": "test_multiples_of_x_below_y_examples", "signature": "def test_multiples_of_x_below_y_examples(self)" }, { "docstring": "it should get the example correct", "name": "test_solution_example", "signature": "def test_solution_exampl...
2
stack_v2_sparse_classes_30k_train_002241
Implement the Python class `Test0001` described below. Class description: Implement the Test0001 class. Method signatures and docstrings: - def test_multiples_of_x_below_y_examples(self): it should get the example correct - def test_solution_example(self): it should get the example correct
Implement the Python class `Test0001` described below. Class description: Implement the Test0001 class. Method signatures and docstrings: - def test_multiples_of_x_below_y_examples(self): it should get the example correct - def test_solution_example(self): it should get the example correct <|skeleton|> class Test000...
9687b709385a23d36bd8a24af16aaf7f375f4818
<|skeleton|> class Test0001: def test_multiples_of_x_below_y_examples(self): """it should get the example correct""" <|body_0|> def test_solution_example(self): """it should get the example correct""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Test0001: def test_multiples_of_x_below_y_examples(self): """it should get the example correct""" test_cases = [([3, 6, 9], (3, 10)), ([5], (5, 10))] for test_case in test_cases: multiples = multiples_of_x_below_y(test_case[1][0], test_case[1][1]) self.assertEqu...
the_stack_v2_python_sparse
problem_0001/python/test.py
mleue/project_euler
train
0
ae54c0737fa287fe1a7c27d6533ecd71c3376132
[ "self.num_layers = num_layers\nself.threshold = threshold\nself.contact_graph = contact_graph\nself.weights = weights\nself.freq_input = freq_input\noutput_shapes = ([None, 20], [None, None]) if self.contact_graph else ([None, 20],)\noutput_types = ('float32', 'float32') if self.contact_graph else ('float32',)\nout...
<|body_start_0|> self.num_layers = num_layers self.threshold = threshold self.contact_graph = contact_graph self.weights = weights self.freq_input = freq_input output_shapes = ([None, 20], [None, None]) if self.contact_graph else ([None, 20],) output_types = ('flo...
ProteinNetPy LabeledFunction returning the required data for the sequence UNET model. LabeledFunction taking a ProteinNetPy record and returning the data required to run Sequence UNET on that record. This can be used with a ProteinNetPy map to generate input data for training or predictions. The function outputs a tupl...
SequenceUNETMapFunction
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SequenceUNETMapFunction: """ProteinNetPy LabeledFunction returning the required data for the sequence UNET model. LabeledFunction taking a ProteinNetPy record and returning the data required to run Sequence UNET on that record. This can be used with a ProteinNetPy map to generate input data for t...
stack_v2_sparse_classes_75kplus_train_001393
13,717
permissive
[ { "docstring": "Initialise the SequenceUNETMapFunction. Parameters ---------- num_layers : int Number of layers in the Sequence UNET model. threshold : float or None Return categorical output, with variants below this threshold classed as deleterious. contact_graph : bool Return a contact graph in addition to t...
2
stack_v2_sparse_classes_30k_train_033476
Implement the Python class `SequenceUNETMapFunction` described below. Class description: ProteinNetPy LabeledFunction returning the required data for the sequence UNET model. LabeledFunction taking a ProteinNetPy record and returning the data required to run Sequence UNET on that record. This can be used with a Protei...
Implement the Python class `SequenceUNETMapFunction` described below. Class description: ProteinNetPy LabeledFunction returning the required data for the sequence UNET model. LabeledFunction taking a ProteinNetPy record and returning the data required to run Sequence UNET on that record. This can be used with a Protei...
cfd0a32f11c733c52c2818b697077feb991ff788
<|skeleton|> class SequenceUNETMapFunction: """ProteinNetPy LabeledFunction returning the required data for the sequence UNET model. LabeledFunction taking a ProteinNetPy record and returning the data required to run Sequence UNET on that record. This can be used with a ProteinNetPy map to generate input data for t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SequenceUNETMapFunction: """ProteinNetPy LabeledFunction returning the required data for the sequence UNET model. LabeledFunction taking a ProteinNetPy record and returning the data required to run Sequence UNET on that record. This can be used with a ProteinNetPy map to generate input data for training or pr...
the_stack_v2_python_sparse
sequence_unet/predict.py
allydunham/sequence_unet
train
16
f603e141e239693960b3156121d59df40fbc2e97
[ "form_errors = form.errors\nfor fields_error in form_errors.keys():\n for error in form_errors[fields_error]:\n messages.error(self.request, fields_error + ': ' + error, 'danger')", "self.object = form.save(commit=False)\nself.object.tutor2 = tutor2\nif self.request.user.groups.filter(name='Teachers').e...
<|body_start_0|> form_errors = form.errors for fields_error in form_errors.keys(): for error in form_errors[fields_error]: messages.error(self.request, fields_error + ': ' + error, 'danger') <|end_body_0|> <|body_start_1|> self.object = form.save(commit=False) ...
Controlador de la vista update generica para todos los usuarios. Atributos: model(Tfms): Modelo TFG, el cual se va a editar. form_class(CreateTfgForm): formulario del Modelo TFM
UpdateTfm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpdateTfm: """Controlador de la vista update generica para todos los usuarios. Atributos: model(Tfms): Modelo TFG, el cual se va a editar. form_class(CreateTfgForm): formulario del Modelo TFM""" def _errors_form(self, form): """Función encargada de checkear los errores de un formular...
stack_v2_sparse_classes_75kplus_train_001394
4,712
no_license
[ { "docstring": "Función encargada de checkear los errores de un formulario. Parametros: form(form.Modelform): formulario del que se va a checkear, si existen errores.", "name": "_errors_form", "signature": "def _errors_form(self, form)" }, { "docstring": "Función encargada de crear un TFG dado s...
6
stack_v2_sparse_classes_30k_train_022481
Implement the Python class `UpdateTfm` described below. Class description: Controlador de la vista update generica para todos los usuarios. Atributos: model(Tfms): Modelo TFG, el cual se va a editar. form_class(CreateTfgForm): formulario del Modelo TFM Method signatures and docstrings: - def _errors_form(self, form):...
Implement the Python class `UpdateTfm` described below. Class description: Controlador de la vista update generica para todos los usuarios. Atributos: model(Tfms): Modelo TFG, el cual se va a editar. form_class(CreateTfgForm): formulario del Modelo TFM Method signatures and docstrings: - def _errors_form(self, form):...
c106dfab0e5698109956cbbf731c049c05b9fa53
<|skeleton|> class UpdateTfm: """Controlador de la vista update generica para todos los usuarios. Atributos: model(Tfms): Modelo TFG, el cual se va a editar. form_class(CreateTfgForm): formulario del Modelo TFM""" def _errors_form(self, form): """Función encargada de checkear los errores de un formular...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UpdateTfm: """Controlador de la vista update generica para todos los usuarios. Atributos: model(Tfms): Modelo TFG, el cual se va a editar. form_class(CreateTfgForm): formulario del Modelo TFM""" def _errors_form(self, form): """Función encargada de checkear los errores de un formulario. Parametro...
the_stack_v2_python_sparse
tfms/utils/update_tfm.py
EmilioSanchezCatalan/project_manager
train
0
7866c9fa6c4501020c6fbf1e417256b1e75eb3d1
[ "super(RedLight, self).__init__(parent)\nself.setFixedSize(22, 22)\nself.red = QtGui.QColor(184, 18, 27)", "painter = QtGui.QPainter()\npainter.begin(self)\npainter.setRenderHint(QtGui.QPainter.Antialiasing, True)\npainter.setPen(self.red)\npainter.setBrush(self.red)\npainter.drawEllipse(1, 1, 20, 20)\npainter.en...
<|body_start_0|> super(RedLight, self).__init__(parent) self.setFixedSize(22, 22) self.red = QtGui.QColor(184, 18, 27) <|end_body_0|> <|body_start_1|> painter = QtGui.QPainter() painter.begin(self) painter.setRenderHint(QtGui.QPainter.Antialiasing, True) painter....
Creates a red circle
RedLight
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RedLight: """Creates a red circle""" def __init__(self, parent=None): """Initializes circle with fixed size and color""" <|body_0|> def paintEvent(self, e): """Draws the circle""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(RedLight, self...
stack_v2_sparse_classes_75kplus_train_001395
4,386
no_license
[ { "docstring": "Initializes circle with fixed size and color", "name": "__init__", "signature": "def __init__(self, parent=None)" }, { "docstring": "Draws the circle", "name": "paintEvent", "signature": "def paintEvent(self, e)" } ]
2
stack_v2_sparse_classes_30k_train_038842
Implement the Python class `RedLight` described below. Class description: Creates a red circle Method signatures and docstrings: - def __init__(self, parent=None): Initializes circle with fixed size and color - def paintEvent(self, e): Draws the circle
Implement the Python class `RedLight` described below. Class description: Creates a red circle Method signatures and docstrings: - def __init__(self, parent=None): Initializes circle with fixed size and color - def paintEvent(self, e): Draws the circle <|skeleton|> class RedLight: """Creates a red circle""" ...
898bda85308f37fd19568f37fe277f93951981ec
<|skeleton|> class RedLight: """Creates a red circle""" def __init__(self, parent=None): """Initializes circle with fixed size and color""" <|body_0|> def paintEvent(self, e): """Draws the circle""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RedLight: """Creates a red circle""" def __init__(self, parent=None): """Initializes circle with fixed size and color""" super(RedLight, self).__init__(parent) self.setFixedSize(22, 22) self.red = QtGui.QColor(184, 18, 27) def paintEvent(self, e): """Draws the...
the_stack_v2_python_sparse
gui/statuslight.py
LightingResearchCenter/PythonDaysimeter12Client
train
0
d30a2106268094b00b2f65cca7c23749a3488635
[ "logging.info('original table has %d rows' % len(table))\ntable = table.dropna(subset=[stat_col])\nlogging.info('cleaned table has %d rows' % len(table))\nreturn table", "threshold = float(threshold)\ntry:\n if alternative == 'less':\n table = table[table[filter_column] < threshold]\n else:\n ...
<|body_start_0|> logging.info('original table has %d rows' % len(table)) table = table.dropna(subset=[stat_col]) logging.info('cleaned table has %d rows' % len(table)) return table <|end_body_0|> <|body_start_1|> threshold = float(threshold) try: if alternati...
This class contains static methods to clean and filter specific columns of a table
TableElaboration
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TableElaboration: """This class contains static methods to clean and filter specific columns of a table""" def clean_table(table: pd.DataFrame, stat_col: str='stat') -> pd.DataFrame: """This function clean the table from the N/A values :param table: dataframerepresenting the table to...
stack_v2_sparse_classes_75kplus_train_001396
2,137
permissive
[ { "docstring": "This function clean the table from the N/A values :param table: dataframerepresenting the table to be cleaned :param stat_col: the column to be cleaned :return: the table cleaned from the N/A values Example _______ >>> import numpy as np >>> table = pd.DataFrame(np.random.randint(0,100,size=(100...
2
stack_v2_sparse_classes_30k_train_047623
Implement the Python class `TableElaboration` described below. Class description: This class contains static methods to clean and filter specific columns of a table Method signatures and docstrings: - def clean_table(table: pd.DataFrame, stat_col: str='stat') -> pd.DataFrame: This function clean the table from the N/...
Implement the Python class `TableElaboration` described below. Class description: This class contains static methods to clean and filter specific columns of a table Method signatures and docstrings: - def clean_table(table: pd.DataFrame, stat_col: str='stat') -> pd.DataFrame: This function clean the table from the N/...
3c172abe4b5391c5fb9a41f5fdc104ba0a3ab86b
<|skeleton|> class TableElaboration: """This class contains static methods to clean and filter specific columns of a table""" def clean_table(table: pd.DataFrame, stat_col: str='stat') -> pd.DataFrame: """This function clean the table from the N/A values :param table: dataframerepresenting the table to...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TableElaboration: """This class contains static methods to clean and filter specific columns of a table""" def clean_table(table: pd.DataFrame, stat_col: str='stat') -> pd.DataFrame: """This function clean the table from the N/A values :param table: dataframerepresenting the table to be cleaned :...
the_stack_v2_python_sparse
pygna/elaborators.py
stracquadaniolab/pygna
train
41
2259e2431ace6d5cb0e49a13846306c652976c4c
[ "global channel_list_page, admin_page\nchannel_list_page = ChannelListPage(self.driver)\nadmin_page = AdminPage(self.driver)\nadmin_page.into_subsystem('业务管理')\nadmin_page.select_menu('首页/渠道业务管理')", "admin_page.select_menu('渠道列表')\nchannel_list_page.simple_query_channel(channel_name='三沙市')\nassert '三沙市' in channe...
<|body_start_0|> global channel_list_page, admin_page channel_list_page = ChannelListPage(self.driver) admin_page = AdminPage(self.driver) admin_page.into_subsystem('业务管理') admin_page.select_menu('首页/渠道业务管理') <|end_body_0|> <|body_start_1|> admin_page.select_menu('渠道列表')...
TestChannelList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestChannelList: def set_up(self): """前置操作 :return:""" <|body_0|> def test_query_channel(self, set_up): """渠道查询 :return:""" <|body_1|> def test_reset_channel_query(self): """重置渠道列表查询 :return:""" <|body_2|> def test_click_more_channel...
stack_v2_sparse_classes_75kplus_train_001397
2,199
no_license
[ { "docstring": "前置操作 :return:", "name": "set_up", "signature": "def set_up(self)" }, { "docstring": "渠道查询 :return:", "name": "test_query_channel", "signature": "def test_query_channel(self, set_up)" }, { "docstring": "重置渠道列表查询 :return:", "name": "test_reset_channel_query", ...
5
stack_v2_sparse_classes_30k_train_044211
Implement the Python class `TestChannelList` described below. Class description: Implement the TestChannelList class. Method signatures and docstrings: - def set_up(self): 前置操作 :return: - def test_query_channel(self, set_up): 渠道查询 :return: - def test_reset_channel_query(self): 重置渠道列表查询 :return: - def test_click_more_...
Implement the Python class `TestChannelList` described below. Class description: Implement the TestChannelList class. Method signatures and docstrings: - def set_up(self): 前置操作 :return: - def test_query_channel(self, set_up): 渠道查询 :return: - def test_reset_channel_query(self): 重置渠道列表查询 :return: - def test_click_more_...
86d1b085af2d3808ac8472d541f4bf26d26591e0
<|skeleton|> class TestChannelList: def set_up(self): """前置操作 :return:""" <|body_0|> def test_query_channel(self, set_up): """渠道查询 :return:""" <|body_1|> def test_reset_channel_query(self): """重置渠道列表查询 :return:""" <|body_2|> def test_click_more_channel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestChannelList: def set_up(self): """前置操作 :return:""" global channel_list_page, admin_page channel_list_page = ChannelListPage(self.driver) admin_page = AdminPage(self.driver) admin_page.into_subsystem('业务管理') admin_page.select_menu('首页/渠道业务管理') def test_q...
the_stack_v2_python_sparse
src/cases/business_manage/channel_business_manage/test_channel_list_page_140.py
102244653/SeleniumByPython
train
2
5c044354700c6fdd8a0353c0bcc55b2872fa286d
[ "Event.objects.create(date=self.yesterday, pub_date=self.now, headline='past')\nEvent.objects.create(date=self.tomorrow, pub_date=self.now, headline='future')\nself.assertQuerysetEqual(Event.objects.future(), ['future'], transform=lambda event: event.headline)\nself.assertQuerysetEqual(Event.objects.past(), ['past'...
<|body_start_0|> Event.objects.create(date=self.yesterday, pub_date=self.now, headline='past') Event.objects.create(date=self.tomorrow, pub_date=self.now, headline='future') self.assertQuerysetEqual(Event.objects.future(), ['future'], transform=lambda event: event.headline) self.assertQu...
EventTestCase
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventTestCase: def test_manager_past_future(self): """Make sure that the Event manager's `past` and `future` methods works""" <|body_0|> def test_manager_past_future_include_today(self): """Make sure that both .future() and .past() include today's events.""" ...
stack_v2_sparse_classes_75kplus_train_001398
5,555
permissive
[ { "docstring": "Make sure that the Event manager's `past` and `future` methods works", "name": "test_manager_past_future", "signature": "def test_manager_past_future(self)" }, { "docstring": "Make sure that both .future() and .past() include today's events.", "name": "test_manager_past_futur...
3
null
Implement the Python class `EventTestCase` described below. Class description: Implement the EventTestCase class. Method signatures and docstrings: - def test_manager_past_future(self): Make sure that the Event manager's `past` and `future` methods works - def test_manager_past_future_include_today(self): Make sure t...
Implement the Python class `EventTestCase` described below. Class description: Implement the EventTestCase class. Method signatures and docstrings: - def test_manager_past_future(self): Make sure that the Event manager's `past` and `future` methods works - def test_manager_past_future_include_today(self): Make sure t...
66a6e87290ee43b4935bc178c737c565570fbc7f
<|skeleton|> class EventTestCase: def test_manager_past_future(self): """Make sure that the Event manager's `past` and `future` methods works""" <|body_0|> def test_manager_past_future_include_today(self): """Make sure that both .future() and .past() include today's events.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EventTestCase: def test_manager_past_future(self): """Make sure that the Event manager's `past` and `future` methods works""" Event.objects.create(date=self.yesterday, pub_date=self.now, headline='past') Event.objects.create(date=self.tomorrow, pub_date=self.now, headline='future') ...
the_stack_v2_python_sparse
blog/tests.py
django/djangoproject.com
train
1,807
48d954be427c7ff912e3dde13361562e17151266
[ "startTime = datetime.datetime.now()\nif trial:\n endTime = datetime.datetime.now()\n return {'start': startTime, 'end': endTime}\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate(TEAM_NAME, TEAM_NAME)\nraw_html = scraper.simple_get(BALLOT_QUESTION_2000_2018_URL)\nhtml = BeautifulSoup...
<|body_start_0|> startTime = datetime.datetime.now() if trial: endTime = datetime.datetime.now() return {'start': startTime, 'end': endTime} client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate(TEAM_NAME, TEAM_NAME) raw_html = sc...
ballotQuestions
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ballotQuestions: def execute(trial=False): """Scrape electionstats to get data about each MA ballot question (2000-2018) and insert into collection ex) { "_id" : "7322", "year" : 2018, "number" : "4", "description" : "SUMMARY Sections 3 to 7 of Chapter 44B of the General Laws of Massachu...
stack_v2_sparse_classes_75kplus_train_001399
5,791
no_license
[ { "docstring": "Scrape electionstats to get data about each MA ballot question (2000-2018) and insert into collection ex) { \"_id\" : \"7322\", \"year\" : 2018, \"number\" : \"4\", \"description\" : \"SUMMARY Sections 3 to 7 of Chapter 44B of the General Laws of Massachusetts, also known as the Community Preser...
2
stack_v2_sparse_classes_30k_train_050094
Implement the Python class `ballotQuestions` described below. Class description: Implement the ballotQuestions class. Method signatures and docstrings: - def execute(trial=False): Scrape electionstats to get data about each MA ballot question (2000-2018) and insert into collection ex) { "_id" : "7322", "year" : 2018,...
Implement the Python class `ballotQuestions` described below. Class description: Implement the ballotQuestions class. Method signatures and docstrings: - def execute(trial=False): Scrape electionstats to get data about each MA ballot question (2000-2018) and insert into collection ex) { "_id" : "7322", "year" : 2018,...
90284cf3debbac36eead07b8d2339cdd191b86cf
<|skeleton|> class ballotQuestions: def execute(trial=False): """Scrape electionstats to get data about each MA ballot question (2000-2018) and insert into collection ex) { "_id" : "7322", "year" : 2018, "number" : "4", "description" : "SUMMARY Sections 3 to 7 of Chapter 44B of the General Laws of Massachu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ballotQuestions: def execute(trial=False): """Scrape electionstats to get data about each MA ballot question (2000-2018) and insert into collection ex) { "_id" : "7322", "year" : 2018, "number" : "4", "description" : "SUMMARY Sections 3 to 7 of Chapter 44B of the General Laws of Massachusetts, also kn...
the_stack_v2_python_sparse
ldisalvo_skeesara_vidyaap/ballotQuestions.py
maximega/course-2019-spr-proj
train
2