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
a4e43698cf434ac493e830391b9db58ed91d3944
[ "self._face = freetype.Face(path)\nself._face.set_char_size(size * 64)\nGL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)\nself._characters = {}\nfor char_num in range(255):\n char = chr(char_num)\n self._face.load_char(char)\n bitmap = self._face.glyph.bitmap\n texture = GL.glGenTextures(1)\n GL.glBindTex...
<|body_start_0|> self._face = freetype.Face(path) self._face.set_char_size(size * 64) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) self._characters = {} for char_num in range(255): char = chr(char_num) self._face.load_char(char) bitmap = self._f...
Font
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Font: def __init__(self, path='/System/Library/Fonts/Courier.dfont', size=16): """Args: path (str): path to the font file size (int): point size of the font""" <|body_0|> def render_3d(self, window_size, text, pos, scale=1.0, color=(1.0, 0.0, 0.0, 1.0)): """Render th...
stack_v2_sparse_classes_75kplus_train_067200
8,519
no_license
[ { "docstring": "Args: path (str): path to the font file size (int): point size of the font", "name": "__init__", "signature": "def __init__(self, path='/System/Library/Fonts/Courier.dfont', size=16)" }, { "docstring": "Render the provided text at a point in 3D space using this font Args: window_...
2
stack_v2_sparse_classes_30k_train_053580
Implement the Python class `Font` described below. Class description: Implement the Font class. Method signatures and docstrings: - def __init__(self, path='/System/Library/Fonts/Courier.dfont', size=16): Args: path (str): path to the font file size (int): point size of the font - def render_3d(self, window_size, tex...
Implement the Python class `Font` described below. Class description: Implement the Font class. Method signatures and docstrings: - def __init__(self, path='/System/Library/Fonts/Courier.dfont', size=16): Args: path (str): path to the font file size (int): point size of the font - def render_3d(self, window_size, tex...
b40ef729353205a9751b1f975f8a487e24286bf9
<|skeleton|> class Font: def __init__(self, path='/System/Library/Fonts/Courier.dfont', size=16): """Args: path (str): path to the font file size (int): point size of the font""" <|body_0|> def render_3d(self, window_size, text, pos, scale=1.0, color=(1.0, 0.0, 0.0, 1.0)): """Render th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Font: def __init__(self, path='/System/Library/Fonts/Courier.dfont', size=16): """Args: path (str): path to the font file size (int): point size of the font""" self._face = freetype.Face(path) self._face.set_char_size(size * 64) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) ...
the_stack_v2_python_sparse
python/game_core/drawing.py
tymonpitts/game_test
train
0
64aa211716d1ff8aa7a7f77a0930a1b04c1f87e2
[ "if not root:\n return ''\nif root.left:\n if root.right:\n return '{}({})({})'.format(root.val, self.serialize(root.left), self.serialize(root.right))\n else:\n return '{}({})'.format(root.val, self.serialize(root.left))\nelif root.right:\n return '{}()({})'.format(root.val, self.serializ...
<|body_start_0|> if not root: return '' if root.left: if root.right: return '{}({})({})'.format(root.val, self.serialize(root.left), self.serialize(root.right)) else: return '{}({})'.format(root.val, self.serialize(root.left)) e...
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_067201
2,097
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_009336
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:...
34a78e06d493e61b21d4442747e9102abf9b319b
<|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 '' if root.left: if root.right: return '{}({})({})'.format(root.val, self.serialize(root.left), self.serialize(root.ri...
the_stack_v2_python_sparse
449_Serialize_and_Deserialize_BST.py
sunnyyeti/Leetcode-solutions
train
0
233e464239c669c25b63d5d61222b39130ae3960
[ "code = '\\na = 0\\nfor i in range(1, 10, 1):\\n a = i\\n '\nattr = self.prepare(code, self.attr_name)\nself.assertEqual(attr, 0)", "code = '\\na = 2\\nfor i in range(1, 10, 1):\\n if i % a == 0:\\n a = 2\\n else:\\n a = 2\\n '\nattr = self.prepare(code, self.attr_name)\nself....
<|body_start_0|> code = '\na = 0\nfor i in range(1, 10, 1):\n a = i\n ' attr = self.prepare(code, self.attr_name) self.assertEqual(attr, 0) <|end_body_0|> <|body_start_1|> code = '\na = 2\nfor i in range(1, 10, 1):\n if i % a == 0:\n a = 2\n else:\n a = 2\n...
Test class for RepeatValues
TestRepeatValues
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestRepeatValues: """Test class for RepeatValues""" def test_noRepeatValues(self): """Tests the correct results for codes which do not have repeating values. Keyword arguments: self -- the TestRepeatValues instance""" <|body_0|> def test_repeatValues(self): """Te...
stack_v2_sparse_classes_75kplus_train_067202
20,005
no_license
[ { "docstring": "Tests the correct results for codes which do not have repeating values. Keyword arguments: self -- the TestRepeatValues instance", "name": "test_noRepeatValues", "signature": "def test_noRepeatValues(self)" }, { "docstring": "Tests the correct results for codes which have repeati...
2
stack_v2_sparse_classes_30k_train_040345
Implement the Python class `TestRepeatValues` described below. Class description: Test class for RepeatValues Method signatures and docstrings: - def test_noRepeatValues(self): Tests the correct results for codes which do not have repeating values. Keyword arguments: self -- the TestRepeatValues instance - def test_r...
Implement the Python class `TestRepeatValues` described below. Class description: Test class for RepeatValues Method signatures and docstrings: - def test_noRepeatValues(self): Tests the correct results for codes which do not have repeating values. Keyword arguments: self -- the TestRepeatValues instance - def test_r...
2c0b907f5d9e74265e87ab3e36753f764a965f21
<|skeleton|> class TestRepeatValues: """Test class for RepeatValues""" def test_noRepeatValues(self): """Tests the correct results for codes which do not have repeating values. Keyword arguments: self -- the TestRepeatValues instance""" <|body_0|> def test_repeatValues(self): """Te...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestRepeatValues: """Test class for RepeatValues""" def test_noRepeatValues(self): """Tests the correct results for codes which do not have repeating values. Keyword arguments: self -- the TestRepeatValues instance""" code = '\na = 0\nfor i in range(1, 10, 1):\n a = i\n ' ...
the_stack_v2_python_sparse
AlgoBooster/ab_ui/ab_main/ab_unittests/test_extraction.py
danielaboeing/algobooster
train
0
254a77c058fb3ea4be7cd79c8d090676a1f141c3
[ "nums.sort()\nfor i in range(len(nums)):\n if nums[i] == nums[i + 1]:\n return nums[i]\nreturn -1", "s = set()\nfor num in nums:\n if num in s:\n return num\n else:\n s.add(num)\nreturn -1", "slow = nums[0]\nfast = nums[nums[0]]\nwhile slow != fast:\n slow = nums[slow]\n fast...
<|body_start_0|> nums.sort() for i in range(len(nums)): if nums[i] == nums[i + 1]: return nums[i] return -1 <|end_body_0|> <|body_start_1|> s = set() for num in nums: if num in s: return num else: ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def find_duplicate_number(self, nums: List[int]) -> int: """找出重复的数字 Args: arr: 数组 Returns: 重复数字""" <|body_0|> def find_duplicate_number2(self, nums: List[int]) -> int: """找出重复的数字 Args: arr: 数组 Returns: 重复数字""" <|body_1|> def find_duplicate_numb...
stack_v2_sparse_classes_75kplus_train_067203
2,766
permissive
[ { "docstring": "找出重复的数字 Args: arr: 数组 Returns: 重复数字", "name": "find_duplicate_number", "signature": "def find_duplicate_number(self, nums: List[int]) -> int" }, { "docstring": "找出重复的数字 Args: arr: 数组 Returns: 重复数字", "name": "find_duplicate_number2", "signature": "def find_duplicate_number...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def find_duplicate_number(self, nums: List[int]) -> int: 找出重复的数字 Args: arr: 数组 Returns: 重复数字 - def find_duplicate_number2(self, nums: List[int]) -> int: 找出重复的数字 Args: arr: 数组 Ret...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def find_duplicate_number(self, nums: List[int]) -> int: 找出重复的数字 Args: arr: 数组 Returns: 重复数字 - def find_duplicate_number2(self, nums: List[int]) -> int: 找出重复的数字 Args: arr: 数组 Ret...
50f35eef6a0ad63173efed10df3c835b1dceaa3f
<|skeleton|> class Solution: def find_duplicate_number(self, nums: List[int]) -> int: """找出重复的数字 Args: arr: 数组 Returns: 重复数字""" <|body_0|> def find_duplicate_number2(self, nums: List[int]) -> int: """找出重复的数字 Args: arr: 数组 Returns: 重复数字""" <|body_1|> def find_duplicate_numb...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def find_duplicate_number(self, nums: List[int]) -> int: """找出重复的数字 Args: arr: 数组 Returns: 重复数字""" nums.sort() for i in range(len(nums)): if nums[i] == nums[i + 1]: return nums[i] return -1 def find_duplicate_number2(self, nums: List[i...
the_stack_v2_python_sparse
src/leetcodepython/top100likedquestions/find_duplicate_number_287.py
zhangyu345293721/leetcode
train
101
4b329e510d6098851dd3c76c8716ab4018867840
[ "n = len(nums)\nM = [0] * (n + 1)\nif n == 0:\n return 0\nM[0] = 0\nM[1] = nums[0]\nfor i in range(2, n + 1):\n M[i] = max(nums[i - 1] + M[i - 2], M[i - 1])\nreturn M[-1]", "prev = 0\ncurr = 0\nfor i in nums:\n prev, curr = (curr, max(curr, prev + i))\nreturn curr", "n = len(nums)\ndp_i_1 = 0\ndp_i_2 =...
<|body_start_0|> n = len(nums) M = [0] * (n + 1) if n == 0: return 0 M[0] = 0 M[1] = nums[0] for i in range(2, n + 1): M[i] = max(nums[i - 1] + M[i - 2], M[i - 1]) return M[-1] <|end_body_0|> <|body_start_1|> prev = 0 curr ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_2|> <|end_skele...
stack_v2_sparse_classes_75kplus_train_067204
1,312
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "rob", "signature": "def rob(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "rob", "signature": "def rob(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "rob",...
3
stack_v2_sparse_classes_30k_train_050336
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums): :type nums: List[int] :rtype: int - def rob(self, nums): :type nums: List[int] :rtype: int - def rob(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 rob(self, nums): :type nums: List[int] :rtype: int - def rob(self, nums): :type nums: List[int] :rtype: int - def rob(self, nums): :type nums: List[int] :rtype: int <|skelet...
a509b383a42f54313970168d9faa11f088f18708
<|skeleton|> class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_2|> <|end_skele...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" n = len(nums) M = [0] * (n + 1) if n == 0: return 0 M[0] = 0 M[1] = nums[0] for i in range(2, n + 1): M[i] = max(nums[i - 1] + M[i - 2], M[i - 1]) retu...
the_stack_v2_python_sparse
0198_House_Robber.py
bingli8802/leetcode
train
0
2629fc1175b68277265ebdb5cee77bf2188cecb1
[ "content_type = ContentType.objects.get_for_model(instance.__class__)\nobj_id = instance.id\nqueryset = super(LikeDislikeManager, self).filter(content_type=content_type, object_id=obj_id)\nreturn queryset", "ip_address = get_client_ip(request)\ncontent_type = ContentType.objects.get_for_model(instance.__class__)\...
<|body_start_0|> content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id queryset = super(LikeDislikeManager, self).filter(content_type=content_type, object_id=obj_id) return queryset <|end_body_0|> <|body_start_1|> ip_address = get_client_ip(re...
mesle manager e Comments
LikeDislikeManager
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LikeDislikeManager: """mesle manager e Comments""" def filter_by_model(self, instance): """bar assasse model filter mikonim""" <|body_0|> def create_for_instance_model(self, instance, request, likedislike, user=None): """bar assasse model create mkonim age user a...
stack_v2_sparse_classes_75kplus_train_067205
6,949
permissive
[ { "docstring": "bar assasse model filter mikonim", "name": "filter_by_model", "signature": "def filter_by_model(self, instance)" }, { "docstring": "bar assasse model create mkonim age user anonymous bud bar assasse IP_address taghirat emal mishe age authenticate bud ke nega mikone bebine ip sh h...
2
stack_v2_sparse_classes_30k_train_048908
Implement the Python class `LikeDislikeManager` described below. Class description: mesle manager e Comments Method signatures and docstrings: - def filter_by_model(self, instance): bar assasse model filter mikonim - def create_for_instance_model(self, instance, request, likedislike, user=None): bar assasse model cre...
Implement the Python class `LikeDislikeManager` described below. Class description: mesle manager e Comments Method signatures and docstrings: - def filter_by_model(self, instance): bar assasse model filter mikonim - def create_for_instance_model(self, instance, request, likedislike, user=None): bar assasse model cre...
aef47922fdd6488550881ed9d42bf30a0d33a32a
<|skeleton|> class LikeDislikeManager: """mesle manager e Comments""" def filter_by_model(self, instance): """bar assasse model filter mikonim""" <|body_0|> def create_for_instance_model(self, instance, request, likedislike, user=None): """bar assasse model create mkonim age user a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LikeDislikeManager: """mesle manager e Comments""" def filter_by_model(self, instance): """bar assasse model filter mikonim""" content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id queryset = super(LikeDislikeManager, self).filter(conten...
the_stack_v2_python_sparse
src/likes/models.py
m3h-D/Myinfoblog
train
0
970b77954e3edb5d114b8701f2654963d2ef1263
[ "\"\"\"\n You'll have to do a set of jumps, and choose for each one whether \n to do it using a rope or bricks. It's always optimal to use ropes \n in the largest jumps.\n\n \"\"\"\nA = heights\nheap = []\n'\\n Iterate on the buildings, maintaining the largest r jumps and the \\n ...
<|body_start_0|> """ You'll have to do a set of jumps, and choose for each one whether to do it using a rope or bricks. It's always optimal to use ropes in the largest jumps. """ A = heights heap = [] '\n Iterate o...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def furthestBuilding(self, heights, bricks, ladders): """:type heights: List[int] :type bricks: int :type ladders: int :rtype: int""" <|body_0|> def furthestBuildingHeap(self, heights, bricks, ladders): """:type heights: List[int] :type bricks: int :type la...
stack_v2_sparse_classes_75kplus_train_067206
4,669
no_license
[ { "docstring": ":type heights: List[int] :type bricks: int :type ladders: int :rtype: int", "name": "furthestBuilding", "signature": "def furthestBuilding(self, heights, bricks, ladders)" }, { "docstring": ":type heights: List[int] :type bricks: int :type ladders: int :rtype: int", "name": "...
3
stack_v2_sparse_classes_30k_train_051727
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def furthestBuilding(self, heights, bricks, ladders): :type heights: List[int] :type bricks: int :type ladders: int :rtype: int - def furthestBuildingHeap(self, heights, bricks, ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def furthestBuilding(self, heights, bricks, ladders): :type heights: List[int] :type bricks: int :type ladders: int :rtype: int - def furthestBuildingHeap(self, heights, bricks, ...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def furthestBuilding(self, heights, bricks, ladders): """:type heights: List[int] :type bricks: int :type ladders: int :rtype: int""" <|body_0|> def furthestBuildingHeap(self, heights, bricks, ladders): """:type heights: List[int] :type bricks: int :type la...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def furthestBuilding(self, heights, bricks, ladders): """:type heights: List[int] :type bricks: int :type ladders: int :rtype: int""" """ You'll have to do a set of jumps, and choose for each one whether to do it using a rope or bricks. It's always op...
the_stack_v2_python_sparse
F/FurthestBuildingYouCanReach.py
bssrdf/pyleet
train
2
5c2f1e41b694cbfd877def321a88593fcda4fbca
[ "super(PeriodStrategy, self).__init__('periodStrategy')\nself.configDict = configDict\nassert int(configDict[CONF_STRATEGY_PERIOD]) >= 1\nself.perAmount = max(1, round(int(configDict[CONF_INIT_CASH]) / 100))\nself.period = int(configDict[CONF_STRATEGY_PERIOD])\nself.symbols = None\nself.counter = 0", "self.counte...
<|body_start_0|> super(PeriodStrategy, self).__init__('periodStrategy') self.configDict = configDict assert int(configDict[CONF_STRATEGY_PERIOD]) >= 1 self.perAmount = max(1, round(int(configDict[CONF_INIT_CASH]) / 100)) self.period = int(configDict[CONF_STRATEGY_PERIOD]) ...
period strategy
PeriodStrategy
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PeriodStrategy: """period strategy""" def __init__(self, configDict): """constructor""" <|body_0|> def increaseAndCheckCounter(self): """increase counter by one and check whether a period is end""" <|body_1|> def tickUpdate(self, tickDict): "...
stack_v2_sparse_classes_75kplus_train_067207
1,684
no_license
[ { "docstring": "constructor", "name": "__init__", "signature": "def __init__(self, configDict)" }, { "docstring": "increase counter by one and check whether a period is end", "name": "increaseAndCheckCounter", "signature": "def increaseAndCheckCounter(self)" }, { "docstring": "co...
3
stack_v2_sparse_classes_30k_train_054502
Implement the Python class `PeriodStrategy` described below. Class description: period strategy Method signatures and docstrings: - def __init__(self, configDict): constructor - def increaseAndCheckCounter(self): increase counter by one and check whether a period is end - def tickUpdate(self, tickDict): consume ticks
Implement the Python class `PeriodStrategy` described below. Class description: period strategy Method signatures and docstrings: - def __init__(self, configDict): constructor - def increaseAndCheckCounter(self): increase counter by one and check whether a period is end - def tickUpdate(self, tickDict): consume ticks...
d494b3041069d377d6a7a9c296a14334f2fa5acc
<|skeleton|> class PeriodStrategy: """period strategy""" def __init__(self, configDict): """constructor""" <|body_0|> def increaseAndCheckCounter(self): """increase counter by one and check whether a period is end""" <|body_1|> def tickUpdate(self, tickDict): "...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PeriodStrategy: """period strategy""" def __init__(self, configDict): """constructor""" super(PeriodStrategy, self).__init__('periodStrategy') self.configDict = configDict assert int(configDict[CONF_STRATEGY_PERIOD]) >= 1 self.perAmount = max(1, round(int(configDic...
the_stack_v2_python_sparse
python/panpanpandas_ultrafinance/ultrafinance-master/ultrafinance/backTest/tickSubscriber/strategies/periodStrategy.py
LiuFang816/SALSTM_py_data
train
10
af93ab0728f64999c75d5999cef34b9f5eb27e9b
[ "try:\n print('收到获取教师信息的请求')\n self.sqlhandler = None\n body = json.loads(self.request.body)\n self.TeaUid = body['teaUid']\n if self.getTeaInfo():\n self.write({'success': True, 'data': self.TeaInfo})\n self.finish()\n else:\n raise RuntimeError\nexcept Exception as e:\n p...
<|body_start_0|> try: print('收到获取教师信息的请求') self.sqlhandler = None body = json.loads(self.request.body) self.TeaUid = body['teaUid'] if self.getTeaInfo(): self.write({'success': True, 'data': self.TeaInfo}) self.finish() ...
TeaInfoRequestHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TeaInfoRequestHandler: def post(self): """从数据库获取教师信息返回给客户端""" <|body_0|> def getTeaInfo(self): """从数据库读取教师信息""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: print('收到获取教师信息的请求') self.sqlhandler = None body = ...
stack_v2_sparse_classes_75kplus_train_067208
1,819
no_license
[ { "docstring": "从数据库获取教师信息返回给客户端", "name": "post", "signature": "def post(self)" }, { "docstring": "从数据库读取教师信息", "name": "getTeaInfo", "signature": "def getTeaInfo(self)" } ]
2
stack_v2_sparse_classes_30k_train_053025
Implement the Python class `TeaInfoRequestHandler` described below. Class description: Implement the TeaInfoRequestHandler class. Method signatures and docstrings: - def post(self): 从数据库获取教师信息返回给客户端 - def getTeaInfo(self): 从数据库读取教师信息
Implement the Python class `TeaInfoRequestHandler` described below. Class description: Implement the TeaInfoRequestHandler class. Method signatures and docstrings: - def post(self): 从数据库获取教师信息返回给客户端 - def getTeaInfo(self): 从数据库读取教师信息 <|skeleton|> class TeaInfoRequestHandler: def post(self): """从数据库获取教师信...
b28eb4163b02bd0a931653b94851592f2654b199
<|skeleton|> class TeaInfoRequestHandler: def post(self): """从数据库获取教师信息返回给客户端""" <|body_0|> def getTeaInfo(self): """从数据库读取教师信息""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TeaInfoRequestHandler: def post(self): """从数据库获取教师信息返回给客户端""" try: print('收到获取教师信息的请求') self.sqlhandler = None body = json.loads(self.request.body) self.TeaUid = body['teaUid'] if self.getTeaInfo(): self.write({'succes...
the_stack_v2_python_sparse
server/teacher/TeaInfoRequestHandler.py
lyh-ADT/edu-app
train
1
1d555060c191b81e72dbeedb761a6de5c9dc12bf
[ "if not root:\n return ''\ns = []\nq = collections.deque()\nq.append(root)\nwhile q:\n node = q.popleft()\n if node:\n s.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\n else:\n s.append('null')\nres = ','.join(s)\nreturn res", "if not data:\n return ...
<|body_start_0|> if not root: return '' s = [] q = collections.deque() q.append(root) while q: node = q.popleft() if node: s.append(str(node.val)) q.append(node.left) q.append(node.right) ...
Codec
[ "MIT" ]
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_067209
1,224
permissive
[ { "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:...
95ca845e40c7c9f8ba589a45332791d5bbf49bbf
<|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 '' s = [] q = collections.deque() q.append(root) while q: node = q.popleft() if node: ...
the_stack_v2_python_sparse
Tree/Leetcode 297. Serialize and Deserialize Binary Tree.py
sriharsha004/LeetCode
train
0
ec8c9badd21860ebf1ee710ba28f854561fe00b9
[ "len_s = len(s)\nflags = []\nfor i in range(len_s // 2):\n if (len_s - i - 1) % (i + 1) != 0:\n continue\n target = s[0:i + 1]\n flag = True\n j = i + 1\n tmp = s[j:]\n while flag:\n if tmp[0:i + 1] != target:\n flag = False\n j += i + 1\n if j < len_s:\n ...
<|body_start_0|> len_s = len(s) flags = [] for i in range(len_s // 2): if (len_s - i - 1) % (i + 1) != 0: continue target = s[0:i + 1] flag = True j = i + 1 tmp = s[j:] while flag: if tmp[0:i ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def repeatedSubstringPattern(self, s: str) -> bool: """Mine""" <|body_0|> def repeatedSubstringPattern(self, s): """枚举""" <|body_1|> <|end_skeleton|> <|body_start_0|> len_s = len(s) flags = [] for i in range(len_s // 2): ...
stack_v2_sparse_classes_75kplus_train_067210
1,113
no_license
[ { "docstring": "Mine", "name": "repeatedSubstringPattern", "signature": "def repeatedSubstringPattern(self, s: str) -> bool" }, { "docstring": "枚举", "name": "repeatedSubstringPattern", "signature": "def repeatedSubstringPattern(self, s)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def repeatedSubstringPattern(self, s: str) -> bool: Mine - def repeatedSubstringPattern(self, s): 枚举
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def repeatedSubstringPattern(self, s: str) -> bool: Mine - def repeatedSubstringPattern(self, s): 枚举 <|skeleton|> class Solution: def repeatedSubstringPattern(self, s: str)...
ae191a449619418e3eba23f18574c7841e7ba52a
<|skeleton|> class Solution: def repeatedSubstringPattern(self, s: str) -> bool: """Mine""" <|body_0|> def repeatedSubstringPattern(self, s): """枚举""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def repeatedSubstringPattern(self, s: str) -> bool: """Mine""" len_s = len(s) flags = [] for i in range(len_s // 2): if (len_s - i - 1) % (i + 1) != 0: continue target = s[0:i + 1] flag = True j = i + 1 ...
the_stack_v2_python_sparse
lc/459.py
zealfory/dive_python
train
0
c3b2dc381ad3ba2ddfdff0e05eb2ebcceb363bff
[ "self.protocol = protocol\nself.srp = srp\nself._atv_salt = None\nself._atv_pub_key = None", "self.srp.initialize()\nawait self.protocol.start(skip_initial_messages=True)\nmsg = messages.crypto_pairing({TlvValue.Method: b'\\x00', TlvValue.SeqNo: b'\\x01'}, is_pairing=True)\nresp = await self.protocol.send_and_rec...
<|body_start_0|> self.protocol = protocol self.srp = srp self._atv_salt = None self._atv_pub_key = None <|end_body_0|> <|body_start_1|> self.srp.initialize() await self.protocol.start(skip_initial_messages=True) msg = messages.crypto_pairing({TlvValue.Method: b'\...
Perform pairing and return new credentials.
MrpPairSetupProcedure
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MrpPairSetupProcedure: """Perform pairing and return new credentials.""" def __init__(self, protocol, srp): """Initialize a new MrpPairingHandler.""" <|body_0|> async def start_pairing(self): """Start pairing procedure.""" <|body_1|> async def finish...
stack_v2_sparse_classes_75kplus_train_067211
4,068
permissive
[ { "docstring": "Initialize a new MrpPairingHandler.", "name": "__init__", "signature": "def __init__(self, protocol, srp)" }, { "docstring": "Start pairing procedure.", "name": "start_pairing", "signature": "async def start_pairing(self)" }, { "docstring": "Finish pairing process...
3
null
Implement the Python class `MrpPairSetupProcedure` described below. Class description: Perform pairing and return new credentials. Method signatures and docstrings: - def __init__(self, protocol, srp): Initialize a new MrpPairingHandler. - async def start_pairing(self): Start pairing procedure. - async def finish_pai...
Implement the Python class `MrpPairSetupProcedure` described below. Class description: Perform pairing and return new credentials. Method signatures and docstrings: - def __init__(self, protocol, srp): Initialize a new MrpPairingHandler. - async def start_pairing(self): Start pairing procedure. - async def finish_pai...
05ca46d2a8bbc8e725ad63794d14b2d1fb9913fa
<|skeleton|> class MrpPairSetupProcedure: """Perform pairing and return new credentials.""" def __init__(self, protocol, srp): """Initialize a new MrpPairingHandler.""" <|body_0|> async def start_pairing(self): """Start pairing procedure.""" <|body_1|> async def finish...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MrpPairSetupProcedure: """Perform pairing and return new credentials.""" def __init__(self, protocol, srp): """Initialize a new MrpPairingHandler.""" self.protocol = protocol self.srp = srp self._atv_salt = None self._atv_pub_key = None async def start_pairing...
the_stack_v2_python_sparse
pyatv/protocols/mrp/auth.py
postlund/pyatv
train
749
b2a45618b02c9babe1661231eefdf1d309e6fe6d
[ "assert isinstance(response, scrapy.http.response.html.HtmlResponse)\ncurboard = response.selector.xpath('//div[contains(@class, \"titleBar\")]/h1/text()').extract()\nlast_page = MAX_PAGE[curboard[0].lower()]\n'try:\\n last_page = int(response.selector.xpath(\\'//nav/a[@class=\"PageNavNext\"]/following::...
<|body_start_0|> assert isinstance(response, scrapy.http.response.html.HtmlResponse) curboard = response.selector.xpath('//div[contains(@class, "titleBar")]/h1/text()').extract() last_page = MAX_PAGE[curboard[0].lower()] 'try:\n last_page = int(response.selector.xpath(\'//nav/...
scrape reports from angling addicts forum
worldseafishingAfloatSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class worldseafishingAfloatSpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ...""" <|body_0|> def crawl_board_threads(sel...
stack_v2_sparse_classes_75kplus_train_067212
9,045
no_license
[ { "docstring": "generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ...", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "crawl", "name": "crawl_board_threads", "signature": "def crawl_board_t...
3
stack_v2_sparse_classes_30k_train_001682
Implement the Python class `worldseafishingAfloatSpider` described below. Class description: scrape reports from angling addicts forum Method signatures and docstrings: - def parse(self, response): generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ....
Implement the Python class `worldseafishingAfloatSpider` described below. Class description: scrape reports from angling addicts forum Method signatures and docstrings: - def parse(self, response): generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ....
9123aa6baf538b662143b9098d963d55165e8409
<|skeleton|> class worldseafishingAfloatSpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ...""" <|body_0|> def crawl_board_threads(sel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class worldseafishingAfloatSpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ...""" assert isinstance(response, scrapy.http.response.html.Ht...
the_stack_v2_python_sparse
imgscrape/spiders/worldseafishing_reports.py
gmonkman/python
train
0
240cdfff2b352b2e00ce100211ed85bbe16404c0
[ "if connection_mode is None:\n connection_mode = pybullet.DIRECT\nself._client = pybullet.connect(pybullet.SHARED_MEMORY)\nif self._client < 0:\n self._client = pybullet.connect(connection_mode, options=options)\nself._shapes = {}", "try:\n pybullet.disconnect(physicsClientId=self._client)\nexcept pybull...
<|body_start_0|> if connection_mode is None: connection_mode = pybullet.DIRECT self._client = pybullet.connect(pybullet.SHARED_MEMORY) if self._client < 0: self._client = pybullet.connect(connection_mode, options=options) self._shapes = {} <|end_body_0|> <|body_s...
A wrapper for pybullet to manage different clients.
MyBulletClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyBulletClient: """A wrapper for pybullet to manage different clients.""" def __init__(self, connection_mode=None, options=''): """Create a simulation and connect to it.""" <|body_0|> def __del__(self): """Clean up connection if not already done.""" <|bod...
stack_v2_sparse_classes_75kplus_train_067213
28,029
permissive
[ { "docstring": "Create a simulation and connect to it.", "name": "__init__", "signature": "def __init__(self, connection_mode=None, options='')" }, { "docstring": "Clean up connection if not already done.", "name": "__del__", "signature": "def __del__(self)" }, { "docstring": "In...
3
stack_v2_sparse_classes_30k_train_000547
Implement the Python class `MyBulletClient` described below. Class description: A wrapper for pybullet to manage different clients. Method signatures and docstrings: - def __init__(self, connection_mode=None, options=''): Create a simulation and connect to it. - def __del__(self): Clean up connection if not already d...
Implement the Python class `MyBulletClient` described below. Class description: A wrapper for pybullet to manage different clients. Method signatures and docstrings: - def __init__(self, connection_mode=None, options=''): Create a simulation and connect to it. - def __del__(self): Clean up connection if not already d...
cdd9bbdc2a3a832be24f20105b8c9fe28149cb63
<|skeleton|> class MyBulletClient: """A wrapper for pybullet to manage different clients.""" def __init__(self, connection_mode=None, options=''): """Create a simulation and connect to it.""" <|body_0|> def __del__(self): """Clean up connection if not already done.""" <|bod...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyBulletClient: """A wrapper for pybullet to manage different clients.""" def __init__(self, connection_mode=None, options=''): """Create a simulation and connect to it.""" if connection_mode is None: connection_mode = pybullet.DIRECT self._client = pybullet.connect(py...
the_stack_v2_python_sparse
rlscope/profiler/clib_wrap.py
UofT-EcoSystem/rlscope
train
42
8c7e68cb4c9ff1e92b2d275f71f80f8ee84446da
[ "super(StackedLSTMCell, self).__init__()\nself.hidden_dim = hidden_dim\nself.num_layers = num_layers\nself.lstm_cells = nn.ModuleList([nn.LSTMCell(hidden_dim, hidden_dim) for _ in range(num_layers)])\nself.fc_layers = nn.ModuleList([nn.Sequential(nn.Linear(hidden_dim, hidden_dim), nn.ELU()) for _ in range(num_layer...
<|body_start_0|> super(StackedLSTMCell, self).__init__() self.hidden_dim = hidden_dim self.num_layers = num_layers self.lstm_cells = nn.ModuleList([nn.LSTMCell(hidden_dim, hidden_dim) for _ in range(num_layers)]) self.fc_layers = nn.ModuleList([nn.Sequential(nn.Linear(hidden_dim,...
A looping stack of LSTM cells, with FC()=>ELU() linking between them, as well as both residual connections that additively hop over each RNN block. Between each layer, we have a fully-connected [hidden_dim=>hidden_dim] layer that transforms the hidden state into the input for the next layer.
StackedLSTMCell
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StackedLSTMCell: """A looping stack of LSTM cells, with FC()=>ELU() linking between them, as well as both residual connections that additively hop over each RNN block. Between each layer, we have a fully-connected [hidden_dim=>hidden_dim] layer that transforms the hidden state into the input for ...
stack_v2_sparse_classes_75kplus_train_067214
10,130
no_license
[ { "docstring": "Construct a stacked LSTM cell.", "name": "__init__", "signature": "def __init__(self, hidden_dim, num_layers)" }, { "docstring": "Run over one iteration. Args: * x: the bottom-most input. * h0s: ... * c0s: ... Returns: * outs: an output FloatTensor Variables of shape (batch_size,...
2
stack_v2_sparse_classes_30k_train_024854
Implement the Python class `StackedLSTMCell` described below. Class description: A looping stack of LSTM cells, with FC()=>ELU() linking between them, as well as both residual connections that additively hop over each RNN block. Between each layer, we have a fully-connected [hidden_dim=>hidden_dim] layer that transfor...
Implement the Python class `StackedLSTMCell` described below. Class description: A looping stack of LSTM cells, with FC()=>ELU() linking between them, as well as both residual connections that additively hop over each RNN block. Between each layer, we have a fully-connected [hidden_dim=>hidden_dim] layer that transfor...
7ad943d9cc7a6872a14bba5239a99755f70db4cd
<|skeleton|> class StackedLSTMCell: """A looping stack of LSTM cells, with FC()=>ELU() linking between them, as well as both residual connections that additively hop over each RNN block. Between each layer, we have a fully-connected [hidden_dim=>hidden_dim] layer that transforms the hidden state into the input for ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StackedLSTMCell: """A looping stack of LSTM cells, with FC()=>ELU() linking between them, as well as both residual connections that additively hop over each RNN block. Between each layer, we have a fully-connected [hidden_dim=>hidden_dim] layer that transforms the hidden state into the input for the next laye...
the_stack_v2_python_sparse
modules/rnn_decoder.py
paultsw/wavenet-speech
train
0
390d4bd508572d70e9645bc0b2b5017ece2b9f97
[ "self.scales = scales\nself.ratios = ratios\nself.feature_strides = feature_strides", "pad_shape = calc_batch_padded_shape(img_metas)\nfeature_shapes = [(pad_shape[0] // stride, pad_shape[1] // stride) for stride in self.feature_strides]\nanchors = [self._generate_level_anchors(level, feature_shape) for level, fe...
<|body_start_0|> self.scales = scales self.ratios = ratios self.feature_strides = feature_strides <|end_body_0|> <|body_start_1|> pad_shape = calc_batch_padded_shape(img_metas) feature_shapes = [(pad_shape[0] // stride, pad_shape[1] // stride) for stride in self.feature_strides]...
AnchorGenerator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnchorGenerator: def __init__(self, scales=(32, 64, 128, 256, 512), ratios=(0.5, 1, 2), feature_strides=(4, 8, 16, 32, 64)): """Anchor Generator Attributes --- scales: 1D array of anchor sizes in pixels. ratios: 1D array of anchor ratios of width/height. feature_strides: Stride of the fe...
stack_v2_sparse_classes_75kplus_train_067215
4,368
permissive
[ { "docstring": "Anchor Generator Attributes --- scales: 1D array of anchor sizes in pixels. ratios: 1D array of anchor ratios of width/height. feature_strides: Stride of the feature map relative to the image in pixels.", "name": "__init__", "signature": "def __init__(self, scales=(32, 64, 128, 256, 512)...
4
null
Implement the Python class `AnchorGenerator` described below. Class description: Implement the AnchorGenerator class. Method signatures and docstrings: - def __init__(self, scales=(32, 64, 128, 256, 512), ratios=(0.5, 1, 2), feature_strides=(4, 8, 16, 32, 64)): Anchor Generator Attributes --- scales: 1D array of anch...
Implement the Python class `AnchorGenerator` described below. Class description: Implement the AnchorGenerator class. Method signatures and docstrings: - def __init__(self, scales=(32, 64, 128, 256, 512), ratios=(0.5, 1, 2), feature_strides=(4, 8, 16, 32, 64)): Anchor Generator Attributes --- scales: 1D array of anch...
f756b811ab31c9dab2a8f8afe68f46465422f64b
<|skeleton|> class AnchorGenerator: def __init__(self, scales=(32, 64, 128, 256, 512), ratios=(0.5, 1, 2), feature_strides=(4, 8, 16, 32, 64)): """Anchor Generator Attributes --- scales: 1D array of anchor sizes in pixels. ratios: 1D array of anchor ratios of width/height. feature_strides: Stride of the fe...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AnchorGenerator: def __init__(self, scales=(32, 64, 128, 256, 512), ratios=(0.5, 1, 2), feature_strides=(4, 8, 16, 32, 64)): """Anchor Generator Attributes --- scales: 1D array of anchor sizes in pixels. ratios: 1D array of anchor ratios of width/height. feature_strides: Stride of the feature map rela...
the_stack_v2_python_sparse
detection/core/anchor/anchor_generator.py
HirataYurina/cascade-rcnn-tf2.2
train
1
44719f8ca7fbed3e3b076ea4b8065924a27f2049
[ "self.child = child\nif not child:\n self.child = self\nself.logger = logger\nif not self.logger:\n logargs = utils.logargs(child.__class__, __file__)\n self.logger = utils.setup_logger(logargs.name, logargs.file, extra=logargs.extra)\n self.log('No logger passed into constructor. Creating new logger.')...
<|body_start_0|> self.child = child if not child: self.child = self self.logger = logger if not self.logger: logargs = utils.logargs(child.__class__, __file__) self.logger = utils.setup_logger(logargs.name, logargs.file, extra=logargs.extra) ...
Creates a logger for the subclasses of this class. Handles printing of log messages to log file.
Loggable
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Loggable: """Creates a logger for the subclasses of this class. Handles printing of log messages to log file.""" def __init__(self, child=None, logger=None): """Sets the class logger if passed in. If no logger then uses the secondary option of creating a logger using the logargs argu...
stack_v2_sparse_classes_75kplus_train_067216
2,076
permissive
[ { "docstring": "Sets the class logger if passed in. If no logger then uses the secondary option of creating a logger using the logargs argument. If no child is passed in, meaning this class is not being subclassed but rather used as a standalone object, then it will set its own child as itself.", "name": "_...
2
null
Implement the Python class `Loggable` described below. Class description: Creates a logger for the subclasses of this class. Handles printing of log messages to log file. Method signatures and docstrings: - def __init__(self, child=None, logger=None): Sets the class logger if passed in. If no logger then uses the sec...
Implement the Python class `Loggable` described below. Class description: Creates a logger for the subclasses of this class. Handles printing of log messages to log file. Method signatures and docstrings: - def __init__(self, child=None, logger=None): Sets the class logger if passed in. If no logger then uses the sec...
78f3637b4c03c11d7f6ef15b20a1acf699d4be24
<|skeleton|> class Loggable: """Creates a logger for the subclasses of this class. Handles printing of log messages to log file.""" def __init__(self, child=None, logger=None): """Sets the class logger if passed in. If no logger then uses the secondary option of creating a logger using the logargs argu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Loggable: """Creates a logger for the subclasses of this class. Handles printing of log messages to log file.""" def __init__(self, child=None, logger=None): """Sets the class logger if passed in. If no logger then uses the secondary option of creating a logger using the logargs argument. If no c...
the_stack_v2_python_sparse
source/logger.py
whitegreyblack/PyCurses
train
0
680e48bfa094f2d671311329f9b0a6633f1dcfb9
[ "type_option: Optional[NotificationSettingTypes] = kwargs.get('type')\nactor_mapping = {recipient.actor_id: recipient for recipient in item_list}\nnotifications_settings = NotificationSetting.objects._filter(type=type_option, target_ids=actor_mapping.keys())\nresults: MutableMapping[Union['Team', 'User'], MutableMa...
<|body_start_0|> type_option: Optional[NotificationSettingTypes] = kwargs.get('type') actor_mapping = {recipient.actor_id: recipient for recipient in item_list} notifications_settings = NotificationSetting.objects._filter(type=type_option, target_ids=actor_mapping.keys()) results: Mutabl...
This Serializer fetches and serializes NotificationSettings for a list of targets (users or teams.) Pass filters like `project=project` and `type=NotificationSettingTypes.DEPLOY` to kwargs.
NotificationSettingsSerializer
[ "Apache-2.0", "BUSL-1.1" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NotificationSettingsSerializer: """This Serializer fetches and serializes NotificationSettings for a list of targets (users or teams.) Pass filters like `project=project` and `type=NotificationSettingTypes.DEPLOY` to kwargs.""" def get_attrs(self, item_list: Iterable[Union['Team', 'User']], ...
stack_v2_sparse_classes_75kplus_train_067217
4,722
permissive
[ { "docstring": "This takes a list of recipients (which are either Users or Teams, because both can have Notification Settings). The function returns a mapping of targets to flat lists of object to be passed to the `serialize` function. :param item_list: Either a Set of User or Team objects whose notification se...
2
null
Implement the Python class `NotificationSettingsSerializer` described below. Class description: This Serializer fetches and serializes NotificationSettings for a list of targets (users or teams.) Pass filters like `project=project` and `type=NotificationSettingTypes.DEPLOY` to kwargs. Method signatures and docstrings...
Implement the Python class `NotificationSettingsSerializer` described below. Class description: This Serializer fetches and serializes NotificationSettings for a list of targets (users or teams.) Pass filters like `project=project` and `type=NotificationSettingTypes.DEPLOY` to kwargs. Method signatures and docstrings...
d9dd4f382f96b5c4576b64cbf015db651556c18b
<|skeleton|> class NotificationSettingsSerializer: """This Serializer fetches and serializes NotificationSettings for a list of targets (users or teams.) Pass filters like `project=project` and `type=NotificationSettingTypes.DEPLOY` to kwargs.""" def get_attrs(self, item_list: Iterable[Union['Team', 'User']], ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NotificationSettingsSerializer: """This Serializer fetches and serializes NotificationSettings for a list of targets (users or teams.) Pass filters like `project=project` and `type=NotificationSettingTypes.DEPLOY` to kwargs.""" def get_attrs(self, item_list: Iterable[Union['Team', 'User']], user: User, *...
the_stack_v2_python_sparse
src/sentry/api/serializers/models/notification_setting.py
nagyist/sentry
train
0
a858ed5244385c365bf716a1cab15a68c7b681f0
[ "self.__main_line = main_line\nself.__position = position\nself.__where = where", "if self.__where == 0:\n follower.move_to(self.__main_line.get_start() + self.__position)\nelif self.__where == 1:\n follower.move_to(self.__main_line.get_end() + self.__position)\nelse:\n raise AssertionError('whwre should...
<|body_start_0|> self.__main_line = main_line self.__position = position self.__where = where <|end_body_0|> <|body_start_1|> if self.__where == 0: follower.move_to(self.__main_line.get_start() + self.__position) elif self.__where == 1: follower.move_to(s...
Glue two objects (a point at the edge of a line) for updater Put an follower object next to the end point of a line. + follower(right(where = 1)) / / / line / / follower(left(where = 0)) + This uses move_to() instead of next_to().
Glue_line_point_edge_rotate_updater
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Glue_line_point_edge_rotate_updater: """Glue two objects (a point at the edge of a line) for updater Put an follower object next to the end point of a line. + follower(right(where = 1)) / / / line / / follower(left(where = 0)) + This uses move_to() instead of next_to().""" def __init__(self,...
stack_v2_sparse_classes_75kplus_train_067218
28,855
permissive
[ { "docstring": "param[in] main_line the main object but a line, follower object will follow this main line object via updater param[in] position next_to position param[in] where 0 ... start, 1 ... end", "name": "__init__", "signature": "def __init__(self, main_line, position=LEFT, where=0)" }, { ...
2
stack_v2_sparse_classes_30k_train_017911
Implement the Python class `Glue_line_point_edge_rotate_updater` described below. Class description: Glue two objects (a point at the edge of a line) for updater Put an follower object next to the end point of a line. + follower(right(where = 1)) / / / line / / follower(left(where = 0)) + This uses move_to() instead o...
Implement the Python class `Glue_line_point_edge_rotate_updater` described below. Class description: Glue two objects (a point at the edge of a line) for updater Put an follower object next to the end point of a line. + follower(right(where = 1)) / / / line / / follower(left(where = 0)) + This uses move_to() instead o...
ff8b30ff6b6a8ea746e6739ac170784a08491e7a
<|skeleton|> class Glue_line_point_edge_rotate_updater: """Glue two objects (a point at the edge of a line) for updater Put an follower object next to the end point of a line. + follower(right(where = 1)) / / / line / / follower(left(where = 0)) + This uses move_to() instead of next_to().""" def __init__(self,...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Glue_line_point_edge_rotate_updater: """Glue two objects (a point at the edge of a line) for updater Put an follower object next to the end point of a line. + follower(right(where = 1)) / / / line / / follower(left(where = 0)) + This uses move_to() instead of next_to().""" def __init__(self, main_line, p...
the_stack_v2_python_sparse
202008_corner_cube_mirror/03_corresponding_angles.py
yamauchih/3b1b_manim_examples
train
1
52ac05de1d1f508b94dee705a4401edafc44538a
[ "def parse(st):\n stack = []\n for x in st:\n if x == '#' and stack:\n stack.pop()\n elif x.isalpha():\n stack.append(x)\n return stack\nreturn parse(S) == parse(T)", "i, j, del1, del2 = (len(S) - 1, len(T) - 1, 0, 0)\nwhile i >= 0 or j >= 0:\n while i >= 0:\n ...
<|body_start_0|> def parse(st): stack = [] for x in st: if x == '#' and stack: stack.pop() elif x.isalpha(): stack.append(x) return stack return parse(S) == parse(T) <|end_body_0|> <|body_start_1...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def backspaceCompare1(self, S: str, T: str) -> bool: """常规解法,利用栈,时间空间复杂度都是O(S+T)即O(n)""" <|body_0|> def backspaceCompare2(self, S: str, T: str) -> bool: """Follow up: 要求空间复杂度O(1),双指针逆序遍历""" <|body_1|> <|end_skeleton|> <|body_start_0|> def ...
stack_v2_sparse_classes_75kplus_train_067219
1,998
no_license
[ { "docstring": "常规解法,利用栈,时间空间复杂度都是O(S+T)即O(n)", "name": "backspaceCompare1", "signature": "def backspaceCompare1(self, S: str, T: str) -> bool" }, { "docstring": "Follow up: 要求空间复杂度O(1),双指针逆序遍历", "name": "backspaceCompare2", "signature": "def backspaceCompare2(self, S: str, T: str) -> bo...
2
stack_v2_sparse_classes_30k_train_043677
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def backspaceCompare1(self, S: str, T: str) -> bool: 常规解法,利用栈,时间空间复杂度都是O(S+T)即O(n) - def backspaceCompare2(self, S: str, T: str) -> bool: Follow up: 要求空间复杂度O(1),双指针逆序遍历
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def backspaceCompare1(self, S: str, T: str) -> bool: 常规解法,利用栈,时间空间复杂度都是O(S+T)即O(n) - def backspaceCompare2(self, S: str, T: str) -> bool: Follow up: 要求空间复杂度O(1),双指针逆序遍历 <|skelet...
2bbb1640589aab34f2bc42489283033cc11fb885
<|skeleton|> class Solution: def backspaceCompare1(self, S: str, T: str) -> bool: """常规解法,利用栈,时间空间复杂度都是O(S+T)即O(n)""" <|body_0|> def backspaceCompare2(self, S: str, T: str) -> bool: """Follow up: 要求空间复杂度O(1),双指针逆序遍历""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def backspaceCompare1(self, S: str, T: str) -> bool: """常规解法,利用栈,时间空间复杂度都是O(S+T)即O(n)""" def parse(st): stack = [] for x in st: if x == '#' and stack: stack.pop() elif x.isalpha(): stack.a...
the_stack_v2_python_sparse
844_backspace-string-compare.py
helloocc/algorithm
train
1
2de5036a7a089c7c99425d83c4510d2e8881f2cb
[ "try:\n queryset = self.get_all_objects(User)\n print(queryset)\n serializer = serializers.UserSerializer(queryset, many=True)\n return Utils.dispatch_success(request, serializer.data)\nexcept Exception as e:\n return self.internal_server_error(request, e)", "try:\n serializer = serializers.Crea...
<|body_start_0|> try: queryset = self.get_all_objects(User) print(queryset) serializer = serializers.UserSerializer(queryset, many=True) return Utils.dispatch_success(request, serializer.data) except Exception as e: return self.internal_server_...
Lists all users
UserList
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserList: """Lists all users""" def get(self, request, *args, **kwargs): """Get the List of users :param request: :param args: :param kwargs: :return:""" <|body_0|> def post(self, request, *args, **kwargs): """Create New User :param request: { "username" : "98765...
stack_v2_sparse_classes_75kplus_train_067220
4,727
permissive
[ { "docstring": "Get the List of users :param request: :param args: :param kwargs: :return:", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Create New User :param request: { \"username\" : \"9876543210\", \"first_name\":\"Team 1\", \"email\" : \"team1@gm...
2
stack_v2_sparse_classes_30k_train_009429
Implement the Python class `UserList` described below. Class description: Lists all users Method signatures and docstrings: - def get(self, request, *args, **kwargs): Get the List of users :param request: :param args: :param kwargs: :return: - def post(self, request, *args, **kwargs): Create New User :param request: ...
Implement the Python class `UserList` described below. Class description: Lists all users Method signatures and docstrings: - def get(self, request, *args, **kwargs): Get the List of users :param request: :param args: :param kwargs: :return: - def post(self, request, *args, **kwargs): Create New User :param request: ...
1e31affddf60d2de72445a85dd2055bdeba6f670
<|skeleton|> class UserList: """Lists all users""" def get(self, request, *args, **kwargs): """Get the List of users :param request: :param args: :param kwargs: :return:""" <|body_0|> def post(self, request, *args, **kwargs): """Create New User :param request: { "username" : "98765...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserList: """Lists all users""" def get(self, request, *args, **kwargs): """Get the List of users :param request: :param args: :param kwargs: :return:""" try: queryset = self.get_all_objects(User) print(queryset) serializer = serializers.UserSerializer(...
the_stack_v2_python_sparse
the_mechanic_backend/v0/accounts/views.py
muthukumar4999/the-mechanic-backend
train
0
c086397c2c0a6dedb1fd39d2e2e2493ce9d92e1f
[ "if self.expires:\n return datetime.datetime.utcnow() > self.expires\nreturn False", "if self.refresh_token_expires:\n return datetime.datetime.utcnow() > self.refresh_token_expires\nreturn False", "if not self.expires:\n return None\nnow = datetime.datetime.utcnow()\nttl = self.expires - now\nttl_in_s...
<|body_start_0|> if self.expires: return datetime.datetime.utcnow() > self.expires return False <|end_body_0|> <|body_start_1|> if self.refresh_token_expires: return datetime.datetime.utcnow() > self.refresh_token_expires return False <|end_body_1|> <|body_start...
An API access token for a user. These fall into two categories: - Long-lived developer tokens, which are generated for an account for third-party integrations. These do not expire. - Temporary access tokens, which are currently only issued from JWTs generated by third party `AuthClient`\\\\ s. These do expire.
Token
[ "BSD-2-Clause", "BSD-3-Clause", "BSD-2-Clause-Views" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Token: """An API access token for a user. These fall into two categories: - Long-lived developer tokens, which are generated for an account for third-party integrations. These do not expire. - Temporary access tokens, which are currently only issued from JWTs generated by third party `AuthClient`...
stack_v2_sparse_classes_75kplus_train_067221
2,917
permissive
[ { "docstring": "Return True if this access token has expired, False otherwise.", "name": "expired", "signature": "def expired(self)" }, { "docstring": "Return True if this refresh token has expired, False otherwise.", "name": "refresh_token_expired", "signature": "def refresh_token_expir...
3
null
Implement the Python class `Token` described below. Class description: An API access token for a user. These fall into two categories: - Long-lived developer tokens, which are generated for an account for third-party integrations. These do not expire. - Temporary access tokens, which are currently only issued from JWT...
Implement the Python class `Token` described below. Class description: An API access token for a user. These fall into two categories: - Long-lived developer tokens, which are generated for an account for third-party integrations. These do not expire. - Temporary access tokens, which are currently only issued from JWT...
232446d776fdb906d2fb253cf0a409c6813a08d6
<|skeleton|> class Token: """An API access token for a user. These fall into two categories: - Long-lived developer tokens, which are generated for an account for third-party integrations. These do not expire. - Temporary access tokens, which are currently only issued from JWTs generated by third party `AuthClient`...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Token: """An API access token for a user. These fall into two categories: - Long-lived developer tokens, which are generated for an account for third-party integrations. These do not expire. - Temporary access tokens, which are currently only issued from JWTs generated by third party `AuthClient`\\\\ s. These...
the_stack_v2_python_sparse
h/models/token.py
hypothesis/h
train
2,558
c3e0e36d60c86b73441ae080f8dbe72e548d7451
[ "self.fh = filehandle\nself.counter = 0\nself.chunk = chunksize\nself.extraspaces = extraspaces", "self.fh.write(' ' * self.extraspaces)\nself.fh.write(f2s(value))\nself.counter += 1\nif self.counter == self.chunk:\n self.fh.write('\\n')\n self.counter = 0", "if self.counter != 0:\n self.fh.write('\\n'...
<|body_start_0|> self.fh = filehandle self.counter = 0 self.chunk = chunksize self.extraspaces = extraspaces <|end_body_0|> <|body_start_1|> self.fh.write(' ' * self.extraspaces) self.fh.write(f2s(value)) self.counter += 1 if self.counter == self.chunk: ...
This outputs values in lines, inserting newlines when needed.
ChunkOutput
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChunkOutput: """This outputs values in lines, inserting newlines when needed.""" def __init__(self, filehandle, chunksize=5, extraspaces=0): """filehandle output to write to chunksize number of values on a line extraspaces number of extra spaces between outputs""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_067222
2,205
permissive
[ { "docstring": "filehandle output to write to chunksize number of values on a line extraspaces number of extra spaces between outputs", "name": "__init__", "signature": "def __init__(self, filehandle, chunksize=5, extraspaces=0)" }, { "docstring": "\" Write a value to the output, adding a newlin...
3
stack_v2_sparse_classes_30k_train_049171
Implement the Python class `ChunkOutput` described below. Class description: This outputs values in lines, inserting newlines when needed. Method signatures and docstrings: - def __init__(self, filehandle, chunksize=5, extraspaces=0): filehandle output to write to chunksize number of values on a line extraspaces numb...
Implement the Python class `ChunkOutput` described below. Class description: This outputs values in lines, inserting newlines when needed. Method signatures and docstrings: - def __init__(self, filehandle, chunksize=5, extraspaces=0): filehandle output to write to chunksize number of values on a line extraspaces numb...
af351c4aa4a40aa5bb5bdaa8083575344c0827e2
<|skeleton|> class ChunkOutput: """This outputs values in lines, inserting newlines when needed.""" def __init__(self, filehandle, chunksize=5, extraspaces=0): """filehandle output to write to chunksize number of values on a line extraspaces number of extra spaces between outputs""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ChunkOutput: """This outputs values in lines, inserting newlines when needed.""" def __init__(self, filehandle, chunksize=5, extraspaces=0): """filehandle output to write to chunksize number of values on a line extraspaces number of extra spaces between outputs""" self.fh = filehandle ...
the_stack_v2_python_sparse
pleque/io/_fileutils.py
kripnerl/pleque
train
15
994230ab0479ed58e3b84eb43673850649f3c682
[ "data = self.data\ncode = data['code']\nreturn f'{PLATFORM_URL}reset-password/{code}'", "payload = super().transform()\ndata = self.data\nexpires = data.get('expiration_date')\nif expires.endswith('Z'):\n expires = expires[:-1]\nexpires = self._format_datetime(expires)\npayload[0]['data']['CODE'] = data.get('c...
<|body_start_0|> data = self.data code = data['code'] return f'{PLATFORM_URL}reset-password/{code}' <|end_body_0|> <|body_start_1|> payload = super().transform() data = self.data expires = data.get('expiration_date') if expires.endswith('Z'): expires ...
Send an email to the user the details of a password reset request.
PasswordReset
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PasswordReset: """Send an email to the user the details of a password reset request.""" def _action_url(self) -> str: """Return the action URL for the object.""" <|body_0|> def transform(self) -> t.List[dict]: """Transform data.""" <|body_1|> <|end_skele...
stack_v2_sparse_classes_75kplus_train_067223
4,062
no_license
[ { "docstring": "Return the action URL for the object.", "name": "_action_url", "signature": "def _action_url(self) -> str" }, { "docstring": "Transform data.", "name": "transform", "signature": "def transform(self) -> t.List[dict]" } ]
2
stack_v2_sparse_classes_30k_train_037122
Implement the Python class `PasswordReset` described below. Class description: Send an email to the user the details of a password reset request. Method signatures and docstrings: - def _action_url(self) -> str: Return the action URL for the object. - def transform(self) -> t.List[dict]: Transform data.
Implement the Python class `PasswordReset` described below. Class description: Send an email to the user the details of a password reset request. Method signatures and docstrings: - def _action_url(self) -> str: Return the action URL for the object. - def transform(self) -> t.List[dict]: Transform data. <|skeleton|>...
cca179f55ebc3c420426eff59b23d7c8963ca9a3
<|skeleton|> class PasswordReset: """Send an email to the user the details of a password reset request.""" def _action_url(self) -> str: """Return the action URL for the object.""" <|body_0|> def transform(self) -> t.List[dict]: """Transform data.""" <|body_1|> <|end_skele...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PasswordReset: """Send an email to the user the details of a password reset request.""" def _action_url(self) -> str: """Return the action URL for the object.""" data = self.data code = data['code'] return f'{PLATFORM_URL}reset-password/{code}' def transform(self) -> ...
the_stack_v2_python_sparse
src/briefy/choreographer/actions/mail/user.py
BriefyHQ/briefy.choreographer
train
0
ed0af6b1fc923c0c58411385cac89997e2a9a99c
[ "self.log = logging.getLogger('lapis.gyazo')\nself.headers = {'User-Agent': useragent}\nself.regex = re.compile('^(.*?\\\\.)?gyazo\\\\.com$')", "try:\n if not self.regex.match(urlsplit(submission.url).netloc):\n return None\n data = {'author': 'a gyazo.com user', 'source': submission.url, 'importer_d...
<|body_start_0|> self.log = logging.getLogger('lapis.gyazo') self.headers = {'User-Agent': useragent} self.regex = re.compile('^(.*?\\.)?gyazo\\.com$') <|end_body_0|> <|body_start_1|> try: if not self.regex.match(urlsplit(submission.url).netloc): return None ...
A gyazo.com import plugin. gyazo.com is a site for quickly uploading screen shots.
GyazoPlugin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GyazoPlugin: """A gyazo.com import plugin. gyazo.com is a site for quickly uploading screen shots.""" def __init__(self, useragent: str, **options): """Initialize the gyazo import API. :param useragent: The useragent to use for querying gyazo. :param options: Other options in the con...
stack_v2_sparse_classes_75kplus_train_067224
2,843
permissive
[ { "docstring": "Initialize the gyazo import API. :param useragent: The useragent to use for querying gyazo. :param options: Other options in the configuration. Ignored.", "name": "__init__", "signature": "def __init__(self, useragent: str, **options)" }, { "docstring": "Import a submission from ...
2
stack_v2_sparse_classes_30k_test_001648
Implement the Python class `GyazoPlugin` described below. Class description: A gyazo.com import plugin. gyazo.com is a site for quickly uploading screen shots. Method signatures and docstrings: - def __init__(self, useragent: str, **options): Initialize the gyazo import API. :param useragent: The useragent to use for...
Implement the Python class `GyazoPlugin` described below. Class description: A gyazo.com import plugin. gyazo.com is a site for quickly uploading screen shots. Method signatures and docstrings: - def __init__(self, useragent: str, **options): Initialize the gyazo import API. :param useragent: The useragent to use for...
29503bb70b7b9e47a5cea1ea03098543b1a01efb
<|skeleton|> class GyazoPlugin: """A gyazo.com import plugin. gyazo.com is a site for quickly uploading screen shots.""" def __init__(self, useragent: str, **options): """Initialize the gyazo import API. :param useragent: The useragent to use for querying gyazo. :param options: Other options in the con...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GyazoPlugin: """A gyazo.com import plugin. gyazo.com is a site for quickly uploading screen shots.""" def __init__(self, useragent: str, **options): """Initialize the gyazo import API. :param useragent: The useragent to use for querying gyazo. :param options: Other options in the configuration. I...
the_stack_v2_python_sparse
plugins/gyazo.py
spiral6/VelvetBot
train
0
da9bb410435d894fa4d5dfe710a387976b1c1818
[ "self.profile = profile\nsuper(ProfileForm, self).__init__(*args, **kwargs)\nself.fields['first_name'].initial = profile.user.first_name\nself.fields['last_name'].initial = profile.user.last_name\nself.fields['email'].initial = profile.user.email\nself.fields['email'].gender = profile.gender", "users = User.objec...
<|body_start_0|> self.profile = profile super(ProfileForm, self).__init__(*args, **kwargs) self.fields['first_name'].initial = profile.user.first_name self.fields['last_name'].initial = profile.user.last_name self.fields['email'].initial = profile.user.email self.fields['...
The ProfileForm provides a form used to update the user's informations
ProfileForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProfileForm: """The ProfileForm provides a form used to update the user's informations""" def __init__(self, profile, *args, **kwargs): """Initializes a new instance of the ChangePasswordForm class.""" <|body_0|> def clean_email(self): """Validate that the suppli...
stack_v2_sparse_classes_75kplus_train_067225
5,957
no_license
[ { "docstring": "Initializes a new instance of the ChangePasswordForm class.", "name": "__init__", "signature": "def __init__(self, profile, *args, **kwargs)" }, { "docstring": "Validate that the supplied email address is unique for the site.", "name": "clean_email", "signature": "def cle...
3
stack_v2_sparse_classes_30k_train_040088
Implement the Python class `ProfileForm` described below. Class description: The ProfileForm provides a form used to update the user's informations Method signatures and docstrings: - def __init__(self, profile, *args, **kwargs): Initializes a new instance of the ChangePasswordForm class. - def clean_email(self): Val...
Implement the Python class `ProfileForm` described below. Class description: The ProfileForm provides a form used to update the user's informations Method signatures and docstrings: - def __init__(self, profile, *args, **kwargs): Initializes a new instance of the ChangePasswordForm class. - def clean_email(self): Val...
b0702a8f7f60de6db9de7f712108e68d66f07f61
<|skeleton|> class ProfileForm: """The ProfileForm provides a form used to update the user's informations""" def __init__(self, profile, *args, **kwargs): """Initializes a new instance of the ChangePasswordForm class.""" <|body_0|> def clean_email(self): """Validate that the suppli...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProfileForm: """The ProfileForm provides a form used to update the user's informations""" def __init__(self, profile, *args, **kwargs): """Initializes a new instance of the ChangePasswordForm class.""" self.profile = profile super(ProfileForm, self).__init__(*args, **kwargs) ...
the_stack_v2_python_sparse
getdeal/apps/profiles/forms.py
PankeshGupta/getdeal
train
0
57306ecdfaf3aa610f81dae6b4c488a6adf14178
[ "rslt = super(StockMove, self)._generate_valuation_lines_data(partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id)\nif self.picking_id.currency_rate1 > 0:\n purchase_currency = self.purchase_line_id.currency_id\n purchase_price_unit = self.purchase_line_id.price_unit\n if self.p...
<|body_start_0|> rslt = super(StockMove, self)._generate_valuation_lines_data(partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id) if self.picking_id.currency_rate1 > 0: purchase_currency = self.purchase_line_id.currency_id purchase_price_unit = self.p...
StockMove
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StockMove: def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id): """Overridden from stock_account to support amount_currency on valuation lines generated from po""" <|body_0|> def _prepare_account_move_line...
stack_v2_sparse_classes_75kplus_train_067226
5,257
no_license
[ { "docstring": "Overridden from stock_account to support amount_currency on valuation lines generated from po", "name": "_generate_valuation_lines_data", "signature": "def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id)" }, { ...
2
stack_v2_sparse_classes_30k_test_002965
Implement the Python class `StockMove` described below. Class description: Implement the StockMove class. Method signatures and docstrings: - def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id): Overridden from stock_account to support amount_curre...
Implement the Python class `StockMove` described below. Class description: Implement the StockMove class. Method signatures and docstrings: - def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id): Overridden from stock_account to support amount_curre...
5ed668bda8177586695f5dc2e68a48806eccf976
<|skeleton|> class StockMove: def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id): """Overridden from stock_account to support amount_currency on valuation lines generated from po""" <|body_0|> def _prepare_account_move_line...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StockMove: def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id): """Overridden from stock_account to support amount_currency on valuation lines generated from po""" rslt = super(StockMove, self)._generate_valuation_lines_data...
the_stack_v2_python_sparse
purchase_exchange_currency_rate/models/stock.py
akradore/ACC_12
train
0
82a601333d429a6f960fede0b1563805636fb4d6
[ "self.bin_loc = bin_loc\nself.max_cube = max_cube\nself.available_cube = max_cube\nself.materials = dict()", "if material.id not in self.materials:\n self.materials[material.id] = 0\nchange = cube\nunfulfilled = 0\nif material.bin_loc != self.bin_loc:\n return cube\nif self.available_cube < 0:\n return c...
<|body_start_0|> self.bin_loc = bin_loc self.max_cube = max_cube self.available_cube = max_cube self.materials = dict() <|end_body_0|> <|body_start_1|> if material.id not in self.materials: self.materials[material.id] = 0 change = cube unfulfilled = 0...
Storage
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Storage: def __init__(self, bin_loc, max_cube): """Represents a storage space in a Distribution Center :param bin_loc: BinLocation :param max_cube: int""" <|body_0|> def update_inventory(self, material, cube): """Attempt to place an order in the storage space :param ...
stack_v2_sparse_classes_75kplus_train_067227
5,030
permissive
[ { "docstring": "Represents a storage space in a Distribution Center :param bin_loc: BinLocation :param max_cube: int", "name": "__init__", "signature": "def __init__(self, bin_loc, max_cube)" }, { "docstring": "Attempt to place an order in the storage space :param material: Material :param cube:...
3
stack_v2_sparse_classes_30k_train_049866
Implement the Python class `Storage` described below. Class description: Implement the Storage class. Method signatures and docstrings: - def __init__(self, bin_loc, max_cube): Represents a storage space in a Distribution Center :param bin_loc: BinLocation :param max_cube: int - def update_inventory(self, material, c...
Implement the Python class `Storage` described below. Class description: Implement the Storage class. Method signatures and docstrings: - def __init__(self, bin_loc, max_cube): Represents a storage space in a Distribution Center :param bin_loc: BinLocation :param max_cube: int - def update_inventory(self, material, c...
b9ed1bd924089f06854a9bd2b4a96171e4962e38
<|skeleton|> class Storage: def __init__(self, bin_loc, max_cube): """Represents a storage space in a Distribution Center :param bin_loc: BinLocation :param max_cube: int""" <|body_0|> def update_inventory(self, material, cube): """Attempt to place an order in the storage space :param ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Storage: def __init__(self, bin_loc, max_cube): """Represents a storage space in a Distribution Center :param bin_loc: BinLocation :param max_cube: int""" self.bin_loc = bin_loc self.max_cube = max_cube self.available_cube = max_cube self.materials = dict() def upd...
the_stack_v2_python_sparse
src/opm_manager/models/sku.py
mattrwyrick/OPM-Manager
train
0
f644a5f3aaba16b7e0ec73805f46bc1cf886ed81
[ "while n not in [0, 1, 4]:\n cur, n = (n, 0)\n for x in str(cur):\n x = int(x)\n n += x * x\nif n == 1:\n return True\nelse:\n return False", "seen = set()\nwhile n not in seen:\n seen.add(n)\n n = sum(((ord(x) - ord('0')) ** 2 for x in str(n)))\nreturn n == 1" ]
<|body_start_0|> while n not in [0, 1, 4]: cur, n = (n, 0) for x in str(cur): x = int(x) n += x * x if n == 1: return True else: return False <|end_body_0|> <|body_start_1|> seen = set() while n not ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isHappy1(self, n: int) -> bool: """最终如果是0,1,4,会陷入循环""" <|body_0|> def isHappy2(self, n: int) -> bool: """记录已经出现过的数字,如果再次出现则形成死循环。""" <|body_1|> <|end_skeleton|> <|body_start_0|> while n not in [0, 1, 4]: cur, n = (n, 0) ...
stack_v2_sparse_classes_75kplus_train_067228
1,030
no_license
[ { "docstring": "最终如果是0,1,4,会陷入循环", "name": "isHappy1", "signature": "def isHappy1(self, n: int) -> bool" }, { "docstring": "记录已经出现过的数字,如果再次出现则形成死循环。", "name": "isHappy2", "signature": "def isHappy2(self, n: int) -> bool" } ]
2
stack_v2_sparse_classes_30k_train_033723
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isHappy1(self, n: int) -> bool: 最终如果是0,1,4,会陷入循环 - def isHappy2(self, n: int) -> bool: 记录已经出现过的数字,如果再次出现则形成死循环。
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isHappy1(self, n: int) -> bool: 最终如果是0,1,4,会陷入循环 - def isHappy2(self, n: int) -> bool: 记录已经出现过的数字,如果再次出现则形成死循环。 <|skeleton|> class Solution: def isHappy1(self, n: int) ...
2bbb1640589aab34f2bc42489283033cc11fb885
<|skeleton|> class Solution: def isHappy1(self, n: int) -> bool: """最终如果是0,1,4,会陷入循环""" <|body_0|> def isHappy2(self, n: int) -> bool: """记录已经出现过的数字,如果再次出现则形成死循环。""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isHappy1(self, n: int) -> bool: """最终如果是0,1,4,会陷入循环""" while n not in [0, 1, 4]: cur, n = (n, 0) for x in str(cur): x = int(x) n += x * x if n == 1: return True else: return False ...
the_stack_v2_python_sparse
202_happy-number.py
helloocc/algorithm
train
1
812d66beafd7a774f5ea2094bc3e1e5125821d49
[ "self.engine = engine\nself._allocated_qubit_ids = set()\nself._deallocated_qubit_ids = set()\nself._uncompute_eng = None", "compute_eng = self.engine.next_engine\nif not isinstance(compute_eng, ComputeEngine):\n raise NoComputeSectionError(\"Invalid call to CustomUncompute: No corresponding 'with Compute' sta...
<|body_start_0|> self.engine = engine self._allocated_qubit_ids = set() self._deallocated_qubit_ids = set() self._uncompute_eng = None <|end_body_0|> <|body_start_1|> compute_eng = self.engine.next_engine if not isinstance(compute_eng, ComputeEngine): raise N...
Start a custom uncompute-section. Example: .. code-block:: python with Compute(eng): do_something(qubits) action(qubits) with CustomUncompute(eng): do_something_inverse(qubits) Raises: QubitManagementError: If qubits are allocated within Compute or within CustomUncompute context but are not deallocated.
CustomUncompute
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomUncompute: """Start a custom uncompute-section. Example: .. code-block:: python with Compute(eng): do_something(qubits) action(qubits) with CustomUncompute(eng): do_something_inverse(qubits) Raises: QubitManagementError: If qubits are allocated within Compute or within CustomUncompute conte...
stack_v2_sparse_classes_75kplus_train_067229
16,074
permissive
[ { "docstring": "Initialize a CustomUncompute context. Args: engine (BasicEngine): Engine which is the first to receive all commands (normally: MainEngine).", "name": "__init__", "signature": "def __init__(self, engine)" }, { "docstring": "Context manager enter function.", "name": "__enter__"...
3
stack_v2_sparse_classes_30k_train_023029
Implement the Python class `CustomUncompute` described below. Class description: Start a custom uncompute-section. Example: .. code-block:: python with Compute(eng): do_something(qubits) action(qubits) with CustomUncompute(eng): do_something_inverse(qubits) Raises: QubitManagementError: If qubits are allocated within ...
Implement the Python class `CustomUncompute` described below. Class description: Start a custom uncompute-section. Example: .. code-block:: python with Compute(eng): do_something(qubits) action(qubits) with CustomUncompute(eng): do_something_inverse(qubits) Raises: QubitManagementError: If qubits are allocated within ...
67c660ca18725d23ab0b261a45e34873b6a58d03
<|skeleton|> class CustomUncompute: """Start a custom uncompute-section. Example: .. code-block:: python with Compute(eng): do_something(qubits) action(qubits) with CustomUncompute(eng): do_something_inverse(qubits) Raises: QubitManagementError: If qubits are allocated within Compute or within CustomUncompute conte...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomUncompute: """Start a custom uncompute-section. Example: .. code-block:: python with Compute(eng): do_something(qubits) action(qubits) with CustomUncompute(eng): do_something_inverse(qubits) Raises: QubitManagementError: If qubits are allocated within Compute or within CustomUncompute context but are no...
the_stack_v2_python_sparse
projectq/meta/_compute.py
ProjectQ-Framework/ProjectQ
train
886
14e7633d024e895a24315e735a1d7792d235b9c6
[ "super(AdditiveUpsampleLayer, self).__init__(name=name)\nself.new_size = new_size\nself.n_splits = int(n_splits)", "check_divisible_channels(input_tensor, self.n_splits)\nresizing_layer = ResizingLayer(self.new_size)\nsplit = tf.split(resizing_layer(input_tensor), self.n_splits, axis=-1)\nsplit_tensor = tf.stack(...
<|body_start_0|> super(AdditiveUpsampleLayer, self).__init__(name=name) self.new_size = new_size self.n_splits = int(n_splits) <|end_body_0|> <|body_start_1|> check_divisible_channels(input_tensor, self.n_splits) resizing_layer = ResizingLayer(self.new_size) split = tf.s...
Implementation of bilinear (or trilinear) additive upsampling layer, described in paper: Wojna et al., The devil is in the decoder, https://arxiv.org/abs/1707.05847 In the paper 2D images are upsampled by a factor of 2 and ``n_splits = 4``
AdditiveUpsampleLayer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdditiveUpsampleLayer: """Implementation of bilinear (or trilinear) additive upsampling layer, described in paper: Wojna et al., The devil is in the decoder, https://arxiv.org/abs/1707.05847 In the paper 2D images are upsampled by a factor of 2 and ``n_splits = 4``""" def __init__(self, new_...
stack_v2_sparse_classes_75kplus_train_067230
4,253
permissive
[ { "docstring": ":param new_size: integer or a list of integers set the output 2D/3D spatial shape. If the parameter is an integer ``d``, it'll be expanded to ``(d, d)`` and ``(d, d, d)`` for 2D and 3D inputs respectively. :param n_splits: integer, the output tensor will have ``C / n_splits`` channels, where ``C...
2
stack_v2_sparse_classes_30k_train_020027
Implement the Python class `AdditiveUpsampleLayer` described below. Class description: Implementation of bilinear (or trilinear) additive upsampling layer, described in paper: Wojna et al., The devil is in the decoder, https://arxiv.org/abs/1707.05847 In the paper 2D images are upsampled by a factor of 2 and ``n_split...
Implement the Python class `AdditiveUpsampleLayer` described below. Class description: Implementation of bilinear (or trilinear) additive upsampling layer, described in paper: Wojna et al., The devil is in the decoder, https://arxiv.org/abs/1707.05847 In the paper 2D images are upsampled by a factor of 2 and ``n_split...
84dd0f85c9a1ab8a72f4c55fcf073379acf5ae1b
<|skeleton|> class AdditiveUpsampleLayer: """Implementation of bilinear (or trilinear) additive upsampling layer, described in paper: Wojna et al., The devil is in the decoder, https://arxiv.org/abs/1707.05847 In the paper 2D images are upsampled by a factor of 2 and ``n_splits = 4``""" def __init__(self, new_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AdditiveUpsampleLayer: """Implementation of bilinear (or trilinear) additive upsampling layer, described in paper: Wojna et al., The devil is in the decoder, https://arxiv.org/abs/1707.05847 In the paper 2D images are upsampled by a factor of 2 and ``n_splits = 4``""" def __init__(self, new_size, n_split...
the_stack_v2_python_sparse
niftynet/layer/additive_upsample.py
12SigmaTechnologies/NiftyNet-1
train
2
bd771c814da2ec9ba4337f24a133ee01a51fccb8
[ "params = Parameters.instance().place_params\ntransmission = params['place_transmission']\nplace_idx = place.place_type.value - 1\ntry:\n num_groups = params['mean_group_size'][place_idx]\nexcept IndexError:\n num_groups = 1\nplace_inf = 0 if hasattr(infector.microcell, 'closure_start_time') and infector.is_p...
<|body_start_0|> params = Parameters.instance().place_params transmission = params['place_transmission'] place_idx = place.place_type.value - 1 try: num_groups = params['mean_group_size'][place_idx] except IndexError: num_groups = 1 place_inf = 0 i...
Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, within places.
PlaceInfection
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PlaceInfection: """Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, within places.""" def place_inf(place, infector, time: float): """Calculate the infectiousness of a place. Does not include interventions such as isolation, or...
stack_v2_sparse_classes_75kplus_train_067231
6,023
permissive
[ { "docstring": "Calculate the infectiousness of a place. Does not include interventions such as isolation, or whether individual is a carehome resident. Does not yet differentiate between places as we have not decided which places to implement, and what transmission to give them. Parameters ---------- place : P...
3
stack_v2_sparse_classes_30k_train_039351
Implement the Python class `PlaceInfection` described below. Class description: Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, within places. Method signatures and docstrings: - def place_inf(place, infector, time: float): Calculate the infectiousness of a pl...
Implement the Python class `PlaceInfection` described below. Class description: Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, within places. Method signatures and docstrings: - def place_inf(place, infector, time: float): Calculate the infectiousness of a pl...
c11de122c6bfdf9103162e4045758808da5df322
<|skeleton|> class PlaceInfection: """Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, within places.""" def place_inf(place, infector, time: float): """Calculate the infectiousness of a place. Does not include interventions such as isolation, or...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PlaceInfection: """Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, within places.""" def place_inf(place, infector, time: float): """Calculate the infectiousness of a place. Does not include interventions such as isolation, or whether indi...
the_stack_v2_python_sparse
pyEpiabm/pyEpiabm/property/place_foi.py
SABS-R3-Epidemiology/epiabm
train
21
091a48314e9c600d648acbdf5d959d5bf0170cda
[ "expected = 62006\nmodel: cifar.Net = cifar.load_model()\nactual = sum((p.numel() for p in model.parameters() if p.requires_grad))\nassert actual == expected", "model: cifar.Net = cifar.load_model()\nexpected = 10\nweights: NDArrays = model.get_weights()\nassert len(weights) == expected", "weights_expected: NDA...
<|body_start_0|> expected = 62006 model: cifar.Net = cifar.load_model() actual = sum((p.numel() for p in model.parameters() if p.requires_grad)) assert actual == expected <|end_body_0|> <|body_start_1|> model: cifar.Net = cifar.load_model() expected = 10 weights:...
Tests for cifar module.
CifarTestCase
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CifarTestCase: """Tests for cifar module.""" def test_load_model(self) -> None: """Test the number of (trainable) model parameters.""" <|body_0|> def test_get_weights(self) -> None: """Test get_weights.""" <|body_1|> def test_set_weights(self) -> Non...
stack_v2_sparse_classes_75kplus_train_067232
2,193
permissive
[ { "docstring": "Test the number of (trainable) model parameters.", "name": "test_load_model", "signature": "def test_load_model(self) -> None" }, { "docstring": "Test get_weights.", "name": "test_get_weights", "signature": "def test_get_weights(self) -> None" }, { "docstring": "T...
3
stack_v2_sparse_classes_30k_train_010909
Implement the Python class `CifarTestCase` described below. Class description: Tests for cifar module. Method signatures and docstrings: - def test_load_model(self) -> None: Test the number of (trainable) model parameters. - def test_get_weights(self) -> None: Test get_weights. - def test_set_weights(self) -> None: T...
Implement the Python class `CifarTestCase` described below. Class description: Tests for cifar module. Method signatures and docstrings: - def test_load_model(self) -> None: Test the number of (trainable) model parameters. - def test_get_weights(self) -> None: Test get_weights. - def test_set_weights(self) -> None: T...
55be690535e5f3feb33c888c3e4a586b7bdbf489
<|skeleton|> class CifarTestCase: """Tests for cifar module.""" def test_load_model(self) -> None: """Test the number of (trainable) model parameters.""" <|body_0|> def test_get_weights(self) -> None: """Test get_weights.""" <|body_1|> def test_set_weights(self) -> Non...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CifarTestCase: """Tests for cifar module.""" def test_load_model(self) -> None: """Test the number of (trainable) model parameters.""" expected = 62006 model: cifar.Net = cifar.load_model() actual = sum((p.numel() for p in model.parameters() if p.requires_grad)) as...
the_stack_v2_python_sparse
src/py/flwr_example/pytorch_cifar/cifar_test.py
adap/flower
train
2,999
5e2d2f34748dcad069ca5e46fc81c59aeb27861f
[ "self.num_points = num_points\n'Setting all walks to start from(0,0)'\nself.x_values = [0]\nself.y_values = [0]", "while len(self.x_values) < self.num_points:\n\n def get_step(self):\n self.direction = choice([1, -1])\n self.distance = choice([0, 1, 2, 3])\n self.step = self.direction * se...
<|body_start_0|> self.num_points = num_points 'Setting all walks to start from(0,0)' self.x_values = [0] self.y_values = [0] <|end_body_0|> <|body_start_1|> while len(self.x_values) < self.num_points: def get_step(self): self.direction = choice([1, -...
A class to generate random walks.
RandomWalk
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomWalk: """A class to generate random walks.""" def __init__(self, num_points=5000): """Initialize attributes""" <|body_0|> def fill_walk(self): """Calculate all the points in the walk.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.nu...
stack_v2_sparse_classes_75kplus_train_067233
894
no_license
[ { "docstring": "Initialize attributes", "name": "__init__", "signature": "def __init__(self, num_points=5000)" }, { "docstring": "Calculate all the points in the walk.", "name": "fill_walk", "signature": "def fill_walk(self)" } ]
2
stack_v2_sparse_classes_30k_val_001255
Implement the Python class `RandomWalk` described below. Class description: A class to generate random walks. Method signatures and docstrings: - def __init__(self, num_points=5000): Initialize attributes - def fill_walk(self): Calculate all the points in the walk.
Implement the Python class `RandomWalk` described below. Class description: A class to generate random walks. Method signatures and docstrings: - def __init__(self, num_points=5000): Initialize attributes - def fill_walk(self): Calculate all the points in the walk. <|skeleton|> class RandomWalk: """A class to ge...
6be7694c49f8756faaf6eb009918726863cc01e5
<|skeleton|> class RandomWalk: """A class to generate random walks.""" def __init__(self, num_points=5000): """Initialize attributes""" <|body_0|> def fill_walk(self): """Calculate all the points in the walk.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RandomWalk: """A class to generate random walks.""" def __init__(self, num_points=5000): """Initialize attributes""" self.num_points = num_points 'Setting all walks to start from(0,0)' self.x_values = [0] self.y_values = [0] def fill_walk(self): """Cal...
the_stack_v2_python_sparse
data_visualization/mole_steps.py
osayi/python_intro
train
1
bffd5dd0e85b9ac62352514b792cb874190ce438
[ "try:\n import onnxruntime\n import skl2onnx\n return True\nexcept ImportError:\n return False", "if input_types is None or not isinstance(input_types[0], tuple):\n raise RuntimeError('input_types argument should contain at least one tuple, e.g. [((1, 14), np.float32)]')\nif isinstance(model, RFOnn...
<|body_start_0|> try: import onnxruntime import skl2onnx return True except ImportError: return False <|end_body_0|> <|body_start_1|> if input_types is None or not isinstance(input_types[0], tuple): raise RuntimeError('input_types argu...
RFOnnxCompiler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RFOnnxCompiler: def can_compile(): """Verify whether the required package has been installed.""" <|body_0|> def compile(model, path: str, input_types=None): """Compile the trained model for faster inference. Parameters ---------- model The native model that is expect...
stack_v2_sparse_classes_75kplus_train_067234
4,283
permissive
[ { "docstring": "Verify whether the required package has been installed.", "name": "can_compile", "signature": "def can_compile()" }, { "docstring": "Compile the trained model for faster inference. Parameters ---------- model The native model that is expected to be compiled. path : str The path f...
4
stack_v2_sparse_classes_30k_train_049993
Implement the Python class `RFOnnxCompiler` described below. Class description: Implement the RFOnnxCompiler class. Method signatures and docstrings: - def can_compile(): Verify whether the required package has been installed. - def compile(model, path: str, input_types=None): Compile the trained model for faster inf...
Implement the Python class `RFOnnxCompiler` described below. Class description: Implement the RFOnnxCompiler class. Method signatures and docstrings: - def can_compile(): Verify whether the required package has been installed. - def compile(model, path: str, input_types=None): Compile the trained model for faster inf...
6af92e149491f6e5062495d87306b3625d12d992
<|skeleton|> class RFOnnxCompiler: def can_compile(): """Verify whether the required package has been installed.""" <|body_0|> def compile(model, path: str, input_types=None): """Compile the trained model for faster inference. Parameters ---------- model The native model that is expect...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RFOnnxCompiler: def can_compile(): """Verify whether the required package has been installed.""" try: import onnxruntime import skl2onnx return True except ImportError: return False def compile(model, path: str, input_types=None): ...
the_stack_v2_python_sparse
tabular/src/autogluon/tabular/models/rf/compilers/onnx.py
stjordanis/autogluon
train
0
b0057acdc0e2755c710d7497fef4414b7a2a71dd
[ "self.svc_name = svc_name\nself.set_name = set_name\nself.min = int(min)\nself.max = int(max)\nself.isContinuous = True\nself.vals = None", "self.isContinuous = False\nself.vals = [int(val) for val in vals]\nself.min = min(self.vals)\nself.max = max(self.vals)" ]
<|body_start_0|> self.svc_name = svc_name self.set_name = set_name self.min = int(min) self.max = int(max) self.isContinuous = True self.vals = None <|end_body_0|> <|body_start_1|> self.isContinuous = False self.vals = [int(val) for val in vals] s...
a knob setting with max and min settings. It's the smallest unit for RAPID-C
Knob
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Knob: """a knob setting with max and min settings. It's the smallest unit for RAPID-C""" def __init__(self, svc_name, set_name, min, max): """Initialization :param svc_name: name of service :param set_name: name of setting :param min: lower bound :param max: upper bound""" <|...
stack_v2_sparse_classes_75kplus_train_067235
5,554
no_license
[ { "docstring": "Initialization :param svc_name: name of service :param set_name: name of setting :param min: lower bound :param max: upper bound", "name": "__init__", "signature": "def __init__(self, svc_name, set_name, min, max)" }, { "docstring": "Trasform to a knob with vals (discrete)", ...
2
stack_v2_sparse_classes_30k_train_002596
Implement the Python class `Knob` described below. Class description: a knob setting with max and min settings. It's the smallest unit for RAPID-C Method signatures and docstrings: - def __init__(self, svc_name, set_name, min, max): Initialization :param svc_name: name of service :param set_name: name of setting :par...
Implement the Python class `Knob` described below. Class description: a knob setting with max and min settings. It's the smallest unit for RAPID-C Method signatures and docstrings: - def __init__(self, svc_name, set_name, min, max): Initialization :param svc_name: name of service :param set_name: name of setting :par...
63b50cc32c6f647ea34b5512f48688149f949a3c
<|skeleton|> class Knob: """a knob setting with max and min settings. It's the smallest unit for RAPID-C""" def __init__(self, svc_name, set_name, min, max): """Initialization :param svc_name: name of service :param set_name: name of setting :param min: lower bound :param max: upper bound""" <|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Knob: """a knob setting with max and min settings. It's the smallest unit for RAPID-C""" def __init__(self, svc_name, set_name, min, max): """Initialization :param svc_name: name of service :param set_name: name of setting :param min: lower bound :param max: upper bound""" self.svc_name =...
the_stack_v2_python_sparse
modelConstr/Rapids/Rapids_Classes/KDG.py
niuye8911/rapidlib-linux
train
0
d6bc85077b6c72d706ec16aa9aba38d9f4efa475
[ "dir = [(-1, 0), (1, 0), (0, -1), (0, 1)]\nMAX_NUM_ELEMENTS = 10000\nnrows = len(matrix)\nncols = len(matrix[0])\ndist = [[0 for c in range(ncols)] for r in range(nrows)]\nqueue = []\nfor i in range(0, nrows):\n for j in range(0, ncols):\n if matrix[i][j] == 0:\n queue.append((i, j))\n e...
<|body_start_0|> dir = [(-1, 0), (1, 0), (0, -1), (0, 1)] MAX_NUM_ELEMENTS = 10000 nrows = len(matrix) ncols = len(matrix[0]) dist = [[0 for c in range(ncols)] for r in range(nrows)] queue = [] for i in range(0, nrows): for j in range(0, ncols): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def updateMatrix(self, matrix): """:type matrix: List[List[int]] :rtype: List[List[int]] matrix is stored row-wise""" <|body_0|> def updateMatrix2(self, matrix): """BFS :param matrix: :return:""" <|body_1|> def updateMatrix3(self, matrix): ...
stack_v2_sparse_classes_75kplus_train_067236
4,225
no_license
[ { "docstring": ":type matrix: List[List[int]] :rtype: List[List[int]] matrix is stored row-wise", "name": "updateMatrix", "signature": "def updateMatrix(self, matrix)" }, { "docstring": "BFS :param matrix: :return:", "name": "updateMatrix2", "signature": "def updateMatrix2(self, matrix)"...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def updateMatrix(self, matrix): :type matrix: List[List[int]] :rtype: List[List[int]] matrix is stored row-wise - def updateMatrix2(self, matrix): BFS :param matrix: :return: - d...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def updateMatrix(self, matrix): :type matrix: List[List[int]] :rtype: List[List[int]] matrix is stored row-wise - def updateMatrix2(self, matrix): BFS :param matrix: :return: - d...
a5b02044ef39154b6a8d32eb57682f447e1632ba
<|skeleton|> class Solution: def updateMatrix(self, matrix): """:type matrix: List[List[int]] :rtype: List[List[int]] matrix is stored row-wise""" <|body_0|> def updateMatrix2(self, matrix): """BFS :param matrix: :return:""" <|body_1|> def updateMatrix3(self, matrix): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def updateMatrix(self, matrix): """:type matrix: List[List[int]] :rtype: List[List[int]] matrix is stored row-wise""" dir = [(-1, 0), (1, 0), (0, -1), (0, 1)] MAX_NUM_ELEMENTS = 10000 nrows = len(matrix) ncols = len(matrix[0]) dist = [[0 for c in range...
the_stack_v2_python_sparse
algo/dp/01_matrix.py
xys234/coding-problems
train
0
4cdcd2254e219ca22f778cf162069424188aa01a
[ "super().__init__()\nself.in_dim = in_dim\nself.out_dim = out_dim\nself.hidden_dims = hidden_dims\nself.n_properties = n_properties\nself.min_var = min_var\nself.non_linearity = non_linearity\nself.restrict_var = restrict_var\nself.network = nn.ModuleList()\nfor i in range(self.n_properties):\n self.network.appe...
<|body_start_0|> super().__init__() self.in_dim = in_dim self.out_dim = out_dim self.hidden_dims = hidden_dims self.n_properties = n_properties self.min_var = min_var self.non_linearity = non_linearity self.restrict_var = restrict_var self.network ...
MultiProbabilisticVanillaNN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiProbabilisticVanillaNN: def __init__(self, in_dim, out_dim, hidden_dims, n_properties, non_linearity=F.tanh, min_var=0.01, restrict_var=False): """:param input_size: An integer describing the dimensionality of the input, in this case r_size, (the dimensionality of the embedding r) :...
stack_v2_sparse_classes_75kplus_train_067237
16,175
no_license
[ { "docstring": ":param input_size: An integer describing the dimensionality of the input, in this case r_size, (the dimensionality of the embedding r) :param output_size: An integer describing the dimensionality of the output, in this case output_size = x_size :param decoder_n_hidden: An integer describing the ...
2
stack_v2_sparse_classes_30k_train_020431
Implement the Python class `MultiProbabilisticVanillaNN` described below. Class description: Implement the MultiProbabilisticVanillaNN class. Method signatures and docstrings: - def __init__(self, in_dim, out_dim, hidden_dims, n_properties, non_linearity=F.tanh, min_var=0.01, restrict_var=False): :param input_size: A...
Implement the Python class `MultiProbabilisticVanillaNN` described below. Class description: Implement the MultiProbabilisticVanillaNN class. Method signatures and docstrings: - def __init__(self, in_dim, out_dim, hidden_dims, n_properties, non_linearity=F.tanh, min_var=0.01, restrict_var=False): :param input_size: A...
de60f831ee082ab2ae232c498cf2755da7c14c27
<|skeleton|> class MultiProbabilisticVanillaNN: def __init__(self, in_dim, out_dim, hidden_dims, n_properties, non_linearity=F.tanh, min_var=0.01, restrict_var=False): """:param input_size: An integer describing the dimensionality of the input, in this case r_size, (the dimensionality of the embedding r) :...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MultiProbabilisticVanillaNN: def __init__(self, in_dim, out_dim, hidden_dims, n_properties, non_linearity=F.tanh, min_var=0.01, restrict_var=False): """:param input_size: An integer describing the dimensionality of the input, in this case r_size, (the dimensionality of the embedding r) :param output_s...
the_stack_v2_python_sparse
models/networks/np_networks.py
PenelopeJones/neural_processes
train
4
c093250a430b218f136da1c3103d244cbcd8caa7
[ "CommonProcessWrapper.__init__(self, command, arguments, environs, workingDir, state, timeout, stdout, stderr, displayName, **kwargs)\nself.stdout = '/dev/null'\nself.stderr = '/dev/null'\ntry:\n if stdout is not None:\n self.stdout = stdout\nexcept Exception:\n log.info('Unable to create file to captu...
<|body_start_0|> CommonProcessWrapper.__init__(self, command, arguments, environs, workingDir, state, timeout, stdout, stderr, displayName, **kwargs) self.stdout = '/dev/null' self.stderr = '/dev/null' try: if stdout is not None: self.stdout = stdout e...
Unix process wrapper for process execution and management. The unix process wrapper provides the ability to start and stop an external process, setting the process environment, working directory and state i.e. a foreground process in which case a call to the L{start()} method will not return until the process has exite...
ProcessWrapper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProcessWrapper: """Unix process wrapper for process execution and management. The unix process wrapper provides the ability to start and stop an external process, setting the process environment, working directory and state i.e. a foreground process in which case a call to the L{start()} method w...
stack_v2_sparse_classes_75kplus_train_067238
7,828
no_license
[ { "docstring": "Create an instance of the process wrapper. @param command: The full path to the command to execute @param arguments: A list of arguments to the command @param environs: A dictionary of environment variables (key, value) for the process context execution @param workingDir: The working directory f...
6
stack_v2_sparse_classes_30k_val_002046
Implement the Python class `ProcessWrapper` described below. Class description: Unix process wrapper for process execution and management. The unix process wrapper provides the ability to start and stop an external process, setting the process environment, working directory and state i.e. a foreground process in which...
Implement the Python class `ProcessWrapper` described below. Class description: Unix process wrapper for process execution and management. The unix process wrapper provides the ability to start and stop an external process, setting the process environment, working directory and state i.e. a foreground process in which...
3f93cbedbb806b6c53de89358025f93c740ebdc3
<|skeleton|> class ProcessWrapper: """Unix process wrapper for process execution and management. The unix process wrapper provides the ability to start and stop an external process, setting the process environment, working directory and state i.e. a foreground process in which case a call to the L{start()} method w...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProcessWrapper: """Unix process wrapper for process execution and management. The unix process wrapper provides the ability to start and stop an external process, setting the process environment, working directory and state i.e. a foreground process in which case a call to the L{start()} method will not retur...
the_stack_v2_python_sparse
pysys/process/plat-unix/helper.py
moraygrieve/pysys
train
0
3e121aa4796508a06b6501569e5f670b06a82d86
[ "super().__init__()\nn_blocks = len(channels) - 1\nif type(kernel_size) is not list:\n kernel_size = [kernel_size] * n_blocks\nif stride is None:\n stride = kernel_size\nelif type(stride) is not list:\n stride = [stride] * n_blocks\nif type(nonlinear) is not list:\n nonlinear = [nonlinear] * n_blocks\ns...
<|body_start_0|> super().__init__() n_blocks = len(channels) - 1 if type(kernel_size) is not list: kernel_size = [kernel_size] * n_blocks if stride is None: stride = kernel_size elif type(stride) is not list: stride = [stride] * n_blocks ...
Decoder1d
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Decoder1d: def __init__(self, channels, kernel_size, stride=None, dilated=False, separable=False, nonlinear='relu'): """Args: channels <list<int>> kernel_size <int> or <list<int>> stride <int> or <list<int>> dilated <bool> nonlinear <str> or <list<str>>""" <|body_0|> def for...
stack_v2_sparse_classes_75kplus_train_067239
19,840
no_license
[ { "docstring": "Args: channels <list<int>> kernel_size <int> or <list<int>> stride <int> or <list<int>> dilated <bool> nonlinear <str> or <list<str>>", "name": "__init__", "signature": "def __init__(self, channels, kernel_size, stride=None, dilated=False, separable=False, nonlinear='relu')" }, { ...
2
null
Implement the Python class `Decoder1d` described below. Class description: Implement the Decoder1d class. Method signatures and docstrings: - def __init__(self, channels, kernel_size, stride=None, dilated=False, separable=False, nonlinear='relu'): Args: channels <list<int>> kernel_size <int> or <list<int>> stride <in...
Implement the Python class `Decoder1d` described below. Class description: Implement the Decoder1d class. Method signatures and docstrings: - def __init__(self, channels, kernel_size, stride=None, dilated=False, separable=False, nonlinear='relu'): Args: channels <list<int>> kernel_size <int> or <list<int>> stride <in...
4f7f77406cf580785ebf932d78069e7d6e35b765
<|skeleton|> class Decoder1d: def __init__(self, channels, kernel_size, stride=None, dilated=False, separable=False, nonlinear='relu'): """Args: channels <list<int>> kernel_size <int> or <list<int>> stride <int> or <list<int>> dilated <bool> nonlinear <str> or <list<str>>""" <|body_0|> def for...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Decoder1d: def __init__(self, channels, kernel_size, stride=None, dilated=False, separable=False, nonlinear='relu'): """Args: channels <list<int>> kernel_size <int> or <list<int>> stride <int> or <list<int>> dilated <bool> nonlinear <str> or <list<str>>""" super().__init__() n_blocks =...
the_stack_v2_python_sparse
src/models/unet.py
shelly-tang/DNN-based_source_separation
train
0
621d3628827128962a0eb69f570c3053bf48520a
[ "count = [0] * (len(citations) + 1)\nfor i in range(len(citations)):\n if citations[i] >= len(citations):\n count[len(citations)] += 1\n else:\n count[citations[i]] += 1\nfor j in range(len(citations), -1, -1):\n if count[j] >= j:\n return j\n count[j - 1] += count[j]", "level = 0...
<|body_start_0|> count = [0] * (len(citations) + 1) for i in range(len(citations)): if citations[i] >= len(citations): count[len(citations)] += 1 else: count[citations[i]] += 1 for j in range(len(citations), -1, -1): if count[j]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def hIndex(self, citations): """:type citations: List[int] :rtype: int""" <|body_0|> def hIndex_sort(self, citations): """:type citations: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> count = [0] * (len(citations) ...
stack_v2_sparse_classes_75kplus_train_067240
1,937
no_license
[ { "docstring": ":type citations: List[int] :rtype: int", "name": "hIndex", "signature": "def hIndex(self, citations)" }, { "docstring": ":type citations: List[int] :rtype: int", "name": "hIndex_sort", "signature": "def hIndex_sort(self, citations)" } ]
2
stack_v2_sparse_classes_30k_val_000639
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hIndex(self, citations): :type citations: List[int] :rtype: int - def hIndex_sort(self, citations): :type citations: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hIndex(self, citations): :type citations: List[int] :rtype: int - def hIndex_sort(self, citations): :type citations: List[int] :rtype: int <|skeleton|> class Solution: ...
8595b04cf5a024c2cd8a97f750d890a818568401
<|skeleton|> class Solution: def hIndex(self, citations): """:type citations: List[int] :rtype: int""" <|body_0|> def hIndex_sort(self, citations): """:type citations: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def hIndex(self, citations): """:type citations: List[int] :rtype: int""" count = [0] * (len(citations) + 1) for i in range(len(citations)): if citations[i] >= len(citations): count[len(citations)] += 1 else: count[citat...
the_stack_v2_python_sparse
python/274.h-index.py
tainenko/Leetcode2019
train
5
475b3f7924f7eb75612dd97a0062976ab35630fd
[ "self.buf = buf\nself.ptr = ptr\nself.endian = endian\nself._cache = {}", "pkst = self._cache.get(fmt)\nif pkst is None:\n if self.endian is None or fmt[0] in _ENDIAN_CODES:\n pkst = Struct(fmt)\n else:\n endian_fmt = self.endian + fmt\n pkst = Struct(endian_fmt)\n self._cache[en...
<|body_start_0|> self.buf = buf self.ptr = ptr self.endian = endian self._cache = {} <|end_body_0|> <|body_start_1|> pkst = self._cache.get(fmt) if pkst is None: if self.endian is None or fmt[0] in _ENDIAN_CODES: pkst = Struct(fmt) ...
Class to unpack values from buffer object The buffer object is usually a string. Caches compiled :mod:`struct` format strings so that repeated unpacking with the same format string should be faster than using ``struct.unpack`` directly. Examples -------- >>> a = b'1234567890' >>> upk = Unpacker(a) >>> upk.unpack('2s') ...
Unpacker
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Unpacker: """Class to unpack values from buffer object The buffer object is usually a string. Caches compiled :mod:`struct` format strings so that repeated unpacking with the same format string should be faster than using ``struct.unpack`` directly. Examples -------- >>> a = b'1234567890' >>> upk...
stack_v2_sparse_classes_75kplus_train_067241
3,580
permissive
[ { "docstring": "Initialize unpacker Parameters ---------- buf : buffer object implementing buffer protocol (e.g. str) ptr : int, optional offset at which to begin reads from `buf` endian : None or str, optional endian code to prepend to format, as for ``unpack`` endian codes. None (the default) corresponds to t...
3
stack_v2_sparse_classes_30k_test_000046
Implement the Python class `Unpacker` described below. Class description: Class to unpack values from buffer object The buffer object is usually a string. Caches compiled :mod:`struct` format strings so that repeated unpacking with the same format string should be faster than using ``struct.unpack`` directly. Examples...
Implement the Python class `Unpacker` described below. Class description: Class to unpack values from buffer object The buffer object is usually a string. Caches compiled :mod:`struct` format strings so that repeated unpacking with the same format string should be faster than using ``struct.unpack`` directly. Examples...
3c3acc55de8ba741e673063378e6cbaf10b64c7a
<|skeleton|> class Unpacker: """Class to unpack values from buffer object The buffer object is usually a string. Caches compiled :mod:`struct` format strings so that repeated unpacking with the same format string should be faster than using ``struct.unpack`` directly. Examples -------- >>> a = b'1234567890' >>> upk...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Unpacker: """Class to unpack values from buffer object The buffer object is usually a string. Caches compiled :mod:`struct` format strings so that repeated unpacking with the same format string should be faster than using ``struct.unpack`` directly. Examples -------- >>> a = b'1234567890' >>> upk = Unpacker(a...
the_stack_v2_python_sparse
env/lib/python3.6/site-packages/nibabel/nicom/structreader.py
Raniac/NEURO-LEARN
train
9
73f8f091feb132f58118ef33bc4821b5a81fa3d7
[ "super(LabelSmoothingLoss, self).__init__()\nself.use_label_smoothing = False\nif smoothing > 0.0:\n logging.info('Use label smoothing')\n self.smoothing = smoothing\n self.confidence = 1.0 - smoothing\n self.use_label_smoothing = True\n self.n_target_vocab = n_target_vocab\nself.normalize_length = n...
<|body_start_0|> super(LabelSmoothingLoss, self).__init__() self.use_label_smoothing = False if smoothing > 0.0: logging.info('Use label smoothing') self.smoothing = smoothing self.confidence = 1.0 - smoothing self.use_label_smoothing = True ...
Label Smoothing Loss. Args: smoothing (float): smoothing rate (0.0 means the conventional CE). n_target_vocab (int): number of classes. normalize_length (bool): normalize loss by sequence length if True.
LabelSmoothingLoss
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LabelSmoothingLoss: """Label Smoothing Loss. Args: smoothing (float): smoothing rate (0.0 means the conventional CE). n_target_vocab (int): number of classes. normalize_length (bool): normalize loss by sequence length if True.""" def __init__(self, smoothing, n_target_vocab, normalize_length...
stack_v2_sparse_classes_75kplus_train_067242
2,455
permissive
[ { "docstring": "Initialize Loss.", "name": "__init__", "signature": "def __init__(self, smoothing, n_target_vocab, normalize_length=False, ignore_id=-1)" }, { "docstring": "Forward Loss. Args: ys_block (chainer.Variable): Predicted labels. ys_pad (chainer.Variable): Target (true) labels. Returns...
2
null
Implement the Python class `LabelSmoothingLoss` described below. Class description: Label Smoothing Loss. Args: smoothing (float): smoothing rate (0.0 means the conventional CE). n_target_vocab (int): number of classes. normalize_length (bool): normalize loss by sequence length if True. Method signatures and docstrin...
Implement the Python class `LabelSmoothingLoss` described below. Class description: Label Smoothing Loss. Args: smoothing (float): smoothing rate (0.0 means the conventional CE). n_target_vocab (int): number of classes. normalize_length (bool): normalize loss by sequence length if True. Method signatures and docstrin...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class LabelSmoothingLoss: """Label Smoothing Loss. Args: smoothing (float): smoothing rate (0.0 means the conventional CE). n_target_vocab (int): number of classes. normalize_length (bool): normalize loss by sequence length if True.""" def __init__(self, smoothing, n_target_vocab, normalize_length...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LabelSmoothingLoss: """Label Smoothing Loss. Args: smoothing (float): smoothing rate (0.0 means the conventional CE). n_target_vocab (int): number of classes. normalize_length (bool): normalize loss by sequence length if True.""" def __init__(self, smoothing, n_target_vocab, normalize_length=False, ignor...
the_stack_v2_python_sparse
espnet/nets/chainer_backend/transformer/label_smoothing_loss.py
espnet/espnet
train
7,242
dcaf7f5b15aa6b7a8631fab79d2ff601b3d56c9a
[ "auth_token = helpers.get_auth_token_for_testing()\nbatch = {'user_id': 'erik', 'auth_token': auth_token, 'annotations': [dict(account='r123', key='owner', value='erik'), dict(account='r124', key='owner', value='erik')]}\nresponse = self.client.post('/add', data=json.dumps(batch), content_type='application/json')\n...
<|body_start_0|> auth_token = helpers.get_auth_token_for_testing() batch = {'user_id': 'erik', 'auth_token': auth_token, 'annotations': [dict(account='r123', key='owner', value='erik'), dict(account='r124', key='owner', value='erik')]} response = self.client.post('/add', data=json.dumps(batch), ...
Unit tests for the "/add" API endpoint.
AddTestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddTestCase: """Unit tests for the "/add" API endpoint.""" def test_add_in_body(self): """Test the "/add" endpoint with a batch in the body of the request.""" <|body_0|> def test_add_query_params(self): """Test the "/add" endpoint with a batch in a query paramete...
stack_v2_sparse_classes_75kplus_train_067243
25,230
no_license
[ { "docstring": "Test the \"/add\" endpoint with a batch in the body of the request.", "name": "test_add_in_body", "signature": "def test_add_in_body(self)" }, { "docstring": "Test the \"/add\" endpoint with a batch in a query parameter.", "name": "test_add_query_params", "signature": "de...
3
stack_v2_sparse_classes_30k_train_021989
Implement the Python class `AddTestCase` described below. Class description: Unit tests for the "/add" API endpoint. Method signatures and docstrings: - def test_add_in_body(self): Test the "/add" endpoint with a batch in the body of the request. - def test_add_query_params(self): Test the "/add" endpoint with a batc...
Implement the Python class `AddTestCase` described below. Class description: Unit tests for the "/add" API endpoint. Method signatures and docstrings: - def test_add_in_body(self): Test the "/add" endpoint with a batch in the body of the request. - def test_add_query_params(self): Test the "/add" endpoint with a batc...
a7d49d463ea97900333885dd29cb2e70c1a0fdb9
<|skeleton|> class AddTestCase: """Unit tests for the "/add" API endpoint.""" def test_add_in_body(self): """Test the "/add" endpoint with a batch in the body of the request.""" <|body_0|> def test_add_query_params(self): """Test the "/add" endpoint with a batch in a query paramete...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AddTestCase: """Unit tests for the "/add" API endpoint.""" def test_add_in_body(self): """Test the "/add" endpoint with a batch in the body of the request.""" auth_token = helpers.get_auth_token_for_testing() batch = {'user_id': 'erik', 'auth_token': auth_token, 'annotations': [di...
the_stack_v2_python_sparse
annotationDatabase/api/tests.py
erikwestra/ripple-annotation-database
train
0
817ddd7e812334c72daa8dc5d08d01555bfd629e
[ "request_data = request.GET\nusername = request.META.get('HTTP_USERNAME')\nif not username:\n username = request.user.username\nsearch_value = request_data.get('search_value', '')\nper_page = int(request_data.get('per_page', 10)) if request_data.get('per_page', 10) else 10\npage = int(request_data.get('page', 1)...
<|body_start_0|> request_data = request.GET username = request.META.get('HTTP_USERNAME') if not username: username = request.user.username search_value = request_data.get('search_value', '') per_page = int(request_data.get('per_page', 10)) if request_data.get('per_pag...
WorkflowRunScriptView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WorkflowRunScriptView: def get(self, request, *args, **kwargs): """获取工作流执行脚本列表 :param request: :param args: :param kwargs: :return:""" <|body_0|> def post(self, request, *args, **kwargs): """新增脚本 :param request: :param args: :param kwargs: :return:""" <|body_...
stack_v2_sparse_classes_75kplus_train_067244
35,200
permissive
[ { "docstring": "获取工作流执行脚本列表 :param request: :param args: :param kwargs: :return:", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "新增脚本 :param request: :param args: :param kwargs: :return:", "name": "post", "signature": "def post(self, request, *a...
2
stack_v2_sparse_classes_30k_train_049508
Implement the Python class `WorkflowRunScriptView` described below. Class description: Implement the WorkflowRunScriptView class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): 获取工作流执行脚本列表 :param request: :param args: :param kwargs: :return: - def post(self, request, *args, **kwargs): 新增...
Implement the Python class `WorkflowRunScriptView` described below. Class description: Implement the WorkflowRunScriptView class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): 获取工作流执行脚本列表 :param request: :param args: :param kwargs: :return: - def post(self, request, *args, **kwargs): 新增...
14d29d6669a6538fe176792d001710616719d050
<|skeleton|> class WorkflowRunScriptView: def get(self, request, *args, **kwargs): """获取工作流执行脚本列表 :param request: :param args: :param kwargs: :return:""" <|body_0|> def post(self, request, *args, **kwargs): """新增脚本 :param request: :param args: :param kwargs: :return:""" <|body_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WorkflowRunScriptView: def get(self, request, *args, **kwargs): """获取工作流执行脚本列表 :param request: :param args: :param kwargs: :return:""" request_data = request.GET username = request.META.get('HTTP_USERNAME') if not username: username = request.user.username s...
the_stack_v2_python_sparse
apps/workflow/views.py
Rgcsh/loonflow_custom
train
2
1b8f3861019759034db870907acf8af222ca9750
[ "super().__init__()\nself.n_heads = n_heads\nself.head_dim = head_dim\nself.hid_dim = head_dim * n_heads\nscale = torch.tensor([self.hid_dim], dtype=torch.float32).rsqrt()\nself.register_buffer('scale', scale)\nif kv_emb_dim is None:\n kv_emb_dim = q_emb_dim\nself.fc_q = nn.Linear(q_emb_dim, self.hid_dim)\nself....
<|body_start_0|> super().__init__() self.n_heads = n_heads self.head_dim = head_dim self.hid_dim = head_dim * n_heads scale = torch.tensor([self.hid_dim], dtype=torch.float32).rsqrt() self.register_buffer('scale', scale) if kv_emb_dim is None: kv_emb_d...
MultiHeadAttention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiHeadAttention: def __init__(self, q_emb_dim, head_dim, n_heads, kv_emb_dim=None, dropout=0.0): """:param emb_dim: input embeddings dim :param head_dim: Single head hidden-dim :param n_heads: number of MHSA heads :param dropout: 0 by default (no dropout applied)""" <|body_0|>...
stack_v2_sparse_classes_75kplus_train_067245
3,592
no_license
[ { "docstring": ":param emb_dim: input embeddings dim :param head_dim: Single head hidden-dim :param n_heads: number of MHSA heads :param dropout: 0 by default (no dropout applied)", "name": "__init__", "signature": "def __init__(self, q_emb_dim, head_dim, n_heads, kv_emb_dim=None, dropout=0.0)" }, {...
3
null
Implement the Python class `MultiHeadAttention` described below. Class description: Implement the MultiHeadAttention class. Method signatures and docstrings: - def __init__(self, q_emb_dim, head_dim, n_heads, kv_emb_dim=None, dropout=0.0): :param emb_dim: input embeddings dim :param head_dim: Single head hidden-dim :...
Implement the Python class `MultiHeadAttention` described below. Class description: Implement the MultiHeadAttention class. Method signatures and docstrings: - def __init__(self, q_emb_dim, head_dim, n_heads, kv_emb_dim=None, dropout=0.0): :param emb_dim: input embeddings dim :param head_dim: Single head hidden-dim :...
6a27856f3f5d71373e6d42657233f7af0447a795
<|skeleton|> class MultiHeadAttention: def __init__(self, q_emb_dim, head_dim, n_heads, kv_emb_dim=None, dropout=0.0): """:param emb_dim: input embeddings dim :param head_dim: Single head hidden-dim :param n_heads: number of MHSA heads :param dropout: 0 by default (no dropout applied)""" <|body_0|>...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MultiHeadAttention: def __init__(self, q_emb_dim, head_dim, n_heads, kv_emb_dim=None, dropout=0.0): """:param emb_dim: input embeddings dim :param head_dim: Single head hidden-dim :param n_heads: number of MHSA heads :param dropout: 0 by default (no dropout applied)""" super().__init__() ...
the_stack_v2_python_sparse
models/attention/attention.py
cscribano/AYCE_2021
train
8
fa9e3f76e640b785da2708ce663b481298f995c1
[ "self.response.headers['Content-Type'] = 'text/html'\nsubject = self.request.get('subject')\ncontent = self.request.get('content')\nvalues = {'subject': subject, 'content': content}\npath = os.path.join(os.path.dirname(__file__), '../templates/create_blog_entry.html')\nself.response.out.write(template.render(path, ...
<|body_start_0|> self.response.headers['Content-Type'] = 'text/html' subject = self.request.get('subject') content = self.request.get('content') values = {'subject': subject, 'content': content} path = os.path.join(os.path.dirname(__file__), '../templates/create_blog_entry.html')...
CreateBlogEntry
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateBlogEntry: def get(self): """Handles request for the create page""" <|body_0|> def post(self): """Handles blog entry creation""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.response.headers['Content-Type'] = 'text/html' subject =...
stack_v2_sparse_classes_75kplus_train_067246
7,437
permissive
[ { "docstring": "Handles request for the create page", "name": "get", "signature": "def get(self)" }, { "docstring": "Handles blog entry creation", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_047131
Implement the Python class `CreateBlogEntry` described below. Class description: Implement the CreateBlogEntry class. Method signatures and docstrings: - def get(self): Handles request for the create page - def post(self): Handles blog entry creation
Implement the Python class `CreateBlogEntry` described below. Class description: Implement the CreateBlogEntry class. Method signatures and docstrings: - def get(self): Handles request for the create page - def post(self): Handles blog entry creation <|skeleton|> class CreateBlogEntry: def get(self): ""...
87cf5dd5d0e06ee745d3aba058d96fa46f2aeb6b
<|skeleton|> class CreateBlogEntry: def get(self): """Handles request for the create page""" <|body_0|> def post(self): """Handles blog entry creation""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CreateBlogEntry: def get(self): """Handles request for the create page""" self.response.headers['Content-Type'] = 'text/html' subject = self.request.get('subject') content = self.request.get('content') values = {'subject': subject, 'content': content} path = os....
the_stack_v2_python_sparse
src/unit6/blog/blog_main.py
cdoremus/udacity-python_web_development-cs253
train
0
c4478c74c8829ce931fcac75b79b93dbf132a965
[ "annotations = task.annotations\nif 'request' in self.context and hasattr(self.context['request'], 'user'):\n user = self.context['request'].user\n if user.is_annotator:\n annotations = annotations.filter(completed_by=user)\nreturn AnnotationSerializer(annotations, many=True, read_only=True, default=Tr...
<|body_start_0|> annotations = task.annotations if 'request' in self.context and hasattr(self.context['request'], 'user'): user = self.context['request'].user if user.is_annotator: annotations = annotations.filter(completed_by=user) return AnnotationSerial...
TaskWithAnnotationsAndPredictionsAndDraftsSerializer
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskWithAnnotationsAndPredictionsAndDraftsSerializer: def get_annotations(self, task): """Return annotations only for the current user""" <|body_0|> def get_drafts(self, task): """Return drafts only for the current user""" <|body_1|> <|end_skeleton|> <|body...
stack_v2_sparse_classes_75kplus_train_067247
18,964
permissive
[ { "docstring": "Return annotations only for the current user", "name": "get_annotations", "signature": "def get_annotations(self, task)" }, { "docstring": "Return drafts only for the current user", "name": "get_drafts", "signature": "def get_drafts(self, task)" } ]
2
stack_v2_sparse_classes_30k_train_010487
Implement the Python class `TaskWithAnnotationsAndPredictionsAndDraftsSerializer` described below. Class description: Implement the TaskWithAnnotationsAndPredictionsAndDraftsSerializer class. Method signatures and docstrings: - def get_annotations(self, task): Return annotations only for the current user - def get_dr...
Implement the Python class `TaskWithAnnotationsAndPredictionsAndDraftsSerializer` described below. Class description: Implement the TaskWithAnnotationsAndPredictionsAndDraftsSerializer class. Method signatures and docstrings: - def get_annotations(self, task): Return annotations only for the current user - def get_dr...
7c9e5777b7c0fe510b8585ae4c42b74a46929f73
<|skeleton|> class TaskWithAnnotationsAndPredictionsAndDraftsSerializer: def get_annotations(self, task): """Return annotations only for the current user""" <|body_0|> def get_drafts(self, task): """Return drafts only for the current user""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TaskWithAnnotationsAndPredictionsAndDraftsSerializer: def get_annotations(self, task): """Return annotations only for the current user""" annotations = task.annotations if 'request' in self.context and hasattr(self.context['request'], 'user'): user = self.context['request']...
the_stack_v2_python_sparse
label_studio/tasks/serializers.py
mihirpurwar/label-studio
train
1
936dee37f4be4a748b26ed035e1d6f84f6ccb958
[ "self.word = word\nw2i, i2w = early_model.index\nsim_early = np.dot(early_model.C, early_model.W[w2i[word]])\nsim_later = np.dot(later_model.C, later_model.W[w2i[word]])\nz_early = scipy.special.logsumexp(sim_early)\nz_later = scipy.special.logsumexp(sim_later)\nself.simdiff = sim_later - sim_early\nself.zdiff = z_...
<|body_start_0|> self.word = word w2i, i2w = early_model.index sim_early = np.dot(early_model.C, early_model.W[w2i[word]]) sim_later = np.dot(later_model.C, later_model.W[w2i[word]]) z_early = scipy.special.logsumexp(sim_early) z_later = scipy.special.logsumexp(sim_later)...
Scorer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Scorer: def __init__(self, early_model, later_model, word): """constructor for scoring with respect to the given models and the word Args: early_model (:obj: model): embeddings from early documents. later_model (:obj: model): embeddings from later documents. word (:obj: str): the word"""...
stack_v2_sparse_classes_75kplus_train_067248
2,376
permissive
[ { "docstring": "constructor for scoring with respect to the given models and the word Args: early_model (:obj: model): embeddings from early documents. later_model (:obj: model): embeddings from later documents. word (:obj: str): the word", "name": "__init__", "signature": "def __init__(self, early_mode...
2
null
Implement the Python class `Scorer` described below. Class description: Implement the Scorer class. Method signatures and docstrings: - def __init__(self, early_model, later_model, word): constructor for scoring with respect to the given models and the word Args: early_model (:obj: model): embeddings from early docum...
Implement the Python class `Scorer` described below. Class description: Implement the Scorer class. Method signatures and docstrings: - def __init__(self, early_model, later_model, word): constructor for scoring with respect to the given models and the word Args: early_model (:obj: model): embeddings from early docum...
824079b388d0eebc92b2197805b27ed320353f8f
<|skeleton|> class Scorer: def __init__(self, early_model, later_model, word): """constructor for scoring with respect to the given models and the word Args: early_model (:obj: model): embeddings from early documents. later_model (:obj: model): embeddings from later documents. word (:obj: str): the word"""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Scorer: def __init__(self, early_model, later_model, word): """constructor for scoring with respect to the given models and the word Args: early_model (:obj: model): embeddings from early documents. later_model (:obj: model): embeddings from later documents. word (:obj: str): the word""" self....
the_stack_v2_python_sparse
modules/semshift/docscores.py
petershan1119/semantic-progressiveness
train
0
5105f143b28c00ad4d50a1182ccd43c91f0d3efe
[ "orm_question = self.get_nested_orm_question(data['id'])\nif orm_question is None:\n raise serializers.ValidationError('This question does not belong to this quiz.')\norm_options_by_id = {option.id: option for option in orm_question.options.all()}\nnew_options_by_id = {option['id']: option for option in data['op...
<|body_start_0|> orm_question = self.get_nested_orm_question(data['id']) if orm_question is None: raise serializers.ValidationError('This question does not belong to this quiz.') orm_options_by_id = {option.id: option for option in orm_question.options.all()} new_options_by_i...
This serializer is supposed to be nested into EditableQuizSerializer in a ListSerializer field (i.e. with "many=True").
EditableQuestionSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EditableQuestionSerializer: """This serializer is supposed to be nested into EditableQuizSerializer in a ListSerializer field (i.e. with "many=True").""" def validate(self, data): """Object-level validation method. `data` is a dictionary of submitted field values. Because of validati...
stack_v2_sparse_classes_75kplus_train_067249
10,431
no_license
[ { "docstring": "Object-level validation method. `data` is a dictionary of submitted field values. Because of validation order, can assume that required fields are present.", "name": "validate", "signature": "def validate(self, data)" }, { "docstring": "Get Question ORM object assuming that the s...
4
null
Implement the Python class `EditableQuestionSerializer` described below. Class description: This serializer is supposed to be nested into EditableQuizSerializer in a ListSerializer field (i.e. with "many=True"). Method signatures and docstrings: - def validate(self, data): Object-level validation method. `data` is a ...
Implement the Python class `EditableQuestionSerializer` described below. Class description: This serializer is supposed to be nested into EditableQuizSerializer in a ListSerializer field (i.e. with "many=True"). Method signatures and docstrings: - def validate(self, data): Object-level validation method. `data` is a ...
e2fc1625f9082ebb722b4b7a459537f5d363944a
<|skeleton|> class EditableQuestionSerializer: """This serializer is supposed to be nested into EditableQuizSerializer in a ListSerializer field (i.e. with "many=True").""" def validate(self, data): """Object-level validation method. `data` is a dictionary of submitted field values. Because of validati...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EditableQuestionSerializer: """This serializer is supposed to be nested into EditableQuizSerializer in a ListSerializer field (i.e. with "many=True").""" def validate(self, data): """Object-level validation method. `data` is a dictionary of submitted field values. Because of validation order, can...
the_stack_v2_python_sparse
drf/quizzz/quizzes/serializers.py
pyvlad/quizzz-spa
train
0
1285ce461d8f440a98ade3c28397c317c5a16b3d
[ "try:\n data = {'first_name': user_data['localizedFirstName'], 'last_name': user_data['localizedLastName'], 'email': user_data['elements'][0]['handle~']['emailAddress'], 'photo_url': None}\n return data\nexcept KeyError:\n raise PermissionException", "data = {'grant_type': 'authorization_code', 'code': a...
<|body_start_0|> try: data = {'first_name': user_data['localizedFirstName'], 'last_name': user_data['localizedLastName'], 'email': user_data['elements'][0]['handle~']['emailAddress'], 'photo_url': None} return data except KeyError: raise PermissionException <|end_body...
Linkedin backend.
LinkedinBackend
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinkedinBackend: """Linkedin backend.""" def _normalize_user_data(user_data: dict) -> dict: """Normalize user data. :param user_data: User data from Linkedin :return: normalized user data.""" <|body_0|> def _auth(self, auth_code: str) -> None: """Get user access ...
stack_v2_sparse_classes_75kplus_train_067250
3,876
no_license
[ { "docstring": "Normalize user data. :param user_data: User data from Linkedin :return: normalized user data.", "name": "_normalize_user_data", "signature": "def _normalize_user_data(user_data: dict) -> dict" }, { "docstring": "Get user access token by authorization code. :param auth_code: Autho...
5
stack_v2_sparse_classes_30k_train_026398
Implement the Python class `LinkedinBackend` described below. Class description: Linkedin backend. Method signatures and docstrings: - def _normalize_user_data(user_data: dict) -> dict: Normalize user data. :param user_data: User data from Linkedin :return: normalized user data. - def _auth(self, auth_code: str) -> N...
Implement the Python class `LinkedinBackend` described below. Class description: Linkedin backend. Method signatures and docstrings: - def _normalize_user_data(user_data: dict) -> dict: Normalize user data. :param user_data: User data from Linkedin :return: normalized user data. - def _auth(self, auth_code: str) -> N...
713b9d84ac70d964d46f189ab1f9c7b944b9684b
<|skeleton|> class LinkedinBackend: """Linkedin backend.""" def _normalize_user_data(user_data: dict) -> dict: """Normalize user data. :param user_data: User data from Linkedin :return: normalized user data.""" <|body_0|> def _auth(self, auth_code: str) -> None: """Get user access ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LinkedinBackend: """Linkedin backend.""" def _normalize_user_data(user_data: dict) -> dict: """Normalize user data. :param user_data: User data from Linkedin :return: normalized user data.""" try: data = {'first_name': user_data['localizedFirstName'], 'last_name': user_data['l...
the_stack_v2_python_sparse
jobadvisor/authentication/backends/linkedin.py
ewgen19892/jobadvisor
train
0
87e4bcf8dc95312fe7c8dee6a9f6ba459c6a1ca8
[ "super().__init__(hyper_parameters)\nself.atrous_rates = hyper_parameters['graph'].get('atrous_rates', [2, 1, 2])\nself.crf_lr_multiplier = hyper_parameters.get('train', {}).get('crf_lr_multiplier', 1 if self.embed_type in ['WARD', 'RANDOM'] else 3200)", "conv_pools = []\nfor i in range(len(self.filters_size)):\n...
<|body_start_0|> super().__init__(hyper_parameters) self.atrous_rates = hyper_parameters['graph'].get('atrous_rates', [2, 1, 2]) self.crf_lr_multiplier = hyper_parameters.get('train', {}).get('crf_lr_multiplier', 1 if self.embed_type in ['WARD', 'RANDOM'] else 3200) <|end_body_0|> <|body_start_...
DGCNNGraph
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DGCNNGraph: def __init__(self, hyper_parameters): """Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "train", "save" and "data". Returns: None""" <|body_0|> def build_model(self, inputs, o...
stack_v2_sparse_classes_75kplus_train_067251
3,746
permissive
[ { "docstring": "Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains \"sharing\", \"embed\", \"graph\", \"train\", \"save\" and \"data\". Returns: None", "name": "__init__", "signature": "def __init__(self, hyper_parameters)" }, { "docstring":...
2
stack_v2_sparse_classes_30k_test_000949
Implement the Python class `DGCNNGraph` described below. Class description: Implement the DGCNNGraph class. Method signatures and docstrings: - def __init__(self, hyper_parameters): Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "...
Implement the Python class `DGCNNGraph` described below. Class description: Implement the DGCNNGraph class. Method signatures and docstrings: - def __init__(self, hyper_parameters): Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "...
5237381459db5909f392737e33618a16c1e0452a
<|skeleton|> class DGCNNGraph: def __init__(self, hyper_parameters): """Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "train", "save" and "data". Returns: None""" <|body_0|> def build_model(self, inputs, o...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DGCNNGraph: def __init__(self, hyper_parameters): """Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "train", "save" and "data". Returns: None""" super().__init__(hyper_parameters) self.atrous_rates ...
the_stack_v2_python_sparse
macadam/sl/s04_dgcnn.py
payiz-asj/Macadam
train
1
4834fd049d46da9bfd1841d0444678ed30fe8512
[ "self.output_dir = kwargs.get('output_dir', '.')\nif not os.path.isdir(self.output_dir):\n os.mkidr(self.output_dir)\nself.view_solution_pvd = True\nself.all_variables = ['velocity', 'p', 'T', 'density', 'viscosity', 'sp_upper', 'sp_lower']\nHAS_PLATE_EDGE = True\nif HAS_PLATE_EDGE:\n self.all_variables.appen...
<|body_start_0|> self.output_dir = kwargs.get('output_dir', '.') if not os.path.isdir(self.output_dir): os.mkidr(self.output_dir) self.view_solution_pvd = True self.all_variables = ['velocity', 'p', 'T', 'density', 'viscosity', 'sp_upper', 'sp_lower'] HAS_PLATE_EDGE =...
PARAVIEW_PLOT
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PARAVIEW_PLOT: def __init__(self, filein, **kwargs): """initiate Args: filein(str): path of vtu file plots(list): lists of plot""" <|body_0|> def goto_time(self, _time): """go to a different snapshot""" <|body_1|> <|end_skeleton|> <|body_start_0|> s...
stack_v2_sparse_classes_75kplus_train_067252
9,251
no_license
[ { "docstring": "initiate Args: filein(str): path of vtu file plots(list): lists of plot", "name": "__init__", "signature": "def __init__(self, filein, **kwargs)" }, { "docstring": "go to a different snapshot", "name": "goto_time", "signature": "def goto_time(self, _time)" } ]
2
null
Implement the Python class `PARAVIEW_PLOT` described below. Class description: Implement the PARAVIEW_PLOT class. Method signatures and docstrings: - def __init__(self, filein, **kwargs): initiate Args: filein(str): path of vtu file plots(list): lists of plot - def goto_time(self, _time): go to a different snapshot
Implement the Python class `PARAVIEW_PLOT` described below. Class description: Implement the PARAVIEW_PLOT class. Method signatures and docstrings: - def __init__(self, filein, **kwargs): initiate Args: filein(str): path of vtu file plots(list): lists of plot - def goto_time(self, _time): go to a different snapshot ...
d919cadce2b57811351c0615d94da5c6ebfff800
<|skeleton|> class PARAVIEW_PLOT: def __init__(self, filein, **kwargs): """initiate Args: filein(str): path of vtu file plots(list): lists of plot""" <|body_0|> def goto_time(self, _time): """go to a different snapshot""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PARAVIEW_PLOT: def __init__(self, filein, **kwargs): """initiate Args: filein(str): path of vtu file plots(list): lists of plot""" self.output_dir = kwargs.get('output_dir', '.') if not os.path.isdir(self.output_dir): os.mkidr(self.output_dir) self.view_solution_pvd...
the_stack_v2_python_sparse
paraview_scripts/base.py
lhy11009/aspectLib
train
0
9791e5658365f86124c8501423c9844651c25687
[ "noval_lis = response.xpath('//ul[@class=\"all-img-list cf\"]/li')\nfor noval_li in noval_lis:\n novalItem = QidianNovalItem()\n novalItem['coverImage'] = 'https:' + noval_li.xpath('.//div[@class=\"book-img-box\"]//img/@src').extract_first('')\n novalItem['coverImage'] = 'https:' + noval_li.css('div.book-i...
<|body_start_0|> noval_lis = response.xpath('//ul[@class="all-img-list cf"]/li') for noval_li in noval_lis: novalItem = QidianNovalItem() novalItem['coverImage'] = 'https:' + noval_li.xpath('.//div[@class="book-img-box"]//img/@src').extract_first('') novalItem['coverI...
QdSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QdSpider: def parse(self, response): """获取当前页书籍的列表,遍历 :param response: :return:""" <|body_0|> def parse_noval_detail(self, response): """获取书籍详情信息,提取章节信息 :param response: :return:""" <|body_1|> def parse_dynamic_chpater(self, response): """解析动态加载的...
stack_v2_sparse_classes_75kplus_train_067253
6,824
no_license
[ { "docstring": "获取当前页书籍的列表,遍历 :param response: :return:", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "获取书籍详情信息,提取章节信息 :param response: :return:", "name": "parse_noval_detail", "signature": "def parse_noval_detail(self, response)" }, { "docstring":...
4
stack_v2_sparse_classes_30k_train_039728
Implement the Python class `QdSpider` described below. Class description: Implement the QdSpider class. Method signatures and docstrings: - def parse(self, response): 获取当前页书籍的列表,遍历 :param response: :return: - def parse_noval_detail(self, response): 获取书籍详情信息,提取章节信息 :param response: :return: - def parse_dynamic_chpater...
Implement the Python class `QdSpider` described below. Class description: Implement the QdSpider class. Method signatures and docstrings: - def parse(self, response): 获取当前页书籍的列表,遍历 :param response: :return: - def parse_noval_detail(self, response): 获取书籍详情信息,提取章节信息 :param response: :return: - def parse_dynamic_chpater...
15e1322dcc36de4f1d1e467525761746cadb58fa
<|skeleton|> class QdSpider: def parse(self, response): """获取当前页书籍的列表,遍历 :param response: :return:""" <|body_0|> def parse_noval_detail(self, response): """获取书籍详情信息,提取章节信息 :param response: :return:""" <|body_1|> def parse_dynamic_chpater(self, response): """解析动态加载的...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class QdSpider: def parse(self, response): """获取当前页书籍的列表,遍历 :param response: :return:""" noval_lis = response.xpath('//ul[@class="all-img-list cf"]/li') for noval_li in noval_lis: novalItem = QidianNovalItem() novalItem['coverImage'] = 'https:' + noval_li.xpath('.//di...
the_stack_v2_python_sparse
Code/爬虫/scrapy框架/qidian3/qidian/qidian/spiders/qd.py
wangxuyongkang/chengxuyuanhh
train
1
eea24e4cdef7ddc1605764259cfdbf57b61415e2
[ "self.text = text\nself.rect = pygame.Rect(pos, size)\nself.action = action\nself.params = params if params is not None else []\nself.enabled = enabled\nself._font = pygame.font.SysFont('comicsansms', 18)", "color = (255, 255, 255)\ntext_color = (0, 0, 0) if self.enabled else (200, 200, 200)\nif self.rect.collide...
<|body_start_0|> self.text = text self.rect = pygame.Rect(pos, size) self.action = action self.params = params if params is not None else [] self.enabled = enabled self._font = pygame.font.SysFont('comicsansms', 18) <|end_body_0|> <|body_start_1|> color = (255, 2...
Class to assist in creation of buttons.
Button
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Button: """Class to assist in creation of buttons.""" def __init__(self, text, pos, size, action, params=None, enabled=True): """Initialize a single Button. :param text: Text to write on button. :parm pos: Position to place topleft corner of button (x, y). :parm size: Size of button ...
stack_v2_sparse_classes_75kplus_train_067254
6,310
no_license
[ { "docstring": "Initialize a single Button. :param text: Text to write on button. :parm pos: Position to place topleft corner of button (x, y). :parm size: Size of button (width, height). :parm action: Function to call when clicked. :parm params: Parameters to call action with when called. :parm enabled: Parame...
3
stack_v2_sparse_classes_30k_train_032632
Implement the Python class `Button` described below. Class description: Class to assist in creation of buttons. Method signatures and docstrings: - def __init__(self, text, pos, size, action, params=None, enabled=True): Initialize a single Button. :param text: Text to write on button. :parm pos: Position to place top...
Implement the Python class `Button` described below. Class description: Class to assist in creation of buttons. Method signatures and docstrings: - def __init__(self, text, pos, size, action, params=None, enabled=True): Initialize a single Button. :param text: Text to write on button. :parm pos: Position to place top...
4faeace5327e4e702ba57e8fdc59e313c29d1a42
<|skeleton|> class Button: """Class to assist in creation of buttons.""" def __init__(self, text, pos, size, action, params=None, enabled=True): """Initialize a single Button. :param text: Text to write on button. :parm pos: Position to place topleft corner of button (x, y). :parm size: Size of button ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Button: """Class to assist in creation of buttons.""" def __init__(self, text, pos, size, action, params=None, enabled=True): """Initialize a single Button. :param text: Text to write on button. :parm pos: Position to place topleft corner of button (x, y). :parm size: Size of button (width, heigh...
the_stack_v2_python_sparse
src/gui/utils.py
antatranta/Waids-and-Wyverns
train
0
7e7e44d69fba30084174a0f87524e7f731b27a51
[ "self.policy_manager = PolicyManager(self.project, self.kb)\nif policies is not None:\n for policy in policies:\n self.policy_manager.register_policy(policy, policy.name)", "if functions is None:\n functions = self.policy_manager.fast_cfg.functions.values()\nfor function in functions:\n self.polic...
<|body_start_0|> self.policy_manager = PolicyManager(self.project, self.kb) if policies is not None: for policy in policies: self.policy_manager.register_policy(policy, policy.name) <|end_body_0|> <|body_start_1|> if functions is None: functions = self.po...
An angr analysis that performs policy checks with a given set of policies against the binary program.
StaticPolice
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StaticPolice: """An angr analysis that performs policy checks with a given set of policies against the binary program.""" def __init__(self, policies=None): """Constructor. :param iterable policies: A collection of policies to be registered with the policy manager.""" <|body_...
stack_v2_sparse_classes_75kplus_train_067255
1,151
permissive
[ { "docstring": "Constructor. :param iterable policies: A collection of policies to be registered with the policy manager.", "name": "__init__", "signature": "def __init__(self, policies=None)" }, { "docstring": "Enforce the policy. :param iterable functions: A collection of functions to enforce ...
2
stack_v2_sparse_classes_30k_train_023125
Implement the Python class `StaticPolice` described below. Class description: An angr analysis that performs policy checks with a given set of policies against the binary program. Method signatures and docstrings: - def __init__(self, policies=None): Constructor. :param iterable policies: A collection of policies to ...
Implement the Python class `StaticPolice` described below. Class description: An angr analysis that performs policy checks with a given set of policies against the binary program. Method signatures and docstrings: - def __init__(self, policies=None): Constructor. :param iterable policies: A collection of policies to ...
964dc80c758e25c698c2cbcc454ef5954c5fa0a0
<|skeleton|> class StaticPolice: """An angr analysis that performs policy checks with a given set of policies against the binary program.""" def __init__(self, policies=None): """Constructor. :param iterable policies: A collection of policies to be registered with the policy manager.""" <|body_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StaticPolice: """An angr analysis that performs policy checks with a given set of policies against the binary program.""" def __init__(self, policies=None): """Constructor. :param iterable policies: A collection of policies to be registered with the policy manager.""" self.policy_manager ...
the_stack_v2_python_sparse
exercises/slide_104/static-police/staticpolice/staticpolice.py
Ruide/angr-dev
train
0
8cde3ad6fe45973fbc75ad87986a27d0b8f8a12e
[ "self._app = _app\nself.viewer = viewer\nself.player = None\nself.tournament = tournament", "from app.controllers.edit_player import EditPlayerController\nself._app.change_controller(EditPlayerController(self.player, self.tournament))\nself.viewer.warning = ''\nreturn False", "from app.models.player import Play...
<|body_start_0|> self._app = _app self.viewer = viewer self.player = None self.tournament = tournament <|end_body_0|> <|body_start_1|> from app.controllers.edit_player import EditPlayerController self._app.change_controller(EditPlayerController(self.player, self.tourname...
Project go_to_edit_player command class.
GotoEditPlayer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GotoEditPlayer: """Project go_to_edit_player command class.""" def __init__(self, _app, viewer, tournament): """Init go_to_edit_player command class.""" <|body_0|> def exe_command(self): """Execute command and return False to not exit application.""" <|bo...
stack_v2_sparse_classes_75kplus_train_067256
9,466
no_license
[ { "docstring": "Init go_to_edit_player command class.", "name": "__init__", "signature": "def __init__(self, _app, viewer, tournament)" }, { "docstring": "Execute command and return False to not exit application.", "name": "exe_command", "signature": "def exe_command(self)" }, { ...
3
null
Implement the Python class `GotoEditPlayer` described below. Class description: Project go_to_edit_player command class. Method signatures and docstrings: - def __init__(self, _app, viewer, tournament): Init go_to_edit_player command class. - def exe_command(self): Execute command and return False to not exit applica...
Implement the Python class `GotoEditPlayer` described below. Class description: Project go_to_edit_player command class. Method signatures and docstrings: - def __init__(self, _app, viewer, tournament): Init go_to_edit_player command class. - def exe_command(self): Execute command and return False to not exit applica...
be6089cd71c762f23725b61e8d2745cfabe4f0c0
<|skeleton|> class GotoEditPlayer: """Project go_to_edit_player command class.""" def __init__(self, _app, viewer, tournament): """Init go_to_edit_player command class.""" <|body_0|> def exe_command(self): """Execute command and return False to not exit application.""" <|bo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GotoEditPlayer: """Project go_to_edit_player command class.""" def __init__(self, _app, viewer, tournament): """Init go_to_edit_player command class.""" self._app = _app self.viewer = viewer self.player = None self.tournament = tournament def exe_command(self)...
the_stack_v2_python_sparse
app/commands/navigation.py
FortranVBA/DAP4
train
0
ba61ba7954b2a7866bb9c7f494df973efe361271
[ "super().__init__(*args, **kwargs)\nif 'direct_course' not in self.fields:\n return\nif self.instance.pk:\n course_query = self.instance.get_course().get_snapshots(include_self=True).filter(extended_object__publisher_is_draft=True).distinct()\nelse:\n course_query = models.Course.objects.filter(extended_ob...
<|body_start_0|> super().__init__(*args, **kwargs) if 'direct_course' not in self.fields: return if self.instance.pk: course_query = self.instance.get_course().get_snapshots(include_self=True).filter(extended_object__publisher_is_draft=True).distinct() else: ...
Admin form used for frontend editing.
CourseRunAdminForm
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CourseRunAdminForm: """Admin form used for frontend editing.""" def __init__(self, *args, **kwargs): """If the form is instanciated to update an existing course run: > show the direct course select box only if the course has one or more snapshots and limit choices to either the maste...
stack_v2_sparse_classes_75kplus_train_067257
11,939
permissive
[ { "docstring": "If the form is instanciated to update an existing course run: > show the direct course select box only if the course has one or more snapshots and limit choices to either the master course or one of its snapshots If the form is instanciated to create a new course run and the \"Add\" form is open...
2
stack_v2_sparse_classes_30k_train_032102
Implement the Python class `CourseRunAdminForm` described below. Class description: Admin form used for frontend editing. Method signatures and docstrings: - def __init__(self, *args, **kwargs): If the form is instanciated to update an existing course run: > show the direct course select box only if the course has on...
Implement the Python class `CourseRunAdminForm` described below. Class description: Admin form used for frontend editing. Method signatures and docstrings: - def __init__(self, *args, **kwargs): If the form is instanciated to update an existing course run: > show the direct course select box only if the course has on...
f2d46fc46b271eb3b4d565039a29c15ba15f027c
<|skeleton|> class CourseRunAdminForm: """Admin form used for frontend editing.""" def __init__(self, *args, **kwargs): """If the form is instanciated to update an existing course run: > show the direct course select box only if the course has one or more snapshots and limit choices to either the maste...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CourseRunAdminForm: """Admin form used for frontend editing.""" def __init__(self, *args, **kwargs): """If the form is instanciated to update an existing course run: > show the direct course select box only if the course has one or more snapshots and limit choices to either the master course or o...
the_stack_v2_python_sparse
src/richie/apps/courses/admin.py
openfun/richie
train
238
6584c32016b1dbe77f5bd43c1fdda232d6a80c72
[ "current_app.logger.info('Method called')\ntry:\n response = g.requests.get('{}/{}/state/{}'.format(SESSION_API_URL, token_id, subsection, headers={'X-Trace-ID': g.trace_id}))\nexcept Exception as ex:\n current_app.logger.warning('Failed to get session state. TraceID : {} - Exception - {}'.format(g.trace_id, ...
<|body_start_0|> current_app.logger.info('Method called') try: response = g.requests.get('{}/{}/state/{}'.format(SESSION_API_URL, token_id, subsection, headers={'X-Trace-ID': g.trace_id})) except Exception as ex: current_app.logger.warning('Failed to get session state. Tr...
SessionAPIService
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionAPIService: def get_session_state(token_id, subsection): """Returns either a JSON object containing the session contents, or returns None if the session isn't found. :param token_id: Identifier for the session. :param subsection: The subsection of session state that should be retr...
stack_v2_sparse_classes_75kplus_train_067258
5,336
permissive
[ { "docstring": "Returns either a JSON object containing the session contents, or returns None if the session isn't found. :param token_id: Identifier for the session. :param subsection: The subsection of session state that should be retrieved. :return: Returns dictionary representation of the response or None."...
5
stack_v2_sparse_classes_30k_train_025891
Implement the Python class `SessionAPIService` described below. Class description: Implement the SessionAPIService class. Method signatures and docstrings: - def get_session_state(token_id, subsection): Returns either a JSON object containing the session contents, or returns None if the session isn't found. :param to...
Implement the Python class `SessionAPIService` described below. Class description: Implement the SessionAPIService class. Method signatures and docstrings: - def get_session_state(token_id, subsection): Returns either a JSON object containing the session contents, or returns None if the session isn't found. :param to...
d92446a9972ebbcd9a43a7a7444a528aa2f30bf7
<|skeleton|> class SessionAPIService: def get_session_state(token_id, subsection): """Returns either a JSON object containing the session contents, or returns None if the session isn't found. :param token_id: Identifier for the session. :param subsection: The subsection of session state that should be retr...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SessionAPIService: def get_session_state(token_id, subsection): """Returns either a JSON object containing the session contents, or returns None if the session isn't found. :param token_id: Identifier for the session. :param subsection: The subsection of session state that should be retrieved. :return...
the_stack_v2_python_sparse
maintain_frontend/dependencies/session_api/session_service.py
uk-gov-mirror/LandRegistry.maintain-frontend
train
0
1090157872bb59bd816ef4117e8c76b82eb82e70
[ "tag_name = obj.tag_name\nlogger.info('delete tag {tag}'.format(tag=ensure_utf8(tag_name)))\ngs = Gallery.objects.filter(tags__contains=tag_name + ',') | Gallery.objects.filter(tags__contains=',' + tag_name)\nfor gallery in gs:\n logger.info('delete tag for gallery : {g_id}'.format(g_id=gallery.gallery_id))\n ...
<|body_start_0|> tag_name = obj.tag_name logger.info('delete tag {tag}'.format(tag=ensure_utf8(tag_name))) gs = Gallery.objects.filter(tags__contains=tag_name + ',') | Gallery.objects.filter(tags__contains=',' + tag_name) for gallery in gs: logger.info('delete tag for gallery...
TagAdmin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TagAdmin: def delete_model(self, request, obj): """TODO 清理相关tag的缓存 删除tag,重量级操作 1、找到所有包含这个tag的图集,修改tag字段 2、删除redis中的tag索引 3、删除该tag,刷新缓存 :param request: :param obj: :return:""" <|body_0|> def save_model(self, request, obj, form, change): """新增或更新tag,重量级操作 1、数据库中查找tag_n...
stack_v2_sparse_classes_75kplus_train_067259
3,458
no_license
[ { "docstring": "TODO 清理相关tag的缓存 删除tag,重量级操作 1、找到所有包含这个tag的图集,修改tag字段 2、删除redis中的tag索引 3、删除该tag,刷新缓存 :param request: :param obj: :return:", "name": "delete_model", "signature": "def delete_model(self, request, obj)" }, { "docstring": "新增或更新tag,重量级操作 1、数据库中查找tag_name不存在,存在则直接返回 2、数据库中插入tag 3、按照gal...
2
null
Implement the Python class `TagAdmin` described below. Class description: Implement the TagAdmin class. Method signatures and docstrings: - def delete_model(self, request, obj): TODO 清理相关tag的缓存 删除tag,重量级操作 1、找到所有包含这个tag的图集,修改tag字段 2、删除redis中的tag索引 3、删除该tag,刷新缓存 :param request: :param obj: :return: - def save_model(se...
Implement the Python class `TagAdmin` described below. Class description: Implement the TagAdmin class. Method signatures and docstrings: - def delete_model(self, request, obj): TODO 清理相关tag的缓存 删除tag,重量级操作 1、找到所有包含这个tag的图集,修改tag字段 2、删除redis中的tag索引 3、删除该tag,刷新缓存 :param request: :param obj: :return: - def save_model(se...
b65b053adb7f574eef76612913de962e75b93b26
<|skeleton|> class TagAdmin: def delete_model(self, request, obj): """TODO 清理相关tag的缓存 删除tag,重量级操作 1、找到所有包含这个tag的图集,修改tag字段 2、删除redis中的tag索引 3、删除该tag,刷新缓存 :param request: :param obj: :return:""" <|body_0|> def save_model(self, request, obj, form, change): """新增或更新tag,重量级操作 1、数据库中查找tag_n...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TagAdmin: def delete_model(self, request, obj): """TODO 清理相关tag的缓存 删除tag,重量级操作 1、找到所有包含这个tag的图集,修改tag字段 2、删除redis中的tag索引 3、删除该tag,刷新缓存 :param request: :param obj: :return:""" tag_name = obj.tag_name logger.info('delete tag {tag}'.format(tag=ensure_utf8(tag_name))) gs = Gallery....
the_stack_v2_python_sparse
mysite/beauty/admin.py
gaoconghui/image_site
train
8
ed407e708913b85db248b3493889e67babb38946
[ "self.lsa_components = lsa_components\nself.tfidf_parameters = tfidf_parameters\nself._tfv = TfidfVectorizer(**self.tfidf_parameters)\nself._svd = TruncatedSVD(self.lsa_components)", "X.fillna('NA', inplace=True)\ntfidf_output_csr = self._tfv.fit_transform(X, y)\nself._svd.fit(tfidf_output_csr)\nprint('LSA explai...
<|body_start_0|> self.lsa_components = lsa_components self.tfidf_parameters = tfidf_parameters self._tfv = TfidfVectorizer(**self.tfidf_parameters) self._svd = TruncatedSVD(self.lsa_components) <|end_body_0|> <|body_start_1|> X.fillna('NA', inplace=True) tfidf_output_csr...
This class defines a Scikit-Learn transformer that implements a Latent Semantic Analysis.
LSAVectorizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LSAVectorizer: """This class defines a Scikit-Learn transformer that implements a Latent Semantic Analysis.""" def __init__(self, lsa_components, tfidf_parameters={'analyzer': 'word', 'ngram_range': (1, 1), 'min_df': 10}): """This is the class' constructor. Parameters ---------- lsa_...
stack_v2_sparse_classes_75kplus_train_067260
14,227
no_license
[ { "docstring": "This is the class' constructor. Parameters ---------- lsa_components : positive integer Number of components we want to keep. tfidf_parameters : dict (default = {\"analyzer\": \"word\", \"ngram_range\": (1, 1), \"min_df\": 10}) Dict containing parameters of TfidfVectorizer used in this class. Ea...
3
stack_v2_sparse_classes_30k_train_040824
Implement the Python class `LSAVectorizer` described below. Class description: This class defines a Scikit-Learn transformer that implements a Latent Semantic Analysis. Method signatures and docstrings: - def __init__(self, lsa_components, tfidf_parameters={'analyzer': 'word', 'ngram_range': (1, 1), 'min_df': 10}): T...
Implement the Python class `LSAVectorizer` described below. Class description: This class defines a Scikit-Learn transformer that implements a Latent Semantic Analysis. Method signatures and docstrings: - def __init__(self, lsa_components, tfidf_parameters={'analyzer': 'word', 'ngram_range': (1, 1), 'min_df': 10}): T...
ba9a7a15a3ae8b65cb09044489ee1d907a702909
<|skeleton|> class LSAVectorizer: """This class defines a Scikit-Learn transformer that implements a Latent Semantic Analysis.""" def __init__(self, lsa_components, tfidf_parameters={'analyzer': 'word', 'ngram_range': (1, 1), 'min_df': 10}): """This is the class' constructor. Parameters ---------- lsa_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LSAVectorizer: """This class defines a Scikit-Learn transformer that implements a Latent Semantic Analysis.""" def __init__(self, lsa_components, tfidf_parameters={'analyzer': 'word', 'ngram_range': (1, 1), 'min_df': 10}): """This is the class' constructor. Parameters ---------- lsa_components : ...
the_stack_v2_python_sparse
python_code/M5_Forecasting_Accuracy/m5_forecasting_accuracy/preprocessing/text_encoders.py
ThomasSELECK/src
train
0
b6038537aaa2227adcf6fca88dc1df24e58d8157
[ "history_values = history_table.get_attribute(units)\nhistory_values_without_zeros_idx = where(history_values > 0)[0]\nnbuildings = history_values_without_zeros_idx.size\nids = arange(nbuildings)\ngrid_ids = history_table.get_attribute_by_index('grid_id', history_values_without_zeros_idx)\nstorage = StorageFactory(...
<|body_start_0|> history_values = history_table.get_attribute(units) history_values_without_zeros_idx = where(history_values > 0)[0] nbuildings = history_values_without_zeros_idx.size ids = arange(nbuildings) grid_ids = history_table.get_attribute_by_index('grid_id', history_valu...
BuildingCreator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BuildingCreator: def create_buildings_from_history(self, history_table, type, type_code, units, building_categories): """Returns a BuildingDataset created from the information this development_event_history table. 'type' is the type of the buildings ('residential' or 'commercial') 'type_...
stack_v2_sparse_classes_75kplus_train_067261
5,570
no_license
[ { "docstring": "Returns a BuildingDataset created from the information this development_event_history table. 'type' is the type of the buildings ('residential' or 'commercial') 'type_code' is an interger code for the corresponding building type. 'units' is a string like 'residential_units' or 'commercial_sqft'....
3
null
Implement the Python class `BuildingCreator` described below. Class description: Implement the BuildingCreator class. Method signatures and docstrings: - def create_buildings_from_history(self, history_table, type, type_code, units, building_categories): Returns a BuildingDataset created from the information this dev...
Implement the Python class `BuildingCreator` described below. Class description: Implement the BuildingCreator class. Method signatures and docstrings: - def create_buildings_from_history(self, history_table, type, type_code, units, building_categories): Returns a BuildingDataset created from the information this dev...
c392d15b35aa1d47bbc185ed76314f8e6dd9f92f
<|skeleton|> class BuildingCreator: def create_buildings_from_history(self, history_table, type, type_code, units, building_categories): """Returns a BuildingDataset created from the information this development_event_history table. 'type' is the type of the buildings ('residential' or 'commercial') 'type_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BuildingCreator: def create_buildings_from_history(self, history_table, type, type_code, units, building_categories): """Returns a BuildingDataset created from the information this development_event_history table. 'type' is the type of the buildings ('residential' or 'commercial') 'type_code' is an in...
the_stack_v2_python_sparse
urbansim/datasets/building_dataset.py
psrc/urbansim
train
4
b1bd9176ed8c7004b2fe625b5ced7b081418164c
[ "self.sigmoid_layers = []\nself.rbm_layers = []\nself.params = []\nself.n_layers = len(hidden_layers_sizes)\nassert self.n_layers > 0\nif not theano_rng:\n theano_rng = MRG_RandomStreams(numpy_rng.randint(2 ** 30))\nself.x = T.matrix('x')\nself.y = T.ivector('y')\nfor i in range(self.n_layers):\n if i == 0:\n...
<|body_start_0|> self.sigmoid_layers = [] self.rbm_layers = [] self.params = [] self.n_layers = len(hidden_layers_sizes) assert self.n_layers > 0 if not theano_rng: theano_rng = MRG_RandomStreams(numpy_rng.randint(2 ** 30)) self.x = T.matrix('x') ...
Deep Belief Network
DBN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DBN: """Deep Belief Network""" def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10): """This class is made to support a variable number of layers. numpy_rng is the random state number. numpy_rng is the generator to draw initial weights....
stack_v2_sparse_classes_75kplus_train_067262
9,191
no_license
[ { "docstring": "This class is made to support a variable number of layers. numpy_rng is the random state number. numpy_rng is the generator to draw initial weights. theano_rng is for tensor's theano rng. n_ins is an integer of the input dimension. hidden_layer_sizes is the intermediate layers size. n_outs is ou...
3
stack_v2_sparse_classes_30k_val_001104
Implement the Python class `DBN` described below. Class description: Deep Belief Network Method signatures and docstrings: - def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10): This class is made to support a variable number of layers. numpy_rng is the random state nu...
Implement the Python class `DBN` described below. Class description: Deep Belief Network Method signatures and docstrings: - def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10): This class is made to support a variable number of layers. numpy_rng is the random state nu...
6849cc891bbb9ac69cb20dfb13fe6bb5bd77d8c5
<|skeleton|> class DBN: """Deep Belief Network""" def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10): """This class is made to support a variable number of layers. numpy_rng is the random state number. numpy_rng is the generator to draw initial weights....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DBN: """Deep Belief Network""" def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10): """This class is made to support a variable number of layers. numpy_rng is the random state number. numpy_rng is the generator to draw initial weights. theano_rng i...
the_stack_v2_python_sparse
algebra/linear/deepbeliefnetwork.py
HussainAther/mathematics
train
2
f04e4966acd9085b3a334aa40a4e031c10e82e54
[ "self.__args__ = args\nself.__kargs__ = kargs\nself.__topic__ = topic\nself.__conn__ = connection\nself.__balanced__ = balanced", "cons = None\ntopic = self.__conn__.create_topic(self.__topic__)\nif self.__balanced__ is True:\n cons = topic.get_balanced_consumer(*self.__args__, **self.__kargs__)\nelse:\n co...
<|body_start_0|> self.__args__ = args self.__kargs__ = kargs self.__topic__ = topic self.__conn__ = connection self.__balanced__ = balanced <|end_body_0|> <|body_start_1|> cons = None topic = self.__conn__.create_topic(self.__topic__) if self.__balanced__...
A class capable of create a consumer connection.
ConsumerFactory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConsumerFactory: """A class capable of create a consumer connection.""" def __init__(self, connection, topic, balanced, args, kargs): """Create a ConsumerFactory. A object capable of create a consumer connection Parameters ---------- connection: ConnectionBuilder A object that holds ...
stack_v2_sparse_classes_75kplus_train_067263
2,257
permissive
[ { "docstring": "Create a ConsumerFactory. A object capable of create a consumer connection Parameters ---------- connection: ConnectionBuilder A object that holds the connection information topic: str Name of topic that messages will be read from balanced: bool True for a balanced consumer False for a simple co...
3
stack_v2_sparse_classes_30k_train_010245
Implement the Python class `ConsumerFactory` described below. Class description: A class capable of create a consumer connection. Method signatures and docstrings: - def __init__(self, connection, topic, balanced, args, kargs): Create a ConsumerFactory. A object capable of create a consumer connection Parameters ----...
Implement the Python class `ConsumerFactory` described below. Class description: A class capable of create a consumer connection. Method signatures and docstrings: - def __init__(self, connection, topic, balanced, args, kargs): Create a ConsumerFactory. A object capable of create a consumer connection Parameters ----...
f2c958df88c5698148aae4c5314dd39e31e995c3
<|skeleton|> class ConsumerFactory: """A class capable of create a consumer connection.""" def __init__(self, connection, topic, balanced, args, kargs): """Create a ConsumerFactory. A object capable of create a consumer connection Parameters ---------- connection: ConnectionBuilder A object that holds ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConsumerFactory: """A class capable of create a consumer connection.""" def __init__(self, connection, topic, balanced, args, kargs): """Create a ConsumerFactory. A object capable of create a consumer connection Parameters ---------- connection: ConnectionBuilder A object that holds the connectio...
the_stack_v2_python_sparse
kafka_client_decorators/kafka/consumer_factory.py
cdsedson/kafka-decorator
train
1
4cbc13db75557fa69d6deda7d0ec57075e7e4bdd
[ "self._time_intervals = time_intervals\nif index is not None:\n self._index = index\n self.shape = (index.sum(),)\nelse:\n self._index = slice(None)\n self.shape = (len(time_intervals),)\nself.name = epoch_name", "if time_slice:\n raise NotImplementedError('todo')\nelse:\n start_times = self._ti...
<|body_start_0|> self._time_intervals = time_intervals if index is not None: self._index = index self.shape = (index.sum(),) else: self._index = slice(None) self.shape = (len(time_intervals),) self.name = epoch_name <|end_body_0|> <|body_s...
EpochProxy
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EpochProxy: def __init__(self, time_intervals, epoch_name=None, index=None): """:param time_intervals: An epochs table, which is a specific TimeIntervals table that stores info about long periods :param epoch_name: (str) Name of the epoch object :param index: (np.array, slice) Slice obje...
stack_v2_sparse_classes_75kplus_train_067264
36,998
permissive
[ { "docstring": ":param time_intervals: An epochs table, which is a specific TimeIntervals table that stores info about long periods :param epoch_name: (str) Name of the epoch object :param index: (np.array, slice) Slice object or array of bool values masking time_intervals to be used. In case of an array it has...
2
null
Implement the Python class `EpochProxy` described below. Class description: Implement the EpochProxy class. Method signatures and docstrings: - def __init__(self, time_intervals, epoch_name=None, index=None): :param time_intervals: An epochs table, which is a specific TimeIntervals table that stores info about long p...
Implement the Python class `EpochProxy` described below. Class description: Implement the EpochProxy class. Method signatures and docstrings: - def __init__(self, time_intervals, epoch_name=None, index=None): :param time_intervals: An epochs table, which is a specific TimeIntervals table that stores info about long p...
354c8d9d5fbc4daad3547773d2f281f8c163d208
<|skeleton|> class EpochProxy: def __init__(self, time_intervals, epoch_name=None, index=None): """:param time_intervals: An epochs table, which is a specific TimeIntervals table that stores info about long periods :param epoch_name: (str) Name of the epoch object :param index: (np.array, slice) Slice obje...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EpochProxy: def __init__(self, time_intervals, epoch_name=None, index=None): """:param time_intervals: An epochs table, which is a specific TimeIntervals table that stores info about long periods :param epoch_name: (str) Name of the epoch object :param index: (np.array, slice) Slice object or array of...
the_stack_v2_python_sparse
neo/io/nwbio.py
NeuralEnsemble/python-neo
train
265
a861ed283f44f9704de3a8b7a1ba861f0fc0dc5f
[ "self.log = log or self.log\nself.ssl_config = ssl_config or self.ssl_config_cls()\nif not qnam:\n if not parent:\n qnam = QNetworkAccessManager()\n else:\n qnam = QNetworkAccessManager(parent)\n self._qnam = qnam\nqnam.finished.connect(self._finished)\nself.transfers = {}", "transfer = sel...
<|body_start_0|> self.log = log or self.log self.ssl_config = ssl_config or self.ssl_config_cls() if not qnam: if not parent: qnam = QNetworkAccessManager() else: qnam = QNetworkAccessManager(parent) self._qnam = qnam qn...
Make HTTP requests according to a specified policy.
Client
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Client: """Make HTTP requests according to a specified policy.""" def __init__(self, ssl_config=None, log=None, qnam=None, parent=None): """:arg ssl_config: Optional. SSLConfig instance to use. :arg log: Optional. Logger to use. Defaults to logger .qt.client.Client. :arg qnam: Option...
stack_v2_sparse_classes_75kplus_train_067265
9,933
no_license
[ { "docstring": ":arg ssl_config: Optional. SSLConfig instance to use. :arg log: Optional. Logger to use. Defaults to logger .qt.client.Client. :arg qnam: Optional. A QNetworkAccessManager to be used by this client. If None is passed, the QNAM will be created automatically. :arg parent: Optional. A QObject to pa...
3
stack_v2_sparse_classes_30k_train_030973
Implement the Python class `Client` described below. Class description: Make HTTP requests according to a specified policy. Method signatures and docstrings: - def __init__(self, ssl_config=None, log=None, qnam=None, parent=None): :arg ssl_config: Optional. SSLConfig instance to use. :arg log: Optional. Logger to use...
Implement the Python class `Client` described below. Class description: Make HTTP requests according to a specified policy. Method signatures and docstrings: - def __init__(self, ssl_config=None, log=None, qnam=None, parent=None): :arg ssl_config: Optional. SSLConfig instance to use. :arg log: Optional. Logger to use...
71db923df2862ff246755f1d819b0eecc76960ef
<|skeleton|> class Client: """Make HTTP requests according to a specified policy.""" def __init__(self, ssl_config=None, log=None, qnam=None, parent=None): """:arg ssl_config: Optional. SSLConfig instance to use. :arg log: Optional. Logger to use. Defaults to logger .qt.client.Client. :arg qnam: Option...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Client: """Make HTTP requests according to a specified policy.""" def __init__(self, ssl_config=None, log=None, qnam=None, parent=None): """:arg ssl_config: Optional. SSLConfig instance to use. :arg log: Optional. Logger to use. Defaults to logger .qt.client.Client. :arg qnam: Optional. A QNetwor...
the_stack_v2_python_sparse
because/interfaces/qt/client.py
jrbeckwith/because
train
3
15ae9750fd1fe44be7d58f78d711e9958bbdacb7
[ "serializer = self.get_serializer(data=request.data)\nif serializer.is_valid():\n user = serializer.create(serializer.data)\n login_response_serializer = serializers.LoginResponseV2Serializer(user)\n return Response(login_response_serializer.data)\nreturn Response(serializer.errors, status=status.HTTP_400_...
<|body_start_0|> serializer = self.get_serializer(data=request.data) if serializer.is_valid(): user = serializer.create(serializer.data) login_response_serializer = serializers.LoginResponseV2Serializer(user) return Response(login_response_serializer.data) ret...
AuthViewSet
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthViewSet: def login(self, request, *args, **kwargs): """Logs the user in. --- type: email: required: true type: string password: required: true type: string device_os: required: true type: string device_user_token: required: false type: string parameters: - name: email description: em...
stack_v2_sparse_classes_75kplus_train_067266
3,412
permissive
[ { "docstring": "Logs the user in. --- type: email: required: true type: string password: required: true type: string device_os: required: true type: string device_user_token: required: false type: string parameters: - name: email description: email user. required: true type: string paramType: form - name: passw...
3
stack_v2_sparse_classes_30k_train_026787
Implement the Python class `AuthViewSet` described below. Class description: Implement the AuthViewSet class. Method signatures and docstrings: - def login(self, request, *args, **kwargs): Logs the user in. --- type: email: required: true type: string password: required: true type: string device_os: required: true ty...
Implement the Python class `AuthViewSet` described below. Class description: Implement the AuthViewSet class. Method signatures and docstrings: - def login(self, request, *args, **kwargs): Logs the user in. --- type: email: required: true type: string password: required: true type: string device_os: required: true ty...
7349ce18f56658d67daedf5e1abb352b5c15a029
<|skeleton|> class AuthViewSet: def login(self, request, *args, **kwargs): """Logs the user in. --- type: email: required: true type: string password: required: true type: string device_os: required: true type: string device_user_token: required: false type: string parameters: - name: email description: em...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AuthViewSet: def login(self, request, *args, **kwargs): """Logs the user in. --- type: email: required: true type: string password: required: true type: string device_os: required: true type: string device_user_token: required: false type: string parameters: - name: email description: email user. requ...
the_stack_v2_python_sparse
src/tandlr/authentication/api.py
shrmoud/schoolapp
train
0
aafcdbced26dc2792040871de952ec7290b5ffdf
[ "if n < 2:\n raise ValueError('There must be at least 2 atoms.')\nnx = 3 * n\nnf = n * (n - 1) // 2\nsuper().__init__(self._fdist, nf=nf, nx=nx, maxderiv=None, zlevel=None)\nself.n = n\nreturn", "x = nitrogen.dfun.X2adf(X, deriv, var)\nn = self.n\ny = []\nfor i in range(n):\n for j in range(i + 1, n):\n ...
<|body_start_0|> if n < 2: raise ValueError('There must be at least 2 atoms.') nx = 3 * n nf = n * (n - 1) // 2 super().__init__(self._fdist, nf=nf, nx=nx, maxderiv=None, zlevel=None) self.n = n return <|end_body_0|> <|body_start_1|> x = nitrogen.dfun...
Internuclear coordinate function for linear distance Attributes ---------- n : integer The number of atoms.
InternuclearR
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InternuclearR: """Internuclear coordinate function for linear distance Attributes ---------- n : integer The number of atoms.""" def __init__(self, n): """Parameters ---------- n : integer The number of atoms""" <|body_0|> def _fdist(self, X, deriv=0, out=None, var=None)...
stack_v2_sparse_classes_75kplus_train_067267
37,911
permissive
[ { "docstring": "Parameters ---------- n : integer The number of atoms", "name": "__init__", "signature": "def __init__(self, n)" }, { "docstring": "evaluation function", "name": "_fdist", "signature": "def _fdist(self, X, deriv=0, out=None, var=None)" } ]
2
stack_v2_sparse_classes_30k_train_022764
Implement the Python class `InternuclearR` described below. Class description: Internuclear coordinate function for linear distance Attributes ---------- n : integer The number of atoms. Method signatures and docstrings: - def __init__(self, n): Parameters ---------- n : integer The number of atoms - def _fdist(self,...
Implement the Python class `InternuclearR` described below. Class description: Internuclear coordinate function for linear distance Attributes ---------- n : integer The number of atoms. Method signatures and docstrings: - def __init__(self, n): Parameters ---------- n : integer The number of atoms - def _fdist(self,...
c6341a58331deef3728cc43c627c556139deb673
<|skeleton|> class InternuclearR: """Internuclear coordinate function for linear distance Attributes ---------- n : integer The number of atoms.""" def __init__(self, n): """Parameters ---------- n : integer The number of atoms""" <|body_0|> def _fdist(self, X, deriv=0, out=None, var=None)...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class InternuclearR: """Internuclear coordinate function for linear distance Attributes ---------- n : integer The number of atoms.""" def __init__(self, n): """Parameters ---------- n : integer The number of atoms""" if n < 2: raise ValueError('There must be at least 2 atoms.') ...
the_stack_v2_python_sparse
nitrogen/pes/fit.py
bchangala/nitrogen
train
11
23de18d020f15fe24dcd19bb09b7180e18bab111
[ "input_file = self.get_data(self.test_dir, 'jw88600073001_gs-id_7_image-uncal.fits')\nGuiderPipeline.call(input_file, output_file='jw88600073001_gs-id_7_image-cal.fits')\noutputs = [('jw88600073001_gs-id_7_image-cal.fits', 'jw88600073001_gs-id_7_image-cal_ref.fits', ['primary', 'sci', 'dq'])]\nself.compare_outputs(...
<|body_start_0|> input_file = self.get_data(self.test_dir, 'jw88600073001_gs-id_7_image-uncal.fits') GuiderPipeline.call(input_file, output_file='jw88600073001_gs-id_7_image-cal.fits') outputs = [('jw88600073001_gs-id_7_image-cal.fits', 'jw88600073001_gs-id_7_image-cal_ref.fits', ['primary', 'sc...
TestGuiderPipeline
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestGuiderPipeline: def test_guider_pipeline1(self): """Regression test of calwebb_guider pipeline performed on ID-image data.""" <|body_0|> def test_guider_pipeline2(self): """Regression test of calwebb_guider pipeline performed on ACQ-1 data.""" <|body_1|> ...
stack_v2_sparse_classes_75kplus_train_067268
2,333
permissive
[ { "docstring": "Regression test of calwebb_guider pipeline performed on ID-image data.", "name": "test_guider_pipeline1", "signature": "def test_guider_pipeline1(self)" }, { "docstring": "Regression test of calwebb_guider pipeline performed on ACQ-1 data.", "name": "test_guider_pipeline2", ...
3
stack_v2_sparse_classes_30k_train_012027
Implement the Python class `TestGuiderPipeline` described below. Class description: Implement the TestGuiderPipeline class. Method signatures and docstrings: - def test_guider_pipeline1(self): Regression test of calwebb_guider pipeline performed on ID-image data. - def test_guider_pipeline2(self): Regression test of ...
Implement the Python class `TestGuiderPipeline` described below. Class description: Implement the TestGuiderPipeline class. Method signatures and docstrings: - def test_guider_pipeline1(self): Regression test of calwebb_guider pipeline performed on ID-image data. - def test_guider_pipeline2(self): Regression test of ...
e3a5b2d8bb50d92ccca46cd3bbd6585d5238000a
<|skeleton|> class TestGuiderPipeline: def test_guider_pipeline1(self): """Regression test of calwebb_guider pipeline performed on ID-image data.""" <|body_0|> def test_guider_pipeline2(self): """Regression test of calwebb_guider pipeline performed on ACQ-1 data.""" <|body_1|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestGuiderPipeline: def test_guider_pipeline1(self): """Regression test of calwebb_guider pipeline performed on ID-image data.""" input_file = self.get_data(self.test_dir, 'jw88600073001_gs-id_7_image-uncal.fits') GuiderPipeline.call(input_file, output_file='jw88600073001_gs-id_7_image...
the_stack_v2_python_sparse
jwst/tests_nightly/general/fgs/test_guider_pipeline.py
mperrin/jwst
train
0
2002a2cb97c69129b4ac16445eee3d9be3f38a2e
[ "attrs = attrs or []\nself.attrs = list(attrs)\nif ORTH in self.attrs:\n self.attrs.pop(ORTH)\nif SPACY in self.attrs:\n self.attrs.pop(SPACY)\nself.attrs.insert(0, ORTH)\nself.tokens = []\nself.spaces = []\nself.strings = set()", "array = doc.to_array(self.attrs)\nif len(array.shape) == 1:\n array = arr...
<|body_start_0|> attrs = attrs or [] self.attrs = list(attrs) if ORTH in self.attrs: self.attrs.pop(ORTH) if SPACY in self.attrs: self.attrs.pop(SPACY) self.attrs.insert(0, ORTH) self.tokens = [] self.spaces = [] self.strings = set(...
Serialize analyses from a collection of doc objects.
Binder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Binder: """Serialize analyses from a collection of doc objects.""" def __init__(self, attrs=None): """Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are always serialized, so they're not required. Defaults to ...
stack_v2_sparse_classes_75kplus_train_067269
4,226
permissive
[ { "docstring": "Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are always serialized, so they're not required. Defaults to None.", "name": "__init__", "signature": "def __init__(self, attrs=None)" }, { "docstring": "Add a...
6
stack_v2_sparse_classes_30k_train_016457
Implement the Python class `Binder` described below. Class description: Serialize analyses from a collection of doc objects. Method signatures and docstrings: - def __init__(self, attrs=None): Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are...
Implement the Python class `Binder` described below. Class description: Serialize analyses from a collection of doc objects. Method signatures and docstrings: - def __init__(self, attrs=None): Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are...
a062c118f12b93172e31e8ca115ce3f871b64461
<|skeleton|> class Binder: """Serialize analyses from a collection of doc objects.""" def __init__(self, attrs=None): """Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are always serialized, so they're not required. Defaults to ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Binder: """Serialize analyses from a collection of doc objects.""" def __init__(self, attrs=None): """Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are always serialized, so they're not required. Defaults to None.""" ...
the_stack_v2_python_sparse
python/spaCy/2018/12/_serialize.py
rosoareslv/SED99
train
1
ba957e50b86531f9cb94124952a63c75386fb644
[ "self.start = datetime.now()\nself.duration = timedelta(seconds=30)\nself.end = self.start + self.duration\nself.assertEqual(time_it(self.start, self.end), self.duration.seconds)\nself.assertRaises(BadTimeObjError, time_it, 'first', 'second')", "numlist = []\nfor num in range(0, 1000):\n numlist.append(gennum(...
<|body_start_0|> self.start = datetime.now() self.duration = timedelta(seconds=30) self.end = self.start + self.duration self.assertEqual(time_it(self.start, self.end), self.duration.seconds) self.assertRaises(BadTimeObjError, time_it, 'first', 'second') <|end_body_0|> <|body_st...
MathQuiz
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MathQuiz: def test_time_it(self): """Test the time_it function""" <|body_0|> def test_randint(self): """Tests the random number generator part of math_quiz.py""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.start = datetime.now() self.d...
stack_v2_sparse_classes_75kplus_train_067270
1,825
no_license
[ { "docstring": "Test the time_it function", "name": "test_time_it", "signature": "def test_time_it(self)" }, { "docstring": "Tests the random number generator part of math_quiz.py", "name": "test_randint", "signature": "def test_randint(self)" } ]
2
stack_v2_sparse_classes_30k_train_026767
Implement the Python class `MathQuiz` described below. Class description: Implement the MathQuiz class. Method signatures and docstrings: - def test_time_it(self): Test the time_it function - def test_randint(self): Tests the random number generator part of math_quiz.py
Implement the Python class `MathQuiz` described below. Class description: Implement the MathQuiz class. Method signatures and docstrings: - def test_time_it(self): Test the time_it function - def test_randint(self): Tests the random number generator part of math_quiz.py <|skeleton|> class MathQuiz: def test_tim...
b32f83aa1b705a5ad384b73c618f04f7d2622753
<|skeleton|> class MathQuiz: def test_time_it(self): """Test the time_it function""" <|body_0|> def test_randint(self): """Tests the random number generator part of math_quiz.py""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MathQuiz: def test_time_it(self): """Test the time_it function""" self.start = datetime.now() self.duration = timedelta(seconds=30) self.end = self.start + self.duration self.assertEqual(time_it(self.start, self.end), self.duration.seconds) self.assertRaises(Bad...
the_stack_v2_python_sparse
ostPython3/test_math_quiz.py
deepbsd/OST_Python
train
1
5f1383e0f413352dc8eb3ff69217fcd55831d78d
[ "self.database_uri = None\nself.config = dict()\nself.max_pool = 100\nself.min_pool = 0\nself.max_idle_time = None\nself.connection_timeout = 10000\nself.heartbeat_frequency = 10000\nself.server_timeout = 100", "self.database_uri = app.config.get('MONGODB_DATABASE_URI')\nself.config['maxPoolSize'] = app.config.ge...
<|body_start_0|> self.database_uri = None self.config = dict() self.max_pool = 100 self.min_pool = 0 self.max_idle_time = None self.connection_timeout = 10000 self.heartbeat_frequency = 10000 self.server_timeout = 100 <|end_body_0|> <|body_start_1|> ...
MongoAlchemy
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MongoAlchemy: def __init__(self): """Initialize variables for the MongoDB database connection""" <|body_0|> def init_app(self, app: Flask=None) -> None: """This function will get config values to set configurations for connection :param app: Instance of the Flask App...
stack_v2_sparse_classes_75kplus_train_067271
2,517
permissive
[ { "docstring": "Initialize variables for the MongoDB database connection", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "This function will get config values to set configurations for connection :param app: Instance of the Flask App :return: None", "name": "init_ap...
4
stack_v2_sparse_classes_30k_train_018550
Implement the Python class `MongoAlchemy` described below. Class description: Implement the MongoAlchemy class. Method signatures and docstrings: - def __init__(self): Initialize variables for the MongoDB database connection - def init_app(self, app: Flask=None) -> None: This function will get config values to set co...
Implement the Python class `MongoAlchemy` described below. Class description: Implement the MongoAlchemy class. Method signatures and docstrings: - def __init__(self): Initialize variables for the MongoDB database connection - def init_app(self, app: Flask=None) -> None: This function will get config values to set co...
a008845ca403c4bb07666ed9f9293fffe360bdd8
<|skeleton|> class MongoAlchemy: def __init__(self): """Initialize variables for the MongoDB database connection""" <|body_0|> def init_app(self, app: Flask=None) -> None: """This function will get config values to set configurations for connection :param app: Instance of the Flask App...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MongoAlchemy: def __init__(self): """Initialize variables for the MongoDB database connection""" self.database_uri = None self.config = dict() self.max_pool = 100 self.min_pool = 0 self.max_idle_time = None self.connection_timeout = 10000 self.he...
the_stack_v2_python_sparse
app/db.py
amanjaiswalofficial/infinity-reads-blog
train
0
e06fb8c1064aa1dcfcf8cef4a7d54ac17f5c084e
[ "self.capacity = capacity\nself.size = 0\nself.cache = dict()\nself.cachelist = DoubleList()", "if key not in self.cache:\n return -1\nnode = self.cache[key]\nself.cachelist.delete(node)\nself.cachelist.append(node)\nreturn node.val", "if key in self.cache:\n node = self.cache[key]\n node.val = value\n...
<|body_start_0|> self.capacity = capacity self.size = 0 self.cache = dict() self.cachelist = DoubleList() <|end_body_0|> <|body_start_1|> if key not in self.cache: return -1 node = self.cache[key] self.cachelist.delete(node) self.cachelist.app...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus_train_067272
2,925
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: None", "name": "pu...
3
stack_v2_sparse_classes_30k_train_006829
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None <|sk...
837957ea22aa07ce28a6c23ea0419bd2011e1f88
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.capacity = capacity self.size = 0 self.cache = dict() self.cachelist = DoubleList() def get(self, key): """:type key: int :rtype: int""" if key not in self.cache: ret...
the_stack_v2_python_sparse
Tencent/midum/LRU缓存.py
2226171237/Algorithmpractice
train
0
6c521f53ee011b2eed03b83d1b7031f36ec31102
[ "APIAdminCommon.verifySecurityOfAdminAPICall(appObj, request, tenant)\ncontent_raw = request.get_json()\ncontent = marshal(content_raw, getUserPersonLinkModel(appObj))\nrequiredInPayload(content, ['UserID', 'personGUID'])\nif userID != content['UserID']:\n raise BadRequest('UserID in payload not the same as in U...
<|body_start_0|> APIAdminCommon.verifySecurityOfAdminAPICall(appObj, request, tenant) content_raw = request.get_json() content = marshal(content_raw, getUserPersonLinkModel(appObj)) requiredInPayload(content, ['UserID', 'personGUID']) if userID != content['UserID']: r...
userpersonlinkInfo
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class userpersonlinkInfo: def post(self, tenant, userID, personGUID): """Create userpersonlink""" <|body_0|> def delete(self, tenant, userID, personGUID): """Delete userpersonlink""" <|body_1|> <|end_skeleton|> <|body_start_0|> APIAdminCommon.verifySecuri...
stack_v2_sparse_classes_75kplus_train_067273
35,114
permissive
[ { "docstring": "Create userpersonlink", "name": "post", "signature": "def post(self, tenant, userID, personGUID)" }, { "docstring": "Delete userpersonlink", "name": "delete", "signature": "def delete(self, tenant, userID, personGUID)" } ]
2
stack_v2_sparse_classes_30k_train_025226
Implement the Python class `userpersonlinkInfo` described below. Class description: Implement the userpersonlinkInfo class. Method signatures and docstrings: - def post(self, tenant, userID, personGUID): Create userpersonlink - def delete(self, tenant, userID, personGUID): Delete userpersonlink
Implement the Python class `userpersonlinkInfo` described below. Class description: Implement the userpersonlinkInfo class. Method signatures and docstrings: - def post(self, tenant, userID, personGUID): Create userpersonlink - def delete(self, tenant, userID, personGUID): Delete userpersonlink <|skeleton|> class us...
d3908c46614fb1b638553282cd72ba3634277495
<|skeleton|> class userpersonlinkInfo: def post(self, tenant, userID, personGUID): """Create userpersonlink""" <|body_0|> def delete(self, tenant, userID, personGUID): """Delete userpersonlink""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class userpersonlinkInfo: def post(self, tenant, userID, personGUID): """Create userpersonlink""" APIAdminCommon.verifySecurityOfAdminAPICall(appObj, request, tenant) content_raw = request.get_json() content = marshal(content_raw, getUserPersonLinkModel(appObj)) requiredInPay...
the_stack_v2_python_sparse
services/src/APIadmin_Legacy.py
rmetcalf9/saas_user_management_system
train
1
ea0e3eafbbd443920d6add021877bd4d85b9d0bf
[ "self.exist = False\nif address is not None:\n self.exist = True\n if len(address) == 7:\n if address[0] == 1:\n self.universe, self.address_start, balance = ((address[4], address[5], cut_little_ledstrip), (address[1], address[2], 0))[idx_led < cut_little_ledstrip]\n self.address_...
<|body_start_0|> self.exist = False if address is not None: self.exist = True if len(address) == 7: if address[0] == 1: self.universe, self.address_start, balance = ((address[4], address[5], cut_little_ledstrip), (address[1], address[2], 0))[id...
Represent a led of the cube
Led
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Led: """Represent a led of the cube""" def __init__(self, address, idx_led): """Constructor of led :param address: tuple of led address :param idx_led: led index""" <|body_0|> def show(self, brightness): """Illuminate the led with brightness :param brightness: in...
stack_v2_sparse_classes_75kplus_train_067274
3,537
no_license
[ { "docstring": "Constructor of led :param address: tuple of led address :param idx_led: led index", "name": "__init__", "signature": "def __init__(self, address, idx_led)" }, { "docstring": "Illuminate the led with brightness :param brightness: int between 0 and 15 include :raise exception", ...
2
stack_v2_sparse_classes_30k_train_009173
Implement the Python class `Led` described below. Class description: Represent a led of the cube Method signatures and docstrings: - def __init__(self, address, idx_led): Constructor of led :param address: tuple of led address :param idx_led: led index - def show(self, brightness): Illuminate the led with brightness ...
Implement the Python class `Led` described below. Class description: Represent a led of the cube Method signatures and docstrings: - def __init__(self, address, idx_led): Constructor of led :param address: tuple of led address :param idx_led: led index - def show(self, brightness): Illuminate the led with brightness ...
de1408317d5071b7e0c6b2fea6f281660115d728
<|skeleton|> class Led: """Represent a led of the cube""" def __init__(self, address, idx_led): """Constructor of led :param address: tuple of led address :param idx_led: led index""" <|body_0|> def show(self, brightness): """Illuminate the led with brightness :param brightness: in...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Led: """Represent a led of the cube""" def __init__(self, address, idx_led): """Constructor of led :param address: tuple of led address :param idx_led: led index""" self.exist = False if address is not None: self.exist = True if len(address) == 7: ...
the_stack_v2_python_sparse
api/package/cube/led.py
HE-Arc/Extrusion---web-interface
train
4
5cc2e67d948f786c3302c61c6071119f1bca556d
[ "rmgpy_path = os.path.normpath(os.path.join(get_path(), '..'))\nqm = QMCalculator(software='gaussian', method='pm3', fileStore=os.path.join(rmgpy_path, 'testing', 'qm', 'QMfiles'), scratchDirectory=os.path.join(rmgpy_path, 'testing', 'qm', 'QMscratch'))\nif not os.path.exists(qm.settings.fileStore):\n os.makedir...
<|body_start_0|> rmgpy_path = os.path.normpath(os.path.join(get_path(), '..')) qm = QMCalculator(software='gaussian', method='pm3', fileStore=os.path.join(rmgpy_path, 'testing', 'qm', 'QMfiles'), scratchDirectory=os.path.join(rmgpy_path, 'testing', 'qm', 'QMscratch')) if not os.path.exists(qm.se...
Contains unit tests for the Geometry class.
TestGaussianMolPM3
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestGaussianMolPM3: """Contains unit tests for the Geometry class.""" def setUp(self): """A function run before each unit test in this class.""" <|body_0|> def test_generate_thermo_data(self): """Test that generate_thermo_data() works correctly on gaussian PM3.""...
stack_v2_sparse_classes_75kplus_train_067275
7,452
permissive
[ { "docstring": "A function run before each unit test in this class.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test that generate_thermo_data() works correctly on gaussian PM3.", "name": "test_generate_thermo_data", "signature": "def test_generate_thermo_data(se...
3
null
Implement the Python class `TestGaussianMolPM3` described below. Class description: Contains unit tests for the Geometry class. Method signatures and docstrings: - def setUp(self): A function run before each unit test in this class. - def test_generate_thermo_data(self): Test that generate_thermo_data() works correct...
Implement the Python class `TestGaussianMolPM3` described below. Class description: Contains unit tests for the Geometry class. Method signatures and docstrings: - def setUp(self): A function run before each unit test in this class. - def test_generate_thermo_data(self): Test that generate_thermo_data() works correct...
349a4af759cf8877197772cd7eaca1e51d46eff5
<|skeleton|> class TestGaussianMolPM3: """Contains unit tests for the Geometry class.""" def setUp(self): """A function run before each unit test in this class.""" <|body_0|> def test_generate_thermo_data(self): """Test that generate_thermo_data() works correctly on gaussian PM3.""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestGaussianMolPM3: """Contains unit tests for the Geometry class.""" def setUp(self): """A function run before each unit test in this class.""" rmgpy_path = os.path.normpath(os.path.join(get_path(), '..')) qm = QMCalculator(software='gaussian', method='pm3', fileStore=os.path.joi...
the_stack_v2_python_sparse
rmgpy/qm/gaussianTest.py
CanePan-cc/CanePanWorkshop
train
2
473ea668bd8cd63beafea221b74d1212abdf1525
[ "self._to = dest\nself._from = source\nself._pwd = pwds\nself.status = None", "file_path = os.path.join(self._from, filename)\nfor pwd in self._pwd:\n unr = unrar.UnrarSpoon(file_path, self._to, pwd)\n status = unr.update_loop(callback=proc)\n self.status = status\n if status[unrar.STATUS_OK]:\n ...
<|body_start_0|> self._to = dest self._from = source self._pwd = pwds self.status = None <|end_body_0|> <|body_start_1|> file_path = os.path.join(self._from, filename) for pwd in self._pwd: unr = unrar.UnrarSpoon(file_path, self._to, pwd) status =...
extractor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class extractor: def __init__(self, source, dest, pwds): """Creates and configures an extractor-object""" <|body_0|> def extract(self, filename, proc=None): """Starts extractor-utility and extracts packets.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_067276
845
no_license
[ { "docstring": "Creates and configures an extractor-object", "name": "__init__", "signature": "def __init__(self, source, dest, pwds)" }, { "docstring": "Starts extractor-utility and extracts packets.", "name": "extract", "signature": "def extract(self, filename, proc=None)" } ]
2
stack_v2_sparse_classes_30k_train_008469
Implement the Python class `extractor` described below. Class description: Implement the extractor class. Method signatures and docstrings: - def __init__(self, source, dest, pwds): Creates and configures an extractor-object - def extract(self, filename, proc=None): Starts extractor-utility and extracts packets.
Implement the Python class `extractor` described below. Class description: Implement the extractor class. Method signatures and docstrings: - def __init__(self, source, dest, pwds): Creates and configures an extractor-object - def extract(self, filename, proc=None): Starts extractor-utility and extracts packets. <|s...
353ab0f9a651233ad1cbc1c463dd052fa28dc35d
<|skeleton|> class extractor: def __init__(self, source, dest, pwds): """Creates and configures an extractor-object""" <|body_0|> def extract(self, filename, proc=None): """Starts extractor-utility and extracts packets.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class extractor: def __init__(self, source, dest, pwds): """Creates and configures an extractor-object""" self._to = dest self._from = source self._pwd = pwds self.status = None def extract(self, filename, proc=None): """Starts extractor-utility and extracts pack...
the_stack_v2_python_sparse
src/pfextractor.py
boon-code/pfrinc4
train
0
e43fadc6fbd7ebdd13c520e8c7f46c0a1cacb0e6
[ "self.opt = opt\nself.dataset = None\nself.dataset_loader = None", "if self.opt.dataset in ['imagenet', 'folder', 'lfw']:\n self.dataset = dset.ImageFolder(root=self.opt.dataroot, transform=transforms.Compose([transforms.Scale(self.opt.imageSize), transforms.CenterCrop(self.opt.imageSize), transforms.ToTensor(...
<|body_start_0|> self.opt = opt self.dataset = None self.dataset_loader = None <|end_body_0|> <|body_start_1|> if self.opt.dataset in ['imagenet', 'folder', 'lfw']: self.dataset = dset.ImageFolder(root=self.opt.dataroot, transform=transforms.Compose([transforms.Scale(self.op...
Load a dataset.
Dataset_load
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dataset_load: """Load a dataset.""" def __init__(self, opt): """Constructor.""" <|body_0|> def initialize_dataset(self): """Initialize.""" <|body_1|> def initialize_dataset_loader(self, batchSize=None): """Create the datset loader.""" ...
stack_v2_sparse_classes_75kplus_train_067277
3,119
permissive
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self, opt)" }, { "docstring": "Initialize.", "name": "initialize_dataset", "signature": "def initialize_dataset(self)" }, { "docstring": "Create the datset loader.", "name": "initialize_dataset_load...
5
stack_v2_sparse_classes_30k_train_000792
Implement the Python class `Dataset_load` described below. Class description: Load a dataset. Method signatures and docstrings: - def __init__(self, opt): Constructor. - def initialize_dataset(self): Initialize. - def initialize_dataset_loader(self, batchSize=None): Create the datset loader. - def get_dataset(self): ...
Implement the Python class `Dataset_load` described below. Class description: Load a dataset. Method signatures and docstrings: - def __init__(self, opt): Constructor. - def initialize_dataset(self): Initialize. - def initialize_dataset_loader(self, batchSize=None): Create the datset loader. - def get_dataset(self): ...
e1e4a8d9a2ab51c2108a4d167bc37fab101f0c2c
<|skeleton|> class Dataset_load: """Load a dataset.""" def __init__(self, opt): """Constructor.""" <|body_0|> def initialize_dataset(self): """Initialize.""" <|body_1|> def initialize_dataset_loader(self, batchSize=None): """Create the datset loader.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Dataset_load: """Load a dataset.""" def __init__(self, opt): """Constructor.""" self.opt = opt self.dataset = None self.dataset_loader = None def initialize_dataset(self): """Initialize.""" if self.opt.dataset in ['imagenet', 'folder', 'lfw']: ...
the_stack_v2_python_sparse
diffrend/torch/GAN/datasets.py
sainatarajan/pix2shape
train
0
bcf1b9c13fa954c345b9ae9778b1cea8e402d049
[ "super(KleinConstraint, self).__init__()\nself.norm = Norm(axis=-1)\nself.min_norm = min_norm\nself.maxnorm = 1 - 0.004\nself.shape = Shape()\nself.reshape = Reshape()", "last_dim_val = self.shape(x)[-1]\nnorm = self.reshape(self.norm(x), (-1, 1))\nmaxnorm = self.maxnorm\ncond = norm > maxnorm\nx_reshape = self.r...
<|body_start_0|> super(KleinConstraint, self).__init__() self.norm = Norm(axis=-1) self.min_norm = min_norm self.maxnorm = 1 - 0.004 self.shape = Shape() self.reshape = Reshape() <|end_body_0|> <|body_start_1|> last_dim_val = self.shape(x)[-1] norm = self...
klein constraint class
KleinConstraint
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KleinConstraint: """klein constraint class""" def __init__(self, min_norm): """init fun""" <|body_0|> def construct(self, x): """class construction""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(KleinConstraint, self).__init__() s...
stack_v2_sparse_classes_75kplus_train_067278
8,596
permissive
[ { "docstring": "init fun", "name": "__init__", "signature": "def __init__(self, min_norm)" }, { "docstring": "class construction", "name": "construct", "signature": "def construct(self, x)" } ]
2
stack_v2_sparse_classes_30k_test_000175
Implement the Python class `KleinConstraint` described below. Class description: klein constraint class Method signatures and docstrings: - def __init__(self, min_norm): init fun - def construct(self, x): class construction
Implement the Python class `KleinConstraint` described below. Class description: klein constraint class Method signatures and docstrings: - def __init__(self, min_norm): init fun - def construct(self, x): class construction <|skeleton|> class KleinConstraint: """klein constraint class""" def __init__(self, ...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class KleinConstraint: """klein constraint class""" def __init__(self, min_norm): """init fun""" <|body_0|> def construct(self, x): """class construction""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KleinConstraint: """klein constraint class""" def __init__(self, min_norm): """init fun""" super(KleinConstraint, self).__init__() self.norm = Norm(axis=-1) self.min_norm = min_norm self.maxnorm = 1 - 0.004 self.shape = Shape() self.reshape = Reshap...
the_stack_v2_python_sparse
research/nlp/hypertext/src/poincare.py
mindspore-ai/models
train
301
e27f524b287f45bdacf68e26fc8e63fceee91e06
[ "n = len(init_val)\nself.segfunc = segfunc\nself.ide_ele = ide_ele\nself.num = 1 << (n - 1).bit_length()\nself.tree = [ide_ele] * 2 * self.num\nfor i in range(n):\n self.tree[self.num + i] = init_val[i]\nfor i in range(self.num - 1, 0, -1):\n self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])...
<|body_start_0|> n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): ...
init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
SegTree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SegTree: """init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)""" def __init__(self, init_val, segfunc, ide_ele): """init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)"...
stack_v2_sparse_classes_75kplus_train_067279
2,945
no_license
[ { "docstring": "init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)", "name": "__init__", "signature": "def __init__(self, init_val, segfunc, ide_ele)" }, { "docstring": "k番目の値をxに更新 k: index(0-index) x: update value", "name": "update", "signatur...
3
stack_v2_sparse_classes_30k_train_024057
Implement the Python class `SegTree` described below. Class description: init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN) Method signatures and docstrings: - def __init__(self, init_val, segfunc, ide_ele): init_val: 配列の初期値 segfunc: 区間にしたい操作 ide...
Implement the Python class `SegTree` described below. Class description: init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN) Method signatures and docstrings: - def __init__(self, init_val, segfunc, ide_ele): init_val: 配列の初期値 segfunc: 区間にしたい操作 ide...
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
<|skeleton|> class SegTree: """init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)""" def __init__(self, init_val, segfunc, ide_ele): """init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)"...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SegTree: """init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)""" def __init__(self, init_val, segfunc, ide_ele): """init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)""" n ...
the_stack_v2_python_sparse
Python_codes/p03061/s654525017.py
Aasthaengg/IBMdataset
train
0
53c6fd4999622528c9b791d5a22851709f29d7c6
[ "if not root:\n return True\nreturn self.isValidBSTUtil(root)[0]", "if not root.left and (not root.right):\n return (True, root.val, root.val)\nif root.left:\n isLeft, leftMin, leftMax = self.isValidBSTUtil(root.left)\nelse:\n isLeft, leftMin, leftMax = (True, float('inf'), float('-inf'))\nif root.rig...
<|body_start_0|> if not root: return True return self.isValidBSTUtil(root)[0] <|end_body_0|> <|body_start_1|> if not root.left and (not root.right): return (True, root.val, root.val) if root.left: isLeft, leftMin, leftMax = self.isValidBSTUtil(root.le...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isValidBST(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isValidBSTUtil(self, root): """:type root: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root: return True ...
stack_v2_sparse_classes_75kplus_train_067280
1,439
no_license
[ { "docstring": ":type root: TreeNode :rtype: bool", "name": "isValidBST", "signature": "def isValidBST(self, root)" }, { "docstring": ":type root: TreeNode :rtype: bool", "name": "isValidBSTUtil", "signature": "def isValidBSTUtil(self, root)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isValidBST(self, root): :type root: TreeNode :rtype: bool - def isValidBSTUtil(self, root): :type root: TreeNode :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isValidBST(self, root): :type root: TreeNode :rtype: bool - def isValidBSTUtil(self, root): :type root: TreeNode :rtype: bool <|skeleton|> class Solution: def isValidBS...
962803824b4173d553cb76940750dc249927b972
<|skeleton|> class Solution: def isValidBST(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isValidBSTUtil(self, root): """:type root: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isValidBST(self, root): """:type root: TreeNode :rtype: bool""" if not root: return True return self.isValidBSTUtil(root)[0] def isValidBSTUtil(self, root): """:type root: TreeNode :rtype: bool""" if not root.left and (not root.right): ...
the_stack_v2_python_sparse
ValidateBST.py
divyanshk/algorithms-and-data-structures
train
0
4ba6cc6f9c1795b0f091aef3592a11398adc4085
[ "connection = sqlite3.connect(Constants.DATABASE)\nconnection.row_factory = sqlite3.Row\ncursor = connection.cursor()\nquery = 'SELECT * FROM ' + table + ' WHERE ' + attribute + ' = ' + str(value)\ncursor.execute(query)\nreturn cursor.fetchone()", "connection = sqlite3.connect(Constants.DATABASE)\nconnection.row_...
<|body_start_0|> connection = sqlite3.connect(Constants.DATABASE) connection.row_factory = sqlite3.Row cursor = connection.cursor() query = 'SELECT * FROM ' + table + ' WHERE ' + attribute + ' = ' + str(value) cursor.execute(query) return cursor.fetchone() <|end_body_0|> ...
DatabaseHelper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DatabaseHelper: def dbSelectRowByID(table, attribute, value): """Generic method to fetch contents from the local database.""" <|body_0|> def dbUpdate(table, key_name, key_id, attribute, value): """Generic mathod to update data in table with the key_name matches key_i...
stack_v2_sparse_classes_75kplus_train_067281
2,600
no_license
[ { "docstring": "Generic method to fetch contents from the local database.", "name": "dbSelectRowByID", "signature": "def dbSelectRowByID(table, attribute, value)" }, { "docstring": "Generic mathod to update data in table with the key_name matches key_id", "name": "dbUpdate", "signature":...
4
stack_v2_sparse_classes_30k_train_050002
Implement the Python class `DatabaseHelper` described below. Class description: Implement the DatabaseHelper class. Method signatures and docstrings: - def dbSelectRowByID(table, attribute, value): Generic method to fetch contents from the local database. - def dbUpdate(table, key_name, key_id, attribute, value): Gen...
Implement the Python class `DatabaseHelper` described below. Class description: Implement the DatabaseHelper class. Method signatures and docstrings: - def dbSelectRowByID(table, attribute, value): Generic method to fetch contents from the local database. - def dbUpdate(table, key_name, key_id, attribute, value): Gen...
8273b84ff8ee0fdb9e4779fe5b605a44636f27a2
<|skeleton|> class DatabaseHelper: def dbSelectRowByID(table, attribute, value): """Generic method to fetch contents from the local database.""" <|body_0|> def dbUpdate(table, key_name, key_id, attribute, value): """Generic mathod to update data in table with the key_name matches key_i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DatabaseHelper: def dbSelectRowByID(table, attribute, value): """Generic method to fetch contents from the local database.""" connection = sqlite3.connect(Constants.DATABASE) connection.row_factory = sqlite3.Row cursor = connection.cursor() query = 'SELECT * FROM ' + ta...
the_stack_v2_python_sparse
branches/hunvilbranch/src/common/DatabaseHelper.py
Panda3D-public-projects-archive/sfsu-multiplayer-game-dev-2011
train
0
2628fa0c9f34505426440711d9d743c2dc218b38
[ "m = 300\nctx.save_for_backward(k)\nk = k.double()\nanswer = (m / 2 - 1) * torch.log(k) - torch.log(sc.ive(m / 2 - 1, k)).cuda() - k - m / 2 * np.log(2 * np.pi)\nanswer = answer.float()\nreturn answer", "k, = ctx.saved_tensors\nm = 300\nk = k.double()\nx = -(scipy.special.ive(m / 2, k) / scipy.special.ive(m / 2 -...
<|body_start_0|> m = 300 ctx.save_for_backward(k) k = k.double() answer = (m / 2 - 1) * torch.log(k) - torch.log(sc.ive(m / 2 - 1, k)).cuda() - k - m / 2 * np.log(2 * np.pi) answer = answer.float() return answer <|end_body_0|> <|body_start_1|> k, = ctx.saved_tens...
The exponentially scaled modified Bessel function of the first kind
Logcmk
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Logcmk: """The exponentially scaled modified Bessel function of the first kind""" def forward(ctx, k): """In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward...
stack_v2_sparse_classes_75kplus_train_067282
2,692
permissive
[ { "docstring": "In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation. You can cache arbitrary objects for use in the backward pass using the ctx.save_for_backward method.", ...
2
stack_v2_sparse_classes_30k_train_029156
Implement the Python class `Logcmk` described below. Class description: The exponentially scaled modified Bessel function of the first kind Method signatures and docstrings: - def forward(ctx, k): In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context ...
Implement the Python class `Logcmk` described below. Class description: The exponentially scaled modified Bessel function of the first kind Method signatures and docstrings: - def forward(ctx, k): In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context ...
99cba1030ed8c012a453bc7715830fc99fb980dc
<|skeleton|> class Logcmk: """The exponentially scaled modified Bessel function of the first kind""" def forward(ctx, k): """In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Logcmk: """The exponentially scaled modified Bessel function of the first kind""" def forward(ctx, k): """In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation....
the_stack_v2_python_sparse
models/loss/old_vonmises.py
jamesoneill12/LayerFusion
train
2
8fed59678ddeabe8b7060bdccc4745817cd442ab
[ "self.expression_data = expression_data\nself.calculator = calculator\nself.rm_outliers = rm_outliers", "data = None\nif isinstance(measurments, dict):\n data = measurments\n measurments = list(measurments.values())\nmeasurments = np.array(measurments)\nupper_quartile = np.percentile(measurments, 75)\nlower...
<|body_start_0|> self.expression_data = expression_data self.calculator = calculator self.rm_outliers = rm_outliers <|end_body_0|> <|body_start_1|> data = None if isinstance(measurments, dict): data = measurments measurments = list(measurments.values()) ...
Base class for navigation of similarity calculation between specified genes.
SimilarityCalculatorNavigator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimilarityCalculatorNavigator: """Base class for navigation of similarity calculation between specified genes.""" def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, rm_outliers: bool=True): """:param expression_data: Data for all genes :param calcul...
stack_v2_sparse_classes_75kplus_train_067283
43,977
no_license
[ { "docstring": ":param expression_data: Data for all genes :param calculator: SimilarityCalculator used in all calculations :param rm_outliers: should outliers be removed before similarity statistics calculation", "name": "__init__", "signature": "def __init__(self, expression_data: GeneExpression, calc...
2
stack_v2_sparse_classes_30k_train_032550
Implement the Python class `SimilarityCalculatorNavigator` described below. Class description: Base class for navigation of similarity calculation between specified genes. Method signatures and docstrings: - def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, rm_outliers: bool=True):...
Implement the Python class `SimilarityCalculatorNavigator` described below. Class description: Base class for navigation of similarity calculation between specified genes. Method signatures and docstrings: - def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, rm_outliers: bool=True):...
6d11df5e8ca37e53e048d261ac287f859ba6e9b9
<|skeleton|> class SimilarityCalculatorNavigator: """Base class for navigation of similarity calculation between specified genes.""" def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, rm_outliers: bool=True): """:param expression_data: Data for all genes :param calcul...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SimilarityCalculatorNavigator: """Base class for navigation of similarity calculation between specified genes.""" def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, rm_outliers: bool=True): """:param expression_data: Data for all genes :param calculator: Similar...
the_stack_v2_python_sparse
correlation_enrichment/library_correlation_enrichment.py
biolab/baylor-dicty
train
0
4b1bb7bb46dc83b5312d2116b49f0b1aacea8a9a
[ "dist_utils.validate_callbacks(input_callbacks=callbacks, optimizer=model.optimizer)\ndist_utils.validate_inputs(x, y)\nbatch_size, steps_per_epoch = dist_utils.process_batch_and_step_size(model._distribution_strategy, x, batch_size, steps_per_epoch, ModeKeys.TRAIN, validation_split=validation_split)\nbatch_size = ...
<|body_start_0|> dist_utils.validate_callbacks(input_callbacks=callbacks, optimizer=model.optimizer) dist_utils.validate_inputs(x, y) batch_size, steps_per_epoch = dist_utils.process_batch_and_step_size(model._distribution_strategy, x, batch_size, steps_per_epoch, ModeKeys.TRAIN, validation_spli...
Training loop for distribution strategy with single worker.
DistributionSingleWorkerTrainingLoop
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DistributionSingleWorkerTrainingLoop: """Training loop for distribution strategy with single worker.""" def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, ...
stack_v2_sparse_classes_75kplus_train_067284
29,780
permissive
[ { "docstring": "Fit loop for Distribution Strategies.", "name": "fit", "signature": "def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoc...
3
stack_v2_sparse_classes_30k_train_007087
Implement the Python class `DistributionSingleWorkerTrainingLoop` described below. Class description: Training loop for distribution strategy with single worker. Method signatures and docstrings: - def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validat...
Implement the Python class `DistributionSingleWorkerTrainingLoop` described below. Class description: Training loop for distribution strategy with single worker. Method signatures and docstrings: - def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validat...
a7f3934a67900720af3d3b15389551483bee50b8
<|skeleton|> class DistributionSingleWorkerTrainingLoop: """Training loop for distribution strategy with single worker.""" def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DistributionSingleWorkerTrainingLoop: """Training loop for distribution strategy with single worker.""" def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch...
the_stack_v2_python_sparse
tensorflow/python/keras/engine/training_distributed_v1.py
tensorflow/tensorflow
train
208,740
a34e7410e522eb674682abd5dd5eebc8cf6d3306
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EdiscoveryEstimateOperation()", "from .case_operation import CaseOperation\nfrom .ediscovery_search import EdiscoverySearch\nfrom .case_operation import CaseOperation\nfrom .ediscovery_search import EdiscoverySearch\nfields: Dict[str, ...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return EdiscoveryEstimateOperation() <|end_body_0|> <|body_start_1|> from .case_operation import CaseOperation from .ediscovery_search import EdiscoverySearch from .case_operation impor...
EdiscoveryEstimateOperation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EdiscoveryEstimateOperation: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoveryEstimateOperation: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a...
stack_v2_sparse_classes_75kplus_train_067285
3,923
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: EdiscoveryEstimateOperation", "name": "create_from_discriminator_value", "signature": "def create_from_discr...
3
stack_v2_sparse_classes_30k_train_026976
Implement the Python class `EdiscoveryEstimateOperation` described below. Class description: Implement the EdiscoveryEstimateOperation class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoveryEstimateOperation: Creates a new instance of the appr...
Implement the Python class `EdiscoveryEstimateOperation` described below. Class description: Implement the EdiscoveryEstimateOperation class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoveryEstimateOperation: Creates a new instance of the appr...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class EdiscoveryEstimateOperation: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoveryEstimateOperation: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EdiscoveryEstimateOperation: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoveryEstimateOperation: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ...
the_stack_v2_python_sparse
msgraph/generated/models/security/ediscovery_estimate_operation.py
microsoftgraph/msgraph-sdk-python
train
135
5c8681a6edfe120479a4d663235935e2e5882fa1
[ "super().__init__()\nBlock = self.name_to_block(block_name)\nN = self.num_blocks_per_layer(Block, depth)\nself.in_channels = 3\nself.channels = 16\nself.conv1 = nn.Conv2d(self.in_channels, self.channels, kernel_size=3, padding=1, bias=False)\nself.in_channels = 16\nself.layer1 = self.make_layer(Block, self.channels...
<|body_start_0|> super().__init__() Block = self.name_to_block(block_name) N = self.num_blocks_per_layer(Block, depth) self.in_channels = 3 self.channels = 16 self.conv1 = nn.Conv2d(self.in_channels, self.channels, kernel_size=3, padding=1, bias=False) self.in_cha...
pre-activated ResNet.
PreResNet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PreResNet: """pre-activated ResNet.""" def __init__(self, depth, num_classes=1000, block_name='BasicBlock', **kwargs): """CTOR for the model.""" <|body_0|> def make_layer(self, Block, channels, num_blocks, stride=1, **kwargs): """create a layer of blocks. NOTE: s...
stack_v2_sparse_classes_75kplus_train_067286
6,340
permissive
[ { "docstring": "CTOR for the model.", "name": "__init__", "signature": "def __init__(self, depth, num_classes=1000, block_name='BasicBlock', **kwargs)" }, { "docstring": "create a layer of blocks. NOTE: self.in_channels will be updated NOTE: channels is the unexpended number of channels", "n...
5
stack_v2_sparse_classes_30k_train_031752
Implement the Python class `PreResNet` described below. Class description: pre-activated ResNet. Method signatures and docstrings: - def __init__(self, depth, num_classes=1000, block_name='BasicBlock', **kwargs): CTOR for the model. - def make_layer(self, Block, channels, num_blocks, stride=1, **kwargs): create a lay...
Implement the Python class `PreResNet` described below. Class description: pre-activated ResNet. Method signatures and docstrings: - def __init__(self, depth, num_classes=1000, block_name='BasicBlock', **kwargs): CTOR for the model. - def make_layer(self, Block, channels, num_blocks, stride=1, **kwargs): create a lay...
f81c417d3754102c902bd153809130e12607bd7d
<|skeleton|> class PreResNet: """pre-activated ResNet.""" def __init__(self, depth, num_classes=1000, block_name='BasicBlock', **kwargs): """CTOR for the model.""" <|body_0|> def make_layer(self, Block, channels, num_blocks, stride=1, **kwargs): """create a layer of blocks. NOTE: s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PreResNet: """pre-activated ResNet.""" def __init__(self, depth, num_classes=1000, block_name='BasicBlock', **kwargs): """CTOR for the model.""" super().__init__() Block = self.name_to_block(block_name) N = self.num_blocks_per_layer(Block, depth) self.in_channels =...
the_stack_v2_python_sparse
gumi/models/preresnet.py
kumasento/gconv-prune
train
10
1d4e7c826e5fce9e495448509ddbb2c71ae57ec7
[ "if embedding_dict is None:\n embedding_dict = get_elemental_embeddings()\nself.embedding_dict = embedding_dict", "features = []\nfor atom in atoms:\n emb = 0\n for k, v in atom.items():\n emb += np.array(self.embedding_dict[k]) * v\n features.append(emb)\nreturn np.array(features).reshape((len...
<|body_start_0|> if embedding_dict is None: embedding_dict = get_elemental_embeddings() self.embedding_dict = embedding_dict <|end_body_0|> <|body_start_1|> features = [] for atom in atoms: emb = 0 for k, v in atom.items(): emb += np.a...
Fixed Atom embedding map, used with CrystalGraphDisordered
_AtomEmbeddingMap
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _AtomEmbeddingMap: """Fixed Atom embedding map, used with CrystalGraphDisordered""" def __init__(self, embedding_dict: dict | None=None): """Args: embedding_dict (dict): element to element vector dictionary""" <|body_0|> def convert(self, atoms: list) -> np.ndarray: ...
stack_v2_sparse_classes_75kplus_train_067287
5,715
permissive
[ { "docstring": "Args: embedding_dict (dict): element to element vector dictionary", "name": "__init__", "signature": "def __init__(self, embedding_dict: dict | None=None)" }, { "docstring": "Convert atom {symbol: fraction} list to numeric features", "name": "convert", "signature": "def c...
2
null
Implement the Python class `_AtomEmbeddingMap` described below. Class description: Fixed Atom embedding map, used with CrystalGraphDisordered Method signatures and docstrings: - def __init__(self, embedding_dict: dict | None=None): Args: embedding_dict (dict): element to element vector dictionary - def convert(self, ...
Implement the Python class `_AtomEmbeddingMap` described below. Class description: Fixed Atom embedding map, used with CrystalGraphDisordered Method signatures and docstrings: - def __init__(self, embedding_dict: dict | None=None): Args: embedding_dict (dict): element to element vector dictionary - def convert(self, ...
f3705760266f24b62c4810dd4abacfc25f4f64ae
<|skeleton|> class _AtomEmbeddingMap: """Fixed Atom embedding map, used with CrystalGraphDisordered""" def __init__(self, embedding_dict: dict | None=None): """Args: embedding_dict (dict): element to element vector dictionary""" <|body_0|> def convert(self, atoms: list) -> np.ndarray: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _AtomEmbeddingMap: """Fixed Atom embedding map, used with CrystalGraphDisordered""" def __init__(self, embedding_dict: dict | None=None): """Args: embedding_dict (dict): element to element vector dictionary""" if embedding_dict is None: embedding_dict = get_elemental_embedding...
the_stack_v2_python_sparse
megnet/data/crystal.py
materialsvirtuallab/megnet
train
471
95be8e650123f600fa47ac72721f7c89e0f709f3
[ "self.game_screen = Background()\nself.check_mouse = True\nself.check_die = False\nself.check_create = True\npets = create_pets(self.game_screen, CAT_IMAGES.CAT, FOX_IMAGES.FOX, STICH_IMAGES.STICH)\nself.newpet = choose_pet(pets)\nself.check_not_die = True\nself.check_moving = 'none'\nself.check_play = False\nself....
<|body_start_0|> self.game_screen = Background() self.check_mouse = True self.check_die = False self.check_create = True pets = create_pets(self.game_screen, CAT_IMAGES.CAT, FOX_IMAGES.FOX, STICH_IMAGES.STICH) self.newpet = choose_pet(pets) self.check_not_die = Tr...
Game
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Game: def __init__(self): """Creating a screen where user can choose a pet""" <|body_0|> def run(self): """The main game loop""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.game_screen = Background() self.check_mouse = True sel...
stack_v2_sparse_classes_75kplus_train_067288
2,153
no_license
[ { "docstring": "Creating a screen where user can choose a pet", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "The main game loop", "name": "run", "signature": "def run(self)" } ]
2
null
Implement the Python class `Game` described below. Class description: Implement the Game class. Method signatures and docstrings: - def __init__(self): Creating a screen where user can choose a pet - def run(self): The main game loop
Implement the Python class `Game` described below. Class description: Implement the Game class. Method signatures and docstrings: - def __init__(self): Creating a screen where user can choose a pet - def run(self): The main game loop <|skeleton|> class Game: def __init__(self): """Creating a screen wher...
106586ca5a2bd41a23d3f9de614263796882955f
<|skeleton|> class Game: def __init__(self): """Creating a screen where user can choose a pet""" <|body_0|> def run(self): """The main game loop""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Game: def __init__(self): """Creating a screen where user can choose a pet""" self.game_screen = Background() self.check_mouse = True self.check_die = False self.check_create = True pets = create_pets(self.game_screen, CAT_IMAGES.CAT, FOX_IMAGES.FOX, STICH_IMAGE...
the_stack_v2_python_sparse
Tamagochi/game.py
frewerins/all_projects
train
0
243f3ea2c07fa52e090941717b5923167bde9de1
[ "try:\n html2pdf_data = kwargs.get('html2pdf_data')\n html2pdf_data_type = kwargs.get('html2pdf_data_type')\n html2pdf_stylesheet = self.get_select_param(kwargs.get('html2pdf_stylesheet'))\n log = logging.getLogger(__name__)\n log.info('html2pdf_data: %s', html2pdf_data)\n log.info('html2pdf_data_...
<|body_start_0|> try: html2pdf_data = kwargs.get('html2pdf_data') html2pdf_data_type = kwargs.get('html2pdf_data_type') html2pdf_stylesheet = self.get_select_param(kwargs.get('html2pdf_stylesheet')) log = logging.getLogger(__name__) log.info('html2pdf_...
Component that implements Resilient function 'utilities_html2pdf' This function takes html, either complete "<html> ... </html>" or a fragment "<table> ... </table>" and converts it to a pdf image. That image is converted to base64 and returned.
FunctionComponent
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FunctionComponent: """Component that implements Resilient function 'utilities_html2pdf' This function takes html, either complete "<html> ... </html>" or a fragment "<table> ... </table>" and converts it to a pdf image. That image is converted to base64 and returned.""" def _fn_html2pdf_func...
stack_v2_sparse_classes_75kplus_train_067289
3,058
permissive
[ { "docstring": "Function: function accessible from Resilient to render html to binary pdf format", "name": "_fn_html2pdf_function", "signature": "def _fn_html2pdf_function(self, event, *args, **kwargs)" }, { "docstring": "convert html data to pdf :param input_data: url to read html or html alrea...
2
stack_v2_sparse_classes_30k_train_030016
Implement the Python class `FunctionComponent` described below. Class description: Component that implements Resilient function 'utilities_html2pdf' This function takes html, either complete "<html> ... </html>" or a fragment "<table> ... </table>" and converts it to a pdf image. That image is converted to base64 and ...
Implement the Python class `FunctionComponent` described below. Class description: Component that implements Resilient function 'utilities_html2pdf' This function takes html, either complete "<html> ... </html>" or a fragment "<table> ... </table>" and converts it to a pdf image. That image is converted to base64 and ...
6878c78b94eeca407998a41ce8db2cc00f2b6758
<|skeleton|> class FunctionComponent: """Component that implements Resilient function 'utilities_html2pdf' This function takes html, either complete "<html> ... </html>" or a fragment "<table> ... </table>" and converts it to a pdf image. That image is converted to base64 and returned.""" def _fn_html2pdf_func...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FunctionComponent: """Component that implements Resilient function 'utilities_html2pdf' This function takes html, either complete "<html> ... </html>" or a fragment "<table> ... </table>" and converts it to a pdf image. That image is converted to base64 and returned.""" def _fn_html2pdf_function(self, ev...
the_stack_v2_python_sparse
fn_html2pdf/fn_html2pdf/components/html2pdf.py
ibmresilient/resilient-community-apps
train
81
7e2c2b446199a82141470cc9a5b4c74c3b0e2ae2
[ "keys = {key: value for key, value in cls.__dict__.items() if not isinstance(value, classmethod) and (not isinstance(value, staticmethod)) and (not callable(value)) and (not key.startswith('__'))}\nrequired = [v for k, v in keys.items() if not k.endswith('_')]\noptional = [v for k, v in keys.items() if k.endswith('...
<|body_start_0|> keys = {key: value for key, value in cls.__dict__.items() if not isinstance(value, classmethod) and (not isinstance(value, staticmethod)) and (not callable(value)) and (not key.startswith('__'))} required = [v for k, v in keys.items() if not k.endswith('_')] optional = [v for k,...
Class to validate dictionary configurations.
ConfigKeys
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigKeys: """Class to validate dictionary configurations.""" def get_keys(cls) -> Tuple[List[str], List[str]]: """Gets all the required and optional config keys for this class. Returns: A tuple (required, optional) which are lists of the required/optional keys for this class.""" ...
stack_v2_sparse_classes_75kplus_train_067290
3,020
permissive
[ { "docstring": "Gets all the required and optional config keys for this class. Returns: A tuple (required, optional) which are lists of the required/optional keys for this class.", "name": "get_keys", "signature": "def get_keys(cls) -> Tuple[List[str], List[str]]" }, { "docstring": "Checks wheth...
2
stack_v2_sparse_classes_30k_train_003105
Implement the Python class `ConfigKeys` described below. Class description: Class to validate dictionary configurations. Method signatures and docstrings: - def get_keys(cls) -> Tuple[List[str], List[str]]: Gets all the required and optional config keys for this class. Returns: A tuple (required, optional) which are ...
Implement the Python class `ConfigKeys` described below. Class description: Class to validate dictionary configurations. Method signatures and docstrings: - def get_keys(cls) -> Tuple[List[str], List[str]]: Gets all the required and optional config keys for this class. Returns: A tuple (required, optional) which are ...
f1499e9c3fee00fd1d66de14cab66c4472c0085d
<|skeleton|> class ConfigKeys: """Class to validate dictionary configurations.""" def get_keys(cls) -> Tuple[List[str], List[str]]: """Gets all the required and optional config keys for this class. Returns: A tuple (required, optional) which are lists of the required/optional keys for this class.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConfigKeys: """Class to validate dictionary configurations.""" def get_keys(cls) -> Tuple[List[str], List[str]]: """Gets all the required and optional config keys for this class. Returns: A tuple (required, optional) which are lists of the required/optional keys for this class.""" keys = ...
the_stack_v2_python_sparse
src/zenml/config/config_keys.py
stefannica/zenml
train
0
f00796aca417e00edbf8d3541fb9bd657e037183
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn List_()", "from .base_item import BaseItem\nfrom .column_definition import ColumnDefinition\nfrom .content_type import ContentType\nfrom .drive import Drive\nfrom .list_info import ListInfo\nfrom .list_item import ListItem\nfrom .rich_...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return List_() <|end_body_0|> <|body_start_1|> from .base_item import BaseItem from .column_definition import ColumnDefinition from .content_type import ContentType from .drive ...
List_
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class List_: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> List_: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: List_""" ...
stack_v2_sparse_classes_75kplus_train_067291
5,839
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: List_", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value(parse_n...
3
stack_v2_sparse_classes_30k_train_037808
Implement the Python class `List_` described below. Class description: Implement the List_ class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> List_: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p...
Implement the Python class `List_` described below. Class description: Implement the List_ class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> List_: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class List_: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> List_: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: List_""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class List_: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> List_: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: List_""" if not pars...
the_stack_v2_python_sparse
msgraph/generated/models/list_.py
microsoftgraph/msgraph-sdk-python
train
135
1c9e8611fe8d8d15df32d591b35e4be511bdd2cd
[ "import collections\nassert isinstance(e, collections.Hashable), 'input is not hashable'\nself.vals.pop(e, 0)", "import collections\nassert isinstance(e, collections.Hashable), 'input is not hashable'\nreturn e in self.vals.keys()" ]
<|body_start_0|> import collections assert isinstance(e, collections.Hashable), 'input is not hashable' self.vals.pop(e, 0) <|end_body_0|> <|body_start_1|> import collections assert isinstance(e, collections.Hashable), 'input is not hashable' return e in self.vals.keys()...
ASet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ASet: def remove(self, e): """assumes e is hashable removes e from self""" <|body_0|> def is_in(self, e): """assumes e is hashable returns True if e has been inserted in self and not subsequently removed, and False otherwise.""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_75kplus_train_067292
3,068
no_license
[ { "docstring": "assumes e is hashable removes e from self", "name": "remove", "signature": "def remove(self, e)" }, { "docstring": "assumes e is hashable returns True if e has been inserted in self and not subsequently removed, and False otherwise.", "name": "is_in", "signature": "def is...
2
stack_v2_sparse_classes_30k_train_054380
Implement the Python class `ASet` described below. Class description: Implement the ASet class. Method signatures and docstrings: - def remove(self, e): assumes e is hashable removes e from self - def is_in(self, e): assumes e is hashable returns True if e has been inserted in self and not subsequently removed, and F...
Implement the Python class `ASet` described below. Class description: Implement the ASet class. Method signatures and docstrings: - def remove(self, e): assumes e is hashable removes e from self - def is_in(self, e): assumes e is hashable returns True if e has been inserted in self and not subsequently removed, and F...
b60eaed255598118319c1efe6da9a78cbcf58f25
<|skeleton|> class ASet: def remove(self, e): """assumes e is hashable removes e from self""" <|body_0|> def is_in(self, e): """assumes e is hashable returns True if e has been inserted in self and not subsequently removed, and False otherwise.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ASet: def remove(self, e): """assumes e is hashable removes e from self""" import collections assert isinstance(e, collections.Hashable), 'input is not hashable' self.vals.pop(e, 0) def is_in(self, e): """assumes e is hashable returns True if e has been inserted in...
the_stack_v2_python_sparse
Final/problem6.py
aanzolaavila/MITx-6.00.1x
train
0
35cd4b3cf420be17e04d516e265e77d9d72c28e5
[ "self.switch_profiles = switch_profiles\nself.switches = switches\nself.stacks = stacks\nself.igmp_snooping_enabled = igmp_snooping_enabled\nself.flood_unknown_multicast_traffic_enabled = flood_unknown_multicast_traffic_enabled", "if dictionary is None:\n return None\nigmp_snooping_enabled = dictionary.get('ig...
<|body_start_0|> self.switch_profiles = switch_profiles self.switches = switches self.stacks = stacks self.igmp_snooping_enabled = igmp_snooping_enabled self.flood_unknown_multicast_traffic_enabled = flood_unknown_multicast_traffic_enabled <|end_body_0|> <|body_start_1|> ...
Implementation of the 'Override1' model. TODO: type model description here. Attributes: switch_profiles (list of string): List of switch profiles ids for template network switches (list of string): List of switch serials for non-template network stacks (list of string): List of switch stack ids for non-template network...
Override1Model
[ "MIT", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Override1Model: """Implementation of the 'Override1' model. TODO: type model description here. Attributes: switch_profiles (list of string): List of switch profiles ids for template network switches (list of string): List of switch serials for non-template network stacks (list of string): List of...
stack_v2_sparse_classes_75kplus_train_067293
3,029
permissive
[ { "docstring": "Constructor for the Override1Model class", "name": "__init__", "signature": "def __init__(self, igmp_snooping_enabled=None, flood_unknown_multicast_traffic_enabled=None, switch_profiles=None, switches=None, stacks=None)" }, { "docstring": "Creates an instance of this model from a...
2
stack_v2_sparse_classes_30k_train_005191
Implement the Python class `Override1Model` described below. Class description: Implementation of the 'Override1' model. TODO: type model description here. Attributes: switch_profiles (list of string): List of switch profiles ids for template network switches (list of string): List of switch serials for non-template n...
Implement the Python class `Override1Model` described below. Class description: Implementation of the 'Override1' model. TODO: type model description here. Attributes: switch_profiles (list of string): List of switch profiles ids for template network switches (list of string): List of switch serials for non-template n...
9894089eb013318243ae48869cc5130eb37f80c0
<|skeleton|> class Override1Model: """Implementation of the 'Override1' model. TODO: type model description here. Attributes: switch_profiles (list of string): List of switch profiles ids for template network switches (list of string): List of switch serials for non-template network stacks (list of string): List of...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Override1Model: """Implementation of the 'Override1' model. TODO: type model description here. Attributes: switch_profiles (list of string): List of switch profiles ids for template network switches (list of string): List of switch serials for non-template network stacks (list of string): List of switch stack...
the_stack_v2_python_sparse
meraki_sdk/models/override_1_model.py
RaulCatalano/meraki-python-sdk
train
1
8a80e3f9249f3fae3b1e26d093550f08fc1aae47
[ "max_idx = nums.index(max(nums))\nfor idx, x in enumerate(nums):\n if idx != max_idx:\n if nums[max_idx] < 2 * x:\n return -1\nreturn max_idx", "m = max(nums)\nif all((m >= 2 * x for x in nums if x != m)):\n return nums.index(m)\nreturn -1" ]
<|body_start_0|> max_idx = nums.index(max(nums)) for idx, x in enumerate(nums): if idx != max_idx: if nums[max_idx] < 2 * x: return -1 return max_idx <|end_body_0|> <|body_start_1|> m = max(nums) if all((m >= 2 * x for x in nums if...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def dominant_index(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def dominantIndex(self, nums): """any(iterable, /) Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False. all(iterable, /) Return T...
stack_v2_sparse_classes_75kplus_train_067294
846
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "dominant_index", "signature": "def dominant_index(self, nums)" }, { "docstring": "any(iterable, /) Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False. all(iterable, /) Return True if bool(x...
2
stack_v2_sparse_classes_30k_train_041620
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def dominant_index(self, nums): :type nums: List[int] :rtype: int - def dominantIndex(self, nums): any(iterable, /) Return True if bool(x) is True for any x in the iterable. If t...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def dominant_index(self, nums): :type nums: List[int] :rtype: int - def dominantIndex(self, nums): any(iterable, /) Return True if bool(x) is True for any x in the iterable. If t...
cc7740026c3774be21ab924b99ae7596ef20d0e4
<|skeleton|> class Solution: def dominant_index(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def dominantIndex(self, nums): """any(iterable, /) Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False. all(iterable, /) Return T...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def dominant_index(self, nums): """:type nums: List[int] :rtype: int""" max_idx = nums.index(max(nums)) for idx, x in enumerate(nums): if idx != max_idx: if nums[max_idx] < 2 * x: return -1 return max_idx def domina...
the_stack_v2_python_sparse
data_structure/arrays_and_strings/747_dominant_index.py
yangtao0304/hands-on-programming-exercise
train
0
d5a55efd4830497d20281ac9a049b8c32ce863c2
[ "data = {'ok': False, 'message': exception.message}\nresult = dumps(data) + '\\n'\nresp = make_response(result, exception.code)\nresp.headers['Content-Type'] = self.content_type\nreturn resp", "method = getattr(self, request.method.lower(), None)\nif method is None and request.method == 'HEAD':\n method = geta...
<|body_start_0|> data = {'ok': False, 'message': exception.message} result = dumps(data) + '\n' resp = make_response(result, exception.code) resp.headers['Content-Type'] = self.content_type return resp <|end_body_0|> <|body_start_1|> method = getattr(self, request.method...
自定义 View 类 json 序列化,异常处理,装饰器支持
RestView
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RestView: """自定义 View 类 json 序列化,异常处理,装饰器支持""" def handler_error(self, exception): """处理异常""" <|body_0|> def dispatch_request(self, *args, **kwargs): """重写父类方法,支持数据自动序列化""" <|body_1|> def unpack(value): """解析视图方法返回值""" <|body_2|> <|e...
stack_v2_sparse_classes_75kplus_train_067295
3,102
permissive
[ { "docstring": "处理异常", "name": "handler_error", "signature": "def handler_error(self, exception)" }, { "docstring": "重写父类方法,支持数据自动序列化", "name": "dispatch_request", "signature": "def dispatch_request(self, *args, **kwargs)" }, { "docstring": "解析视图方法返回值", "name": "unpack", ...
3
stack_v2_sparse_classes_30k_train_036454
Implement the Python class `RestView` described below. Class description: 自定义 View 类 json 序列化,异常处理,装饰器支持 Method signatures and docstrings: - def handler_error(self, exception): 处理异常 - def dispatch_request(self, *args, **kwargs): 重写父类方法,支持数据自动序列化 - def unpack(value): 解析视图方法返回值
Implement the Python class `RestView` described below. Class description: 自定义 View 类 json 序列化,异常处理,装饰器支持 Method signatures and docstrings: - def handler_error(self, exception): 处理异常 - def dispatch_request(self, *args, **kwargs): 重写父类方法,支持数据自动序列化 - def unpack(value): 解析视图方法返回值 <|skeleton|> class RestView: """自定义 ...
655bb48711537efb7856a50dcab55f2380ea127a
<|skeleton|> class RestView: """自定义 View 类 json 序列化,异常处理,装饰器支持""" def handler_error(self, exception): """处理异常""" <|body_0|> def dispatch_request(self, *args, **kwargs): """重写父类方法,支持数据自动序列化""" <|body_1|> def unpack(value): """解析视图方法返回值""" <|body_2|> <|e...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RestView: """自定义 View 类 json 序列化,异常处理,装饰器支持""" def handler_error(self, exception): """处理异常""" data = {'ok': False, 'message': exception.message} result = dumps(data) + '\n' resp = make_response(result, exception.code) resp.headers['Content-Type'] = self.content_typ...
the_stack_v2_python_sparse
rmon/common/rest.py
lvsoso/rmon
train
0
46c1bf38178e10091bce874178c79c8292b3cf46
[ "event = {'event': 'pause'}\nredis.publish(config.PLAYER_CHANNEL, json.dumps(event))\nreturn http.Created(event)", "event = {'event': 'resume'}\nredis.publish(config.PLAYER_CHANNEL, json.dumps(event))\nreturn http.OK(event)" ]
<|body_start_0|> event = {'event': 'pause'} redis.publish(config.PLAYER_CHANNEL, json.dumps(event)) return http.Created(event) <|end_body_0|> <|body_start_1|> event = {'event': 'resume'} redis.publish(config.PLAYER_CHANNEL, json.dumps(event)) return http.OK(event) <|end_...
The pause resources allows the payer to paused and unpaused via POST for pause and DELTETE to unpause the player.
PauseView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PauseView: """The pause resources allows the payer to paused and unpaused via POST for pause and DELTETE to unpause the player.""" def post(self): """Pauses the player.""" <|body_0|> def delete(self): """Unapuses the player.""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_75kplus_train_067296
12,943
no_license
[ { "docstring": "Pauses the player.", "name": "post", "signature": "def post(self)" }, { "docstring": "Unapuses the player.", "name": "delete", "signature": "def delete(self)" } ]
2
stack_v2_sparse_classes_30k_train_017598
Implement the Python class `PauseView` described below. Class description: The pause resources allows the payer to paused and unpaused via POST for pause and DELTETE to unpause the player. Method signatures and docstrings: - def post(self): Pauses the player. - def delete(self): Unapuses the player.
Implement the Python class `PauseView` described below. Class description: The pause resources allows the payer to paused and unpaused via POST for pause and DELTETE to unpause the player. Method signatures and docstrings: - def post(self): Pauses the player. - def delete(self): Unapuses the player. <|skeleton|> cla...
817766c6d2e2660291b723274d345ce5eb40ab77
<|skeleton|> class PauseView: """The pause resources allows the payer to paused and unpaused via POST for pause and DELTETE to unpause the player.""" def post(self): """Pauses the player.""" <|body_0|> def delete(self): """Unapuses the player.""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PauseView: """The pause resources allows the payer to paused and unpaused via POST for pause and DELTETE to unpause the player.""" def post(self): """Pauses the player.""" event = {'event': 'pause'} redis.publish(config.PLAYER_CHANNEL, json.dumps(event)) return http.Create...
the_stack_v2_python_sparse
fm/views/player.py
thisissoon/FM-API
train
3
1851520e5358f6e3556853cb985294009951490d
[ "crc = Crc(g32)\nstr_rep = 'poly = 0x104C11DB7\\nreverse = True\\ninitCrc = 0xFFFFFFFF\\nxorOut = 0x00000000\\ncrcValue = 0xFFFFFFFF'\nself.assertEqual(str(crc), str_rep)\nself.assertEqual(crc.digest(), b'\\xff\\xff\\xff\\xff')\nself.assertEqual(crc.hexdigest(), 'FFFFFFFF')\ncrc.update(self.msg)\nself.assertEqua...
<|body_start_0|> crc = Crc(g32) str_rep = 'poly = 0x104C11DB7\nreverse = True\ninitCrc = 0xFFFFFFFF\nxorOut = 0x00000000\ncrcValue = 0xFFFFFFFF' self.assertEqual(str(crc), str_rep) self.assertEqual(crc.digest(), b'\xff\xff\xff\xff') self.assertEqual(crc.hexdigest(), 'FFFFFFFF'...
Verify the Crc class
CrcClassTest
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CrcClassTest: """Verify the Crc class""" def test_simple_crc32_class(self): """Verify the CRC class when not using xorOut""" <|body_0|> def test_full_crc32_class(self): """Verify the CRC class when using xorOut""" <|body_1|> <|end_skeleton|> <|body_star...
stack_v2_sparse_classes_75kplus_train_067297
18,433
permissive
[ { "docstring": "Verify the CRC class when not using xorOut", "name": "test_simple_crc32_class", "signature": "def test_simple_crc32_class(self)" }, { "docstring": "Verify the CRC class when using xorOut", "name": "test_full_crc32_class", "signature": "def test_full_crc32_class(self)" }...
2
stack_v2_sparse_classes_30k_train_043082
Implement the Python class `CrcClassTest` described below. Class description: Verify the Crc class Method signatures and docstrings: - def test_simple_crc32_class(self): Verify the CRC class when not using xorOut - def test_full_crc32_class(self): Verify the CRC class when using xorOut
Implement the Python class `CrcClassTest` described below. Class description: Verify the Crc class Method signatures and docstrings: - def test_simple_crc32_class(self): Verify the CRC class when not using xorOut - def test_full_crc32_class(self): Verify the CRC class when using xorOut <|skeleton|> class CrcClassTes...
53102de187a48ac2cfc241fef54dcbc29c453a8e
<|skeleton|> class CrcClassTest: """Verify the Crc class""" def test_simple_crc32_class(self): """Verify the CRC class when not using xorOut""" <|body_0|> def test_full_crc32_class(self): """Verify the CRC class when using xorOut""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CrcClassTest: """Verify the Crc class""" def test_simple_crc32_class(self): """Verify the CRC class when not using xorOut""" crc = Crc(g32) str_rep = 'poly = 0x104C11DB7\nreverse = True\ninitCrc = 0xFFFFFFFF\nxorOut = 0x00000000\ncrcValue = 0xFFFFFFFF' self.assertEqual(...
the_stack_v2_python_sparse
third_party/gsutil/third_party/crcmod/python3/crcmod/test.py
catapult-project/catapult
train
2,032
700f976c1465bfdf9256c7a2e2cc916226e22762
[ "q = []\nfor x, y in points:\n heapq.heappush(q, (math.sqrt(x ** 2 + y ** 2), x, y))\nclosest = [[x, y] for _, x, y in heapq.nsmallest(k, q)]\nreturn closest", "q = []\nfor x, y in points:\n if len(q) < k:\n heapq.heappush(q, (-math.sqrt(x ** 2 + y ** 2), x, y))\n else:\n distance = math.sq...
<|body_start_0|> q = [] for x, y in points: heapq.heappush(q, (math.sqrt(x ** 2 + y ** 2), x, y)) closest = [[x, y] for _, x, y in heapq.nsmallest(k, q)] return closest <|end_body_0|> <|body_start_1|> q = [] for x, y in points: if len(q) < k: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: """O(N*log(N)) Solution""" <|body_0|> def kClosest2(self, points: List[List[int]], k: int) -> List[List[int]]: """O(N*log(K)) Solution""" <|body_1|> <|end_skeleton|> <|body_st...
stack_v2_sparse_classes_75kplus_train_067298
916
no_license
[ { "docstring": "O(N*log(N)) Solution", "name": "kClosest", "signature": "def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]" }, { "docstring": "O(N*log(K)) Solution", "name": "kClosest2", "signature": "def kClosest2(self, points: List[List[int]], k: int) -> List[List[...
2
stack_v2_sparse_classes_30k_test_000354
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: O(N*log(N)) Solution - def kClosest2(self, points: List[List[int]], k: int) -> List[List[int]]: O(N*log(K)...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: O(N*log(N)) Solution - def kClosest2(self, points: List[List[int]], k: int) -> List[List[int]]: O(N*log(K)...
b72229c50e87d1ff32d3538d13779953451b9daf
<|skeleton|> class Solution: def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: """O(N*log(N)) Solution""" <|body_0|> def kClosest2(self, points: List[List[int]], k: int) -> List[List[int]]: """O(N*log(K)) Solution""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: """O(N*log(N)) Solution""" q = [] for x, y in points: heapq.heappush(q, (math.sqrt(x ** 2 + y ** 2), x, y)) closest = [[x, y] for _, x, y in heapq.nsmallest(k, q)] return close...
the_stack_v2_python_sparse
leetcode/K Closest Points to Origin/main.py
dalleng/Interview-Practice
train
2
b5de5853d5b005b2134dc53a25d517a1763c575e
[ "values = list(map(str.strip, values))\nfor col in cls.boolean_columns:\n mapping = {'yes': True, 'no': False}\n try:\n values[col] = mapping[values[col].lower()]\n except KeyError:\n raise ValueError(\"Invalid value for boolean column '{}'\".format(values[col]))\nfor col in cls.int_columns:\...
<|body_start_0|> values = list(map(str.strip, values)) for col in cls.boolean_columns: mapping = {'yes': True, 'no': False} try: values[col] = mapping[values[col].lower()] except KeyError: raise ValueError("Invalid value for boolean col...
Class to represent a row in the CSV file that corresponds to a dataset
Dataset
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dataset: """Class to represent a row in the CSV file that corresponds to a dataset""" def from_strings(cls, values): """Instantiate a Dataset object from a line of the CSV file, and convert Yes/No to True/False""" <|body_0|> def get_dict(self): """Return a dictio...
stack_v2_sparse_classes_75kplus_train_067299
3,919
no_license
[ { "docstring": "Instantiate a Dataset object from a line of the CSV file, and convert Yes/No to True/False", "name": "from_strings", "signature": "def from_strings(cls, values)" }, { "docstring": "Return a dictionary that contains metadata about the dataset for this row and its data files", ...
2
stack_v2_sparse_classes_30k_train_031203
Implement the Python class `Dataset` described below. Class description: Class to represent a row in the CSV file that corresponds to a dataset Method signatures and docstrings: - def from_strings(cls, values): Instantiate a Dataset object from a line of the CSV file, and convert Yes/No to True/False - def get_dict(s...
Implement the Python class `Dataset` described below. Class description: Class to represent a row in the CSV file that corresponds to a dataset Method signatures and docstrings: - def from_strings(cls, values): Instantiate a Dataset object from a line of the CSV file, and convert Yes/No to True/False - def get_dict(s...
e376d650ecd7da2938d1b49215fdd945b8395d13
<|skeleton|> class Dataset: """Class to represent a row in the CSV file that corresponds to a dataset""" def from_strings(cls, values): """Instantiate a Dataset object from a line of the CSV file, and convert Yes/No to True/False""" <|body_0|> def get_dict(self): """Return a dictio...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Dataset: """Class to represent a row in the CSV file that corresponds to a dataset""" def from_strings(cls, values): """Instantiate a Dataset object from a line of the CSV file, and convert Yes/No to True/False""" values = list(map(str.strip, values)) for col in cls.boolean_column...
the_stack_v2_python_sparse
esacci_esgf/input/merge_csv_json.py
cedadev/esacci-esgf
train
1